r3277 - in trunk: . lima-business lima-business/src/main/java/org/chorem/lima/business lima-business/src/main/java/org/chorem/lima/business/ejb lima-business/src/main/java/org/chorem/lima/business/ejbinterface lima-business/src/main/java/org/chorem/lima/business/utils lima-business/src/main/resources lima-business/src/main/resources/i18n lima-business/src/test/java/org/chorem/lima/business lima-callao lima-swing lima-swing/src/main/java/org/chorem/lima lima-swing/src/main/java/org/chorem/lima
Author: tchemit Date: 2011-08-16 16:08:32 +0200 (Tue, 16 Aug 2011) New Revision: 3277 Url: http://chorem.org/repositories/revision/lima/3277 Log: Anomalie #432: L'application en d?\195?\169marre pas! Evolution #433: Uniformisation des services Evolution #434: Meilleure gestion des configurations Anomalie #435: Le lien du site pour d?\195?\169marrer on-line ne fonctionne pas :( Modified: trunk/lima-business/pom.xml trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AbstractLimaService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AccountServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/DocumentServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryBookServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ExportServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialPeriodServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialStatementServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialTransactionServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FiscalPeriodServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/HttpServerServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/IdentityServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ImportServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/OptionsServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ReportServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/VatStatementServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/AccountService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/AccountServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/DocumentService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/DocumentServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/EntryBookService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/EntryBookServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ExportService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ExportServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialPeriodService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialPeriodServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialStatementService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialStatementServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialTransactionService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialTransactionServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FiscalPeriodService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FiscalPeriodServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/HttpServerService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/HttpServerServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/IdentityService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/IdentityServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ImportService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ImportServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/OptionsService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/OptionsServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ReportService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ReportServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/VatStatementService.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/VatStatementServiceLocal.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/DocumentsEnum.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FormatsEnum.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/ImportExportEntityEnum.java trunk/lima-business/src/main/resources/i18n/lima-business_en_GB.properties trunk/lima-business/src/main/resources/i18n/lima-business_fr_FR.properties trunk/lima-business/src/main/resources/lima.properties trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java trunk/lima-callao/pom.xml trunk/lima-swing/pom.xml trunk/lima-swing/src/main/java/org/chorem/lima/LimaConfig.java trunk/lima-swing/src/main/java/org/chorem/lima/service/LimaServiceFactory.java trunk/lima-swing/src/main/resources/i18n/lima-swing_en_GB.properties trunk/lima-swing/src/main/resources/i18n/lima-swing_fr_FR.properties trunk/lima-swing/src/main/resources/lima-config.properties trunk/pom.xml trunk/src/site/site_fr.xml Modified: trunk/lima-business/pom.xml =================================================================== --- trunk/lima-business/pom.xml 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/pom.xml 2011-08-16 14:08:32 UTC (rev 3277) @@ -7,7 +7,7 @@ <parent> <groupId>org.chorem</groupId> <artifactId>lima</artifactId> - <version>0.6-SNAPSHOT</version> + <version>0.5.1-SNAPSHOT</version> </parent> <groupId>org.chorem.lima</groupId> Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,18 +25,22 @@ package org.chorem.lima.business; -import static org.nuiton.i18n.I18n._; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.chorem.lima.business.accountingrules.DefaultAccountingRules; +import org.chorem.lima.business.accountingrules.FranceAccountingRules; import org.chorem.lima.business.migration.DatabaseMigrationClass; import org.chorem.lima.entity.LimaCallaoDAOHelper; +import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.migration.TopiaMigrationEngine; import org.nuiton.topia.migration.TopiaMigrationService; import org.nuiton.util.ApplicationConfig; import org.nuiton.util.ArgumentsParserException; +import java.io.File; + +import static org.nuiton.i18n.I18n._; + /** * Configuration pour le business. * @@ -86,16 +90,14 @@ public AccountingRules getAccountingRules() { if (accountingRules == null) { - Class accountingRulesClass = getOptionAsClass(Option.RULES_NATIONALTY.key); + Class<?> accountingRulesClass = getOptionAsClass(Option.RULES_NATIONALTY.key); if (accountingRulesClass == null) { accountingRules = new DefaultAccountingRules(); } else { try { accountingRules = (AccountingRules) accountingRulesClass.newInstance(); - } catch (InstantiationException e) { + } catch (Exception e) { log.error("Can't instantiate accounting rules", e); - } catch (IllegalAccessException e) { - e.printStackTrace(); } } } @@ -103,9 +105,13 @@ return accountingRules; } - - public String getReportsDir(){ - String reportsDir = getOption(Option.REPORTS_DIR.getKey()); + public File getDataDir() { + File datadir = getOptionAsFile(Option.DATA_DIR.getKey()); + return datadir; + } + + public File getReportsDir(){ + File reportsDir = getOptionAsFile(Option.REPORTS_DIR.getKey()); return reportsDir; } @@ -154,7 +160,8 @@ log.error("Can't read configuration", ex); } } - instance.setOption("topia.persistence.classes", LimaCallaoDAOHelper.getImplementationClassesAsString()); + instance.setOption(TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES, + LimaCallaoDAOHelper.getImplementationClassesAsString()); } /** @@ -164,15 +171,16 @@ * information for jaxx configuration frame ({@link #type}, * {@link #transientBoolean}, {@link #finalBoolean}...) */ - public static enum Option implements OptionDef { + public enum Option implements OptionDef { CONFIG_FILE(CONFIG_FILE_NAME, _("lima.config.configFileName.description"), "lima-config.properties", String.class, true, true), - RULES_NATIONALTY("lima.rules", _("lima.config.rulesnationality"), "default", String.class, false, false), - REPORTS_DIR("lima.report.dir", _("lima.config.reportsdir"), "", String.class, false, false), - HTTP_PORT("lima.httpport", _("lima.config.httpport"), "5462", String.class, false, false), - SERVER_ADRESS("lima.serveraddress", _("lima.config.serveraddress"), "", String.class, false, false), - SCALE("lima.scale", _("lima.config.scale"), "2", String.class, false, false), - VAT_PDF_URL("lima.report.vatpdfurl", _("lima.config.reportvatpdfurl"), "default", String.class, false, false); + DATA_DIR("lima.data.dir", _("lima.config.data.dir.description"), "${user.home}/.lima", File.class, false, false), + REPORTS_DIR("lima.reports.dir", _("lima.config.reports.dir.description"), "${lima.data.dir}/reports", File.class, false, false), + RULES_NATIONALTY("lima.rules", _("lima.config.rulesnationality.description"), FranceAccountingRules.class.getName(), String.class, false, false), + HTTP_PORT("lima.httpport", _("lima.config.httpport.description"), "5462", String.class, false, false), + SERVER_ADRESS("lima.serveraddress", _("lima.config.serveraddress.description"), "", String.class, false, false), + SCALE("lima.scale", _("lima.config.scale.description"), "2", String.class, false, false), + VAT_PDF_URL("lima.report.vatpdfurl", _("lima.config.reportvatpdfurl.description"), "default", String.class, false, false); private final String key; private final String description; @@ -181,7 +189,7 @@ private boolean transientBoolean; private boolean finalBoolean; - private Option(String key, String description, String defaultValue, + Option(String key, String description, String defaultValue, Class<?> type, boolean transientBoolean, boolean finalBoolean) { this.key = key; this.description = description; Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AbstractLimaService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AbstractLimaService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AbstractLimaService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,33 +25,54 @@ package org.chorem.lima.business.ejb; -import static org.nuiton.i18n.I18n._; - import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaNotFoundException; +import org.nuiton.topia.TopiaRuntimeException; +import java.util.Properties; + +import static org.nuiton.i18n.I18n._; + /** * TODO add comment here. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ public abstract class AbstractLimaService { + /** Logger. */ + protected final Log log = LogFactory.getLog(getClass()); + + protected static TopiaContext acquireRootContext() { + try { + LimaConfig config = LimaConfig.getInstance(); + Properties options = config.getFlatOptions(); + return TopiaContextFactory.getContext(options); + } catch (TopiaNotFoundException ex) { + throw new TopiaRuntimeException("Could not acquire root context", ex); + } + } + /** * Generic code used to rollback a transaction. - * + * <p/> * TODO : replace this by JTA - * + * * @throws LimaException */ - protected void doCatch(TopiaContext transaction, Exception cause, Log log) throws LimaException { - if (cause instanceof LimaException){ + protected void doCatch(TopiaContext transaction, + Exception cause) throws LimaException { + if (cause instanceof LimaException) { throw (LimaException) cause; } if (transaction != null) { @@ -68,24 +89,49 @@ } throw new LimaException(_("lima-business.common.queryerror"), cause); } - + /** * Generic code used too close a transaction. - * + * * @param transaction transaction to close - * @param log log (can be null) * @throws LimaException */ - protected void doFinally(TopiaContext transaction, Log log) throws LimaException { + protected void doFinally(TopiaContext transaction) throws LimaException { if (transaction != null) { try { transaction.closeContext(); } catch (TopiaException ex) { - if (log != null && log.isErrorEnabled()) { + if (log.isErrorEnabled()) { log.error("Can't close transaction", ex); } - throw new LimaException(_("lima-business.common.transactionerror", ex)); + throw new LimaException(_("lima-business.common.close.transactionerror", ex)); } } } + + protected TopiaContext beginTransaction(TopiaContext rootContext) throws LimaException { + if (rootContext == null) { + throw new NullPointerException("rootContext can not be null"); + } + // basic check done, make check in database + // TODO move it into JTA + try { + TopiaContext topiaContext = rootContext.beginTransaction(); + log.trace("beginTransaction" + topiaContext); + return topiaContext; + } catch (TopiaException e) { + throw new LimaException(_("lima-business.common.open.transactionerror", e)); + } + } + + protected void commitTransaction(TopiaContext topiaContext) throws LimaException { + try { + topiaContext.commitTransaction(); + } catch (TopiaException eee) { + if (log.isErrorEnabled()) { + log.error("Error during commit context", eee); + } + throw new LimaException(_("lima-business.common.commit.transactionerror", eee)); + } + } } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AccountServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AccountServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AccountServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,13 +25,6 @@ package org.chorem.lima.business.ejb; -import static org.nuiton.i18n.I18n._; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import javax.ejb.Stateless; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.business.AccountingRules; import org.chorem.lima.business.LimaBusinessException; import org.chorem.lima.business.LimaConfig; @@ -43,11 +36,16 @@ import org.chorem.lima.entity.AccountDAO; import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; +import javax.ejb.Stateless; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.nuiton.i18n.I18n._; + /** * Permet d'implémenter le Plan Comptable Général. * Un compte ne peut être supprimé si il contient des écritures comptables. @@ -59,123 +57,112 @@ @Stateless public class AccountServiceImpl extends AbstractLimaService implements AccountService, AccountServiceLocal { - private static final Log log = - LogFactory.getLog(AccountServiceImpl.class); - private TopiaContext rootContext; protected AccountingRules accountingRules; - + public AccountServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - accountingRules = config.getAccountingRules(); + rootContext = acquireRootContext(); + accountingRules = LimaConfig.getInstance().getAccountingRules(); } - @Override - public void createAccountWithTransaction(Account masterAccount, Account account, TopiaContext topiaContext) throws LimaException { - + public void createAccountWithTransaction(Account masterAccount, + Account account, + TopiaContext topiaContext) throws LimaException { + try { // force upppercase account number account.setAccountNumber(account.getAccountNumber().toUpperCase()); - + // check if account number already exist AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(topiaContext); - + LimaCallaoDAOHelper.getAccountDAO(topiaContext); + Account existAccount = - accountDAO.findByAccountNumber(account.getAccountNumber()); - if (existAccount != null) { + accountDAO.findByAccountNumber(account.getAccountNumber()); + if (existAccount != null) { throw new LimaBusinessException(_("lima-business.account.accountalreardyexist", account.getAccountNumber())); } - + //create it accountDAO.create(account); - + Account masterAccountUpdate = null; - if (masterAccount != null){ + if (masterAccount != null) { masterAccountUpdate = accountDAO.findByAccountNumber(masterAccount.getAccountNumber()); } - + // check if parent account exist; if (masterAccountUpdate != null) { masterAccountUpdate.addSubAccounts(account); accountDAO.update(masterAccountUpdate); } - + commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } } - - + + /** * Permet de créer un nouveau compte dans le PCG de l'application. * ATTENTION : le compte masterAccount, c'est à dire le compte père, doit * exister, sinon le compte n'est pas créé. Si le compte n'a pas de père, alors * mettre masterAccount à null. - * + * * @param account account to create * @throws LimaException */ @Override - public void createAccount(Account masterAccount, Account account) throws LimaException { - + public void createAccount(Account masterAccount, + Account account) throws LimaException { + //check rules before create the account accountingRules.createAccountRules(masterAccount, account); - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); createAccountWithTransaction(masterAccount, account, transaction); - + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - - + + @Override - public void createSubLedgerWithTransaction(Account masterAccount, Account account, TopiaContext topiaContext) throws LimaException { + public void createSubLedgerWithTransaction(Account masterAccount, + Account account, + TopiaContext topiaContext) throws LimaException { try { - + // force upppercase account number account.setAccountNumber(account.getAccountNumber().toUpperCase()); - + // check if the accountnumber already exist AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(topiaContext); + LimaCallaoDAOHelper.getAccountDAO(topiaContext); Account existAccount = - accountDAO.findByAccountNumber(account.getAccountNumber()); + accountDAO.findByAccountNumber(account.getAccountNumber()); if (existAccount != null) { throw new LimaBusinessException(_( - "lima-business.account.accountalreardyexist", - account.getAccountNumber())); - } - + "lima-business.account.accountalreardyexist", + account.getAccountNumber())); + } + //create it accountDAO.create(account); - + Account masterAccountUpdate = null; - if (masterAccount != null){ + if (masterAccount != null) { masterAccountUpdate = accountDAO.findByAccountNumber(masterAccount.getAccountNumber()); } - + // check if the masteraccount exist; if (masterAccount != null) { masterAccountUpdate.addSubLedgers(account); @@ -183,162 +170,134 @@ } commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } } - - /** - * Permet de créer des comptes tiers - */ + + /** Permet de créer des comptes tiers */ @Override - public void createSubLedger(Account masterAccount, Account account) - throws LimaException { + public void createSubLedger(Account masterAccount, + Account account) throws LimaException { //check rules before create the account accountingRules.createSubLedgerRules(masterAccount, account); - - TopiaContext transaction = null; - try { - transaction = beginTransaction(); + TopiaContext transaction = beginTransaction(rootContext); + try { createSubLedgerWithTransaction(masterAccount, account, transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + } - - /** - * Permer d'obtenir la liste des comptes à partir d'une de ses propriétés - */ + + /** Permer d'obtenir la liste des comptes à partir d'une de ses propriétés */ @Override - public List<Account> getAllAccountByProperty(String propertyName, String value) throws LimaException { + public List<Account> getAllAccountByProperty(String propertyName, + String value) throws LimaException { List<Account> account = null; - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - + AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(transaction); + LimaCallaoDAOHelper.getAccountDAO(transaction); account = accountDAO.findAllByProperty(propertyName, value); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return account; } - - /** - * Permet d'obtenir un compte suivant son numero - */ + + /** Permet d'obtenir un compte suivant son numero */ @Override public Account getAccountByNumber(String number) throws LimaException { - - List<Account> accountsList = new ArrayList<Account>(); - accountsList = getAllAccountByProperty(Account.ACCOUNT_NUMBER, number); - + + List<Account> accountsList = getAllAccountByProperty( + Account.ACCOUNT_NUMBER, number); + + Account account = null; if (accountsList.size() > 0) { - return accountsList.get(0); - } else { - return null; + account = accountsList.get(0); } - + return account; } - /** - * Permet d'obtenir tous les comptes. - */ + /** Permet d'obtenir tous les comptes. */ @Override public List<Account> getAllAccounts() throws LimaException { - + List<Account> accountsList = new ArrayList<Account>(); - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(transaction); + LimaCallaoDAOHelper.getAccountDAO(transaction); accountsList = accountDAO.findAll(); Collections.sort(accountsList, new AccountComparator()); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return accountsList; } - - - /** Permet d'obtenir tout les comptes feuilles - */ + + + /** Permet d'obtenir tout les comptes feuilles */ @Override public List<Account> getAllSubAccounts() throws LimaException { List<Account> accountsList = null; - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(transaction); + LimaCallaoDAOHelper.getAccountDAO(transaction); accountsList = accountDAO.findAllSubAccounts(); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return accountsList; } - + /** * Permet de recuperer la liste des comptes fils d'un compte en particulier. - * + * * @param masterAccount (can be null) * @return - * @throws LimaException + * @throws LimaException */ @Override public List<Account> getChildrenAccounts(Account masterAccount) throws LimaException { - + List<Account> accountsList = new ArrayList<Account>(); - - TopiaContext transaction = null; - try { - transaction = beginTransaction(); + TopiaContext transaction = beginTransaction(rootContext); + try { AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(transaction); + LimaCallaoDAOHelper.getAccountDAO(transaction); TopiaQuery query = accountDAO.createQuery(); - if (masterAccount == null){ + if (masterAccount == null) { query.addEquals("masterAccount", masterAccount); - query.addWhere("generalLedger", TopiaQuery.Op.EQ, null); - } - else { + query.addWhere("generalLedger", TopiaQuery.Op.EQ, null); + } else { query.addWhere("masterAccount = :value or generalLedger = :value") - .addParam("value", masterAccount); + .addParam("value", masterAccount); } accountsList.addAll(accountDAO.findAllByQuery(query)); Collections.sort(accountsList, new AccountComparator()); @@ -353,24 +312,21 @@ t.sizeSubAccounts(); t.sizeSubLedgers(); } - + + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return accountsList; } - - /** - * Get list of all subaccount and ledger of an account - */ + + /** Get list of all subaccount and ledger of an account */ @Override - public List<Account> getAllChildrenAccounts(Account masterAccount, List<Account> accounts) throws LimaException { - + public List<Account> getAllChildrenAccounts(Account masterAccount, + List<Account> accounts) throws LimaException { + List<Account> childAccounts = getChildrenAccounts(masterAccount); accounts.addAll(childAccounts); for (Account account : childAccounts) { @@ -378,137 +334,106 @@ } return accounts; } - + /** * Permet d'effacer un compte dans la base de données. - * + * <p/> * Si il existe une entrée comptable associée au numéro de * compte ou a un de ses sous-compte, il est alors impossible de supprimer le compte. - * + * * @param account - * @throws LimaException + * @throws LimaException */ @Override public void removeAccount(Account account) throws LimaException { - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(transaction); - + LimaCallaoDAOHelper.getAccountDAO(transaction); + // Check rules for account if have entries accountingRules.removeAccountRules(account, transaction); - + // remove account Account accountToDelete = accountDAO.findByTopiaId(account.getTopiaId()); - + //get all subaccounts List<Account> accounts = - getAllChildrenAccounts(accountToDelete, new ArrayList<Account>()); + getAllChildrenAccounts(accountToDelete, new ArrayList<Account>()); //if account have sub accounts - if (accounts.size() > 0){ + if (accounts.size() > 0) { for (Account subAccount : accounts) { // Check rules for subaccount if have entries accountingRules.removeAccountRules(subAccount, transaction); Account subAccountToDelete = - accountDAO.findByTopiaId(subAccount.getTopiaId()); + accountDAO.findByTopiaId(subAccount.getTopiaId()); accountDAO.delete(subAccountToDelete); } } - + accountDAO.delete(accountToDelete); //commit commitTransaction(transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } @Override - public void removeAllAccount() throws LimaException{ + public void removeAllAccount() throws LimaException { List<Account> accounts = getChildrenAccounts(null); for (Account account : accounts) { removeAccount(account); } } - - + + /** * Permet de modifier un compte sur son label et son compte père. - * + * <p/> * Il n'est pas possible de modifier un numéro de compte. * Si le compte n'existe pas, il envoie alors un message d'avertissement. - * + * * @param account compte à modifier - - * @throws LimaException + * @throws LimaException */ @Override public void updateAccount(Account account) throws LimaException { - - TopiaContext transaction = null; - + + TopiaContext transaction = beginTransaction(rootContext); + try { - transaction = beginTransaction(); - // DAO AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(transaction); + LimaCallaoDAOHelper.getAccountDAO(transaction); Account subAccount = accountDAO.findByTopiaId(account.getTopiaId()); //check rules account if ledger or account if (account.getGeneralLedger() == null) { // is an account - + Account master = account.getMasterAccount(); - + accountingRules.updateAccountRules(master, account); subAccount.setMasterAccount(account.getMasterAccount()); subAccount.setSubAccounts(account.getSubAccounts()); - } - else { // is a ledger + } else { // is a ledger accountingRules.updateSubLedgerRules(account); subAccount.setGeneralLedger(account.getGeneralLedger()); subAccount.setSubLedgers(account.getSubLedgers()); subAccount.setThirdParty(account.getThirdParty()); } - + // update account subAccount.setAccountNumber(account.getAccountNumber()); subAccount.setLabel(account.getLabel()); accountDAO.update(subAccount); commitTransaction(transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - - - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } - - protected void commitTransaction(TopiaContext topiaTransaction) throws TopiaException { - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } - } \ No newline at end of file Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/DocumentServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/DocumentServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/DocumentServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,28 +25,21 @@ package org.chorem.lima.business.ejb; -import static org.nuiton.i18n.I18n._; - -import java.awt.Color; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.ejb.EJB; -import javax.ejb.Stateless; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import com.lowagie.text.BadElementException; +import com.lowagie.text.Cell; +import com.lowagie.text.Chapter; +import com.lowagie.text.Document; +import com.lowagie.text.DocumentException; +import com.lowagie.text.Element; +import com.lowagie.text.Font; +import com.lowagie.text.PageSize; +import com.lowagie.text.Paragraph; +import com.lowagie.text.Phrase; +import com.lowagie.text.Rectangle; +import com.lowagie.text.Table; +import com.lowagie.text.html.HtmlWriter; +import com.lowagie.text.pdf.PdfWriter; import org.apache.pdfbox.examples.fdf.SetField; -import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.PDDocument; import org.chorem.lima.beans.BalanceTrial; import org.chorem.lima.beans.FinancialStatementAmounts; @@ -57,10 +50,10 @@ import org.chorem.lima.business.LimaException; import org.chorem.lima.business.ejbinterface.DocumentService; import org.chorem.lima.business.ejbinterface.DocumentServiceLocal; -import org.chorem.lima.business.ejbinterface.FinancialStatementService; -import org.chorem.lima.business.ejbinterface.IdentityService; -import org.chorem.lima.business.ejbinterface.ReportService; -import org.chorem.lima.business.ejbinterface.VatStatementService; +import org.chorem.lima.business.ejbinterface.FinancialStatementServiceLocal; +import org.chorem.lima.business.ejbinterface.IdentityServiceLocal; +import org.chorem.lima.business.ejbinterface.ReportServiceLocal; +import org.chorem.lima.business.ejbinterface.VatStatementServiceLocal; import org.chorem.lima.business.utils.DocumentsEnum; import org.chorem.lima.business.utils.EntryComparator; import org.chorem.lima.business.utils.FormatsEnum; @@ -77,149 +70,149 @@ import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.chorem.lima.entity.VatStatement; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; import org.nuiton.topia.framework.TopiaQuery.Op; -import com.lowagie.text.BadElementException; -import com.lowagie.text.Cell; -import com.lowagie.text.Chapter; -import com.lowagie.text.Document; -import com.lowagie.text.DocumentException; -import com.lowagie.text.Element; -import com.lowagie.text.Font; -import com.lowagie.text.PageSize; -import com.lowagie.text.Paragraph; -import com.lowagie.text.Phrase; -import com.lowagie.text.Rectangle; -import com.lowagie.text.Table; -import com.lowagie.text.html.HtmlWriter; -import com.lowagie.text.pdf.PdfWriter; +import javax.ejb.EJB; +import javax.ejb.Stateless; +import java.awt.Color; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import static org.nuiton.i18n.I18n._; + @Stateless -public class DocumentServiceImpl implements DocumentService, DocumentServiceLocal { +public class DocumentServiceImpl extends AbstractLimaService implements DocumentService, DocumentServiceLocal { - private static final Log log = - LogFactory.getLog(DocumentServiceImpl.class); - private TopiaContext rootContext; - + //Services @EJB - private IdentityService identityService; - + private IdentityServiceLocal identityService; + @EJB - private FinancialStatementService financialStatementService; - + private FinancialStatementServiceLocal financialStatementService; + @EJB - private ReportService reportService; - + private ReportServiceLocal reportService; + @EJB - private VatStatementService vatStatementService; - + private VatStatementServiceLocal vatStatementService; + protected String path; - + //SDFs - private static SimpleDateFormat dateFormat = - new SimpleDateFormat("dd/MM/yyyy"); - private static SimpleDateFormat hourFormat = - new SimpleDateFormat("HH:mm"); - private static SimpleDateFormat filedateFormat = - new SimpleDateFormat("dd-MM-yyyy_HH-mm"); - private static SimpleDateFormat monthYearFormat = - new SimpleDateFormat("MMM yyyy"); - + private static final SimpleDateFormat dateFormat = + new SimpleDateFormat("dd/MM/yyyy"); + + private static final SimpleDateFormat hourFormat = + new SimpleDateFormat("HH:mm"); + +// private static final SimpleDateFormat filedateFormat = +// new SimpleDateFormat("dd-MM-yyyy_HH-mm"); + + private static final SimpleDateFormat monthYearFormat = + new SimpleDateFormat("MMM yyyy"); + //FONTs - private static Font titleFont = - new Font(Font.HELVETICA, 14, Font.BOLD, Color.BLACK); - private static Font normalFont = - new Font(Font.HELVETICA, 9, Font.NORMAL, Color.BLACK); - private static Font boldFont = - new Font(Font.HELVETICA, 9, Font.BOLD, Color.BLACK); - private static Font italicFont = - new Font(Font.HELVETICA, 9, Font.ITALIC, Color.BLACK); - private static Font bolditalicFont = - new Font(Font.HELVETICA, 9, Font.BOLDITALIC, Color.BLACK); - - - + private static final Font titleFont = + new Font(Font.HELVETICA, 14, Font.BOLD, Color.BLACK); + + private static final Font normalFont = + new Font(Font.HELVETICA, 9, Font.NORMAL, Color.BLACK); + + private static final Font boldFont = + new Font(Font.HELVETICA, 9, Font.BOLD, Color.BLACK); + + private static final Font italicFont = + new Font(Font.HELVETICA, 9, Font.ITALIC, Color.BLACK); + + private static final Font bolditalicFont = + new Font(Font.HELVETICA, 9, Font.BOLDITALIC, Color.BLACK); + + public DocumentServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); + rootContext = acquireRootContext(); + path = LimaConfig.getInstance().getReportsDir().getAbsolutePath(); + } + + + public Paragraph createHeaderPage(String title, + Identity identity, + String beginDate, + String endDate) { + Paragraph paragraphHeaderPage = new Paragraph(); + Table t = null; try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } + + //define table + t = new Table(4, 5); + t.setWidth(100f); + float[] widths = {0.25f, 0.45f, 0.12f, 0.18f}; + t.setWidths(widths); + t.setPadding(1.5f); + + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.NO_BORDER); + t.setDefaultCell(cell); + + //line 1 + t.addCell(new Phrase(identity.getName(), bolditalicFont)); + Cell titleCell = new Cell(new Phrase(title, titleFont)); + titleCell.setVerticalAlignment(Element.ALIGN_MIDDLE); + titleCell.setHorizontalAlignment(Element.ALIGN_CENTER); + titleCell.setRowspan(2); + t.addCell(titleCell); + t.addCell(new Phrase(_("lima-business.document.businessnumber"), + bolditalicFont)); + t.addCell(new Phrase(identity.getBusinessNumber(), italicFont)); + //line 2 + t.addCell(new Phrase(identity.getDescription(), italicFont)); + t.addCell(new Phrase(_("lima-business.document.classificationcode"), + bolditalicFont)); + t.addCell(new Phrase(identity.getClassificationCode(), italicFont)); + //line 3 + t.addCell(new Phrase(identity.getAddress(), italicFont)); + t.addCell(""); + t.addCell(new Phrase(_("lima-business.document.vatnumber"), + bolditalicFont)); + t.addCell(new Phrase(identity.getVatNumber(), italicFont)); + //line 4 + t.addCell(new Phrase(identity.getAddress2(), italicFont)); + t.addCell(""); + t.addCell(new Phrase(_("lima-business.document.period1"), + bolditalicFont)); + t.addCell(new Phrase(beginDate, italicFont)); + //line 5 + t.addCell(new Phrase(identity.getZipCode() + " " + identity.getCity(), + italicFont)); + t.addCell(""); + t.addCell(new Phrase(_("lima-business.document.period2"), + bolditalicFont)); + t.addCell(new Phrase(endDate, italicFont)); + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); } - path = LimaConfig.getInstance().getReportsDir(); - } - - - public Paragraph createHeaderPage(String title, Identity identity, String beginDate, String endDate){ - Paragraph paragraphHeaderPage = new Paragraph(); - Table t = null; - try { - - //define table - t = new Table(4, 5); - t.setWidth(100f); - float[] widths = {0.25f, 0.45f, 0.12f, 0.18f}; - t.setWidths(widths); - t.setPadding(1.5f); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.NO_BORDER); - t.setDefaultCell(cell); - - //line 1 - t.addCell(new Phrase(identity.getName(), bolditalicFont)); - Cell titleCell = new Cell(new Phrase(title, titleFont)); - titleCell.setVerticalAlignment(Element.ALIGN_MIDDLE); - titleCell.setHorizontalAlignment(Element.ALIGN_CENTER); - titleCell.setRowspan(2); - t.addCell(titleCell); - t.addCell(new Phrase(_("lima-business.document.businessnumber"), - bolditalicFont)); - t.addCell(new Phrase(identity.getBusinessNumber(), italicFont)); - //line 2 - t.addCell(new Phrase(identity.getDescription(), italicFont)); - t.addCell(new Phrase(_("lima-business.document.classificationcode"), - bolditalicFont)); - t.addCell(new Phrase(identity.getClassificationCode(), italicFont)); - //line 3 - t.addCell(new Phrase(identity.getAddress(), italicFont)); - t.addCell(""); - t.addCell(new Phrase(_("lima-business.document.vatnumber"), - bolditalicFont)); - t.addCell(new Phrase(identity.getVatNumber(), italicFont)); - //line 4 - t.addCell(new Phrase(identity.getAddress2(), italicFont)); - t.addCell(""); - t.addCell(new Phrase(_("lima-business.document.period1"), - bolditalicFont)); - t.addCell(new Phrase(beginDate, italicFont)); - //line 5 - t.addCell(new Phrase(identity.getZipCode() + " " + identity.getCity(), - italicFont)); - t.addCell(""); - t.addCell(new Phrase(_("lima-business.document.period2"), - bolditalicFont)); - t.addCell(new Phrase(endDate, italicFont)); - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - - paragraphHeaderPage.add(t); - return paragraphHeaderPage; - } - - - public Paragraph createNumberPage (int nbPages, String dateS, String hourS) throws BadElementException{ - //n° page + paragraphHeaderPage.add(t); + return paragraphHeaderPage; + } + + + public Paragraph createNumberPage(int nbPages, + String dateS, + String hourS) throws BadElementException { + //n° page Paragraph paragraphPage = new Paragraph(); Table infos = new Table(2); infos.setWidth(100f); @@ -230,623 +223,618 @@ c.setHorizontalAlignment(Element.ALIGN_CENTER); infos.setDefaultCell(c); infos.addCell(new Phrase(_("lima-business.document.createdate1") - + dateS + _("lima-business.document.createdate2") - + hourS, normalFont)); + + dateS + _("lima-business.document.createdate2") + + hourS, normalFont)); infos.addCell(new Phrase(_("lima-business.document.pagenumber") - + nbPages, normalFont)); + + nbPages, normalFont)); paragraphPage.add(infos); return paragraphPage; - } - + } + //############## FinancialStatements ############## - - + + @Override - public void createFinancialStatementsDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException { - Document document = new Document(PageSize.A4, 8, 8, 8, 8); - - List<FinancialStatementAmounts> financialStatementAmounts = - financialStatementService.financialStatementReport(beginDate, endDate); - + public void createFinancialStatementsDocuments(Date beginDate, + Date endDate, + FormatsEnum format) throws LimaException { + Document document = new Document(PageSize.A4, 8, 8, 8, 8); + + List<FinancialStatementAmounts> financialStatementAmounts = + financialStatementService.financialStatementReport(beginDate, endDate); + + Date newDate = new Date(); + String dateS = dateFormat.format(newDate); + String hourS = hourFormat.format(newDate); + + String filePath = path + File.separator + DocumentsEnum.FINANCIALSTATEMENT.getFileName(); + try { - Date newDate = new Date(); - String dateS = dateFormat.format(newDate); - String hourS = hourFormat.format(newDate); - - String filePath = path+File.separator+DocumentsEnum.FINANCIALSTATEMENT.getFileName(); - FileOutputStream fileOut = new FileOutputStream(filePath+format.getExtension()); + FileOutputStream fileOut = new FileOutputStream(filePath + format.getExtension()); + switch (format) { - case HTML: - HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); - break; - case PDF: - PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); - break; + case HTML: + HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); + break; + case PDF: + PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); + break; } - document.open(); - int nbpages = 1; - - Identity identity = identityService.getIdentity(); - - //Split list by financialstatement type - List<List<FinancialStatementAmounts>> listList = - new ArrayList<List<FinancialStatementAmounts>>(); - Boolean first = true; - int min=0; - int size = financialStatementAmounts.size(); - for (int i=0;i<size;i++) { - FinancialStatementAmounts fStatementAmounts = - financialStatementAmounts.get(i); - if (fStatementAmounts.getLevel() == 1 && !fStatementAmounts.getSubAmount()){ - if (first){ - first=false; - } - else{ - listList.add(financialStatementAmounts.subList(min, i-1)); - } - min=i; - } - } - listList.add(financialStatementAmounts.subList(min, size)); - - //create pages - for (List<FinancialStatementAmounts> list : listList) { - String title = list.get(0).getLabel(); - int i = 0; - int n = list.size(); - int max = n; - // alloc nb rows max for pdf documents on one page - if (format == FormatsEnum.PDF){ - max = 35; - } - while (i < n){ - int j = i + max; - if (j > n){ - j = n; - } - List <FinancialStatementAmounts> subFinancialStatementAmounts = - list.subList(i, j); - //create page : header + table + footer - Table headerTable = createFinancialStatementsHeaderTable(); - Table table = createFinancialStatementsTable( - subFinancialStatementAmounts); - //new page - Chapter chapter = new Chapter(0); - //headerPage - chapter.add(createHeaderPage(title, identity, - dateFormat.format(beginDate), dateFormat.format(endDate))); - //n° page - chapter.add(createNumberPage(nbpages, dateS, hourS)); - //headerTable - Paragraph paragraphHeaderTable = new Paragraph(); - paragraphHeaderTable.add(headerTable); - chapter.add(paragraphHeaderTable); - //table - Paragraph paragraphTable = new Paragraph(); - paragraphTable.add(table); - chapter.add(paragraphTable); - //add page - document.add(chapter); - i = i + max; - nbpages++; - } - } - - document.close(); - - } catch (FileNotFoundException eeFNFE) { - log.error("Can't create pdf file", eeFNFE); - } catch (DocumentException eeDE) { - log.error("Can't create document", eeDE); - } - } - - public Table createFinancialStatementsHeaderTable(){ - Table t = null; - try { - t = new Table(4,1); - float[] widths = {0.4f, 0.2f, 0.2f, 0.2f}; - t.setWidths(widths); - t.setWidth(100f); - t.setPadding(3f); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); - t.setDefaultCell(cell); - t.setOffset(8); - t.addCell(new Phrase(_("lima-business.document.label"), - boldFont)); - t.addCell(new Phrase(_("lima-business.document.grossamount"), - boldFont)); - t.addCell(new Phrase(_("lima-business.document.provisiondeprecationamount"), - boldFont)); - t.addCell(new Phrase(_("lima-business.document.netamount"), - boldFont)); - - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - - } - - public Table createFinancialStatementsTable(List<FinancialStatementAmounts> financialStatementAmounts){ - int nbrow = financialStatementAmounts.size(); - Table t = null; - try { - //define table - t = new Table(4,nbrow); - t.setWidth(100f); - float[] widths = {0.4f, 0.2f, 0.2f, 0.2f}; - t.setWidths(widths); - t.setPadding(1.5f); - t.setBorderWidth(1); - t.setOffset(0); - //define default cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - t.setDefaultCell(cell); - - for (FinancialStatementAmounts financialStatementAmount : financialStatementAmounts) { - - String label = financialStatementAmount.getLabel(); - int level = financialStatementAmount.getLevel(); - BigDecimal grossAmount = - financialStatementAmount.getGrossAmount(); - if (grossAmount == null){ - grossAmount = new BigDecimal(0); - } - BigDecimal provisionDeprecationAmount = - financialStatementAmount.getProvisionDeprecationAmount(); - if (provisionDeprecationAmount == null){ - provisionDeprecationAmount = new BigDecimal(0); - } - - if (financialStatementAmount.getSubAmount() && level==1){ - cell.setGrayFill(0.88f); - } - else if (financialStatementAmount.getSubAmount()){ - cell.setGrayFill(0.94f); - } - else { - cell.setGrayFill(1f); - } - if (label == null){ - t.addCell(""); - t.addCell(""); - t.addCell(""); - t.addCell(""); - } - else { - //cell1 - StringBuffer tab = new StringBuffer(); - for (int i = 0; i < level; i++) { - tab.append("\t"); - } - Phrase phrase = null; - if (financialStatementAmount.getHeader()){ - phrase = new Phrase(tab+label, boldFont); - } - else { - phrase = new Phrase(tab+label, normalFont); - } - Cell c = new Cell(phrase); - c.setHorizontalAlignment(Element.ALIGN_LEFT); - t.addCell(c); - //cell2 - if (grossAmount != BigDecimal.ZERO){ - phrase = new Phrase(String.valueOf( - grossAmount), normalFont); - } - else { - phrase = new Phrase(""); - } - t.addCell(phrase); - //cell 3 - if (provisionDeprecationAmount != BigDecimal.ZERO){ - phrase = new Phrase(String.valueOf( - provisionDeprecationAmount), normalFont); - } - else { - phrase = new Phrase(""); - } - t.addCell(phrase); - //cell 4 - BigDecimal solde = grossAmount; - solde = solde.subtract(provisionDeprecationAmount); - if (solde != BigDecimal.ZERO){ - phrase = new Phrase(solde.toString(), normalFont); - } - else { - phrase = new Phrase(""); - } - t.addCell(phrase); - } - } - - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - } - - - + document.open(); + int nbpages = 1; + + Identity identity = identityService.getIdentity(); + + //Split list by financialstatement type + List<List<FinancialStatementAmounts>> listList = + new ArrayList<List<FinancialStatementAmounts>>(); + Boolean first = true; + int min = 0; + int size = financialStatementAmounts.size(); + for (int i = 0; i < size; i++) { + FinancialStatementAmounts fStatementAmounts = + financialStatementAmounts.get(i); + if (fStatementAmounts.getLevel() == 1 && !fStatementAmounts.getSubAmount()) { + if (first) { + first = false; + } else { + listList.add(financialStatementAmounts.subList(min, i - 1)); + } + min = i; + } + } + listList.add(financialStatementAmounts.subList(min, size)); + + //create pages + for (List<FinancialStatementAmounts> list : listList) { + String title = list.get(0).getLabel(); + int i = 0; + int n = list.size(); + int max = n; + // alloc nb rows max for pdf documents on one page + if (format == FormatsEnum.PDF) { + max = 35; + } + while (i < n) { + int j = i + max; + if (j > n) { + j = n; + } + List<FinancialStatementAmounts> subFinancialStatementAmounts = + list.subList(i, j); + //create page : header + table + footer + Table headerTable = createFinancialStatementsHeaderTable(); + Table table = createFinancialStatementsTable( + subFinancialStatementAmounts); + //new page + Chapter chapter = new Chapter(0); + //headerPage + chapter.add(createHeaderPage(title, identity, + dateFormat.format(beginDate), dateFormat.format(endDate))); + //n° page + chapter.add(createNumberPage(nbpages, dateS, hourS)); + //headerTable + Paragraph paragraphHeaderTable = new Paragraph(); + paragraphHeaderTable.add(headerTable); + chapter.add(paragraphHeaderTable); + //table + Paragraph paragraphTable = new Paragraph(); + paragraphTable.add(table); + chapter.add(paragraphTable); + //add page + document.add(chapter); + i = i + max; + nbpages++; + } + } + + document.close(); + + } catch (FileNotFoundException eeFNFE) { + log.error("Can't create pdf file", eeFNFE); + } catch (DocumentException eeDE) { + log.error("Can't create document", eeDE); + } + } + + public Table createFinancialStatementsHeaderTable() { + Table t = null; + try { + t = new Table(4, 1); + float[] widths = {0.4f, 0.2f, 0.2f, 0.2f}; + t.setWidths(widths); + t.setWidth(100f); + t.setPadding(3f); + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + t.setDefaultCell(cell); + t.setOffset(8); + t.addCell(new Phrase(_("lima-business.document.label"), + boldFont)); + t.addCell(new Phrase(_("lima-business.document.grossamount"), + boldFont)); + t.addCell(new Phrase(_("lima-business.document.provisiondeprecationamount"), + boldFont)); + t.addCell(new Phrase(_("lima-business.document.netamount"), + boldFont)); + + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + + } + + public Table createFinancialStatementsTable(List<FinancialStatementAmounts> financialStatementAmounts) { + int nbrow = financialStatementAmounts.size(); + Table t = null; + try { + //define table + t = new Table(4, nbrow); + t.setWidth(100f); + float[] widths = {0.4f, 0.2f, 0.2f, 0.2f}; + t.setWidths(widths); + t.setPadding(1.5f); + t.setBorderWidth(1); + t.setOffset(0); + //define default cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_RIGHT); + t.setDefaultCell(cell); + + for (FinancialStatementAmounts financialStatementAmount : financialStatementAmounts) { + + String label = financialStatementAmount.getLabel(); + int level = financialStatementAmount.getLevel(); + BigDecimal grossAmount = + financialStatementAmount.getGrossAmount(); + if (grossAmount == null) { + grossAmount = new BigDecimal(0); + } + BigDecimal provisionDeprecationAmount = + financialStatementAmount.getProvisionDeprecationAmount(); + if (provisionDeprecationAmount == null) { + provisionDeprecationAmount = new BigDecimal(0); + } + + if (financialStatementAmount.getSubAmount() && level == 1) { + cell.setGrayFill(0.88f); + } else if (financialStatementAmount.getSubAmount()) { + cell.setGrayFill(0.94f); + } else { + cell.setGrayFill(1f); + } + if (label == null) { + t.addCell(""); + t.addCell(""); + t.addCell(""); + t.addCell(""); + } else { + //cell1 + StringBuffer tab = new StringBuffer(); + for (int i = 0; i < level; i++) { + tab.append("\t"); + } + Phrase phrase; + if (financialStatementAmount.getHeader()) { + phrase = new Phrase(tab + label, boldFont); + } else { + phrase = new Phrase(tab + label, normalFont); + } + Cell c = new Cell(phrase); + c.setHorizontalAlignment(Element.ALIGN_LEFT); + t.addCell(c); + //cell2 + if (grossAmount != BigDecimal.ZERO) { + phrase = new Phrase(String.valueOf( + grossAmount), normalFont); + } else { + phrase = new Phrase(""); + } + t.addCell(phrase); + //cell 3 + if (provisionDeprecationAmount != BigDecimal.ZERO) { + phrase = new Phrase(String.valueOf( + provisionDeprecationAmount), normalFont); + } else { + phrase = new Phrase(""); + } + t.addCell(phrase); + //cell 4 + BigDecimal solde = grossAmount; + solde = solde.subtract(provisionDeprecationAmount); + if (solde != BigDecimal.ZERO) { + phrase = new Phrase(solde.toString(), normalFont); + } else { + phrase = new Phrase(""); + } + t.addCell(phrase); + } + } + + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + } + + //############## Ledger ############## - - @Override - public void createLedgerDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException { - Document document = new Document(PageSize.A4, 8, 8, 8, 8); - List<Object> list = new ArrayList<Object>(); + + @Override + public void createLedgerDocuments(Date beginDate, + Date endDate, + FormatsEnum format) throws LimaException { + Document document = new Document(PageSize.A4, 8, 8, 8, 8); + List<Object> list = new ArrayList<Object>(); try { - + BalanceTrial balanceTrial = reportService.generateLedger(beginDate, endDate, null, true); - if (balanceTrial.getReportsDatas() != null){ - for (ReportsDatas reportsDatas : balanceTrial.getReportsDatas()) { + if (balanceTrial.getReportsDatas() != null) { + for (ReportsDatas reportsDatas : balanceTrial.getReportsDatas()) { list.add(reportsDatas); List<Entry> entries = (List<Entry>) reportsDatas.getListEntry(); - if (entries != null){ + if (entries != null) { Collections.sort(entries, new EntryComparator()); - list.addAll(entries); + list.addAll(entries); } } } - + Date newDate = new Date(); String dateS = dateFormat.format(newDate); String hourS = hourFormat.format(newDate); BigDecimal currentAmountDebit = new BigDecimal(0); BigDecimal currentAmountCredit = new BigDecimal(0); - String accountcarry =""; - - String filePath = path+File.separator+DocumentsEnum.LEDGER.getFileName(); - FileOutputStream fileOut = new FileOutputStream(filePath+format.getExtension()); + String accountcarry = ""; + + String filePath = path + File.separator + DocumentsEnum.LEDGER.getFileName(); + FileOutputStream fileOut = new FileOutputStream(filePath + format.getExtension()); switch (format) { - case HTML: - HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); - break; - case PDF: - PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); - break; + case HTML: + HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); + break; + case PDF: + PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); + break; } - document.open(); - int nbpages = 1; - Identity identity = identityService.getIdentity(); + document.open(); + int nbpages = 1; + Identity identity = identityService.getIdentity(); - //create pages - int i = 0; - int n = list.size(); - int max = n; - // alloc nb rows max for pdf documents on one page - if (format == FormatsEnum.PDF){ - max = 32; - } - while (i < n){ - int j = i + max; - if (j > n){ - j = n; - } - List <Object> subList = list.subList(i, j); - //create page : header + table + footer - Table headerTable = createLedgerHeaderTable(); - //new page - Chapter chapter = new Chapter(0); - //headerPage - chapter.add(createHeaderPage(DocumentsEnum.LEDGER.getDescription(), identity, - dateFormat.format(beginDate), dateFormat.format(endDate))); - //n° page - chapter.add(createNumberPage(nbpages, dateS, hourS)); - //headerTable - Paragraph paragraphHeaderTable = new Paragraph(); - paragraphHeaderTable.add(headerTable); - chapter.add(paragraphHeaderTable); - //backward amounts - if (n>max && nbpages>1){ - Paragraph backwardParagraph = new Paragraph(); - backwardParagraph.add(createLedgerAmountTable( - accountcarry, _("lima-business.document.carryback"), - currentAmountDebit, currentAmountCredit)); - chapter.add(backwardParagraph); - } - //table - Paragraph paragraphTable = new Paragraph(); - Table table = createLedgerTable(subList); - paragraphTable.add(table); - chapter.add(paragraphTable); - for (Object object : subList) { - if (object instanceof Entry){ - Entry entry = (Entry) object; - if (entry.getDebit()){ - currentAmountDebit = currentAmountDebit.add(entry.getAmount()); - } - else { - currentAmountCredit = currentAmountCredit.add(entry.getAmount()); - } + //create pages + int i = 0; + int n = list.size(); + int max = n; + // alloc nb rows max for pdf documents on one page + if (format == FormatsEnum.PDF) { + max = 32; + } + while (i < n) { + int j = i + max; + if (j > n) { + j = n; + } + List<Object> subList = list.subList(i, j); + //create page : header + table + footer + Table headerTable = createLedgerHeaderTable(); + //new page + Chapter chapter = new Chapter(0); + //headerPage + chapter.add(createHeaderPage(DocumentsEnum.LEDGER.getDescription(), identity, + dateFormat.format(beginDate), dateFormat.format(endDate))); + //n° page + chapter.add(createNumberPage(nbpages, dateS, hourS)); + //headerTable + Paragraph paragraphHeaderTable = new Paragraph(); + paragraphHeaderTable.add(headerTable); + chapter.add(paragraphHeaderTable); + //backward amounts + if (n > max && nbpages > 1) { + Paragraph backwardParagraph = new Paragraph(); + backwardParagraph.add(createLedgerAmountTable( + accountcarry, _("lima-business.document.carryback"), + currentAmountDebit, currentAmountCredit)); + chapter.add(backwardParagraph); + } + //table + Paragraph paragraphTable = new Paragraph(); + Table table = createLedgerTable(subList); + paragraphTable.add(table); + chapter.add(paragraphTable); + for (Object object : subList) { + if (object instanceof Entry) { + Entry entry = (Entry) object; + if (entry.getDebit()) { + currentAmountDebit = currentAmountDebit.add(entry.getAmount()); + } else { + currentAmountCredit = currentAmountCredit.add(entry.getAmount()); } - else { - ReportsDatas reportsDatas = (ReportsDatas) object; - Account account = reportsDatas.getAccount(); - if ( account != null){ - accountcarry = account.getAccountNumber() - + " " + account.getLabel() + " "; - } + } else { + ReportsDatas reportsDatas = (ReportsDatas) object; + Account account = reportsDatas.getAccount(); + if (account != null) { + accountcarry = account.getAccountNumber() + + " " + account.getLabel() + " "; } } - //forward amounts - if (n > max && i <= n-max){ - Paragraph forwardParagraph = new Paragraph(); - forwardParagraph.add(createLedgerAmountTable("", - _("lima-business.document.carryforward"), - currentAmountDebit, currentAmountCredit)); - chapter.add(forwardParagraph); - } - //final amounts - if (i >= n-max){ - Paragraph finalAmountParagraph = new Paragraph(); - finalAmountParagraph.add(createLedgerAmountTable("", - _("lima-business.document.amounts"), - currentAmountDebit, currentAmountCredit)); - chapter.add(finalAmountParagraph); - } - //add page - document.add(chapter); - i = i + max; - nbpages++; - } - document.close(); - + } + //forward amounts + if (n > max && i <= n - max) { + Paragraph forwardParagraph = new Paragraph(); + forwardParagraph.add(createLedgerAmountTable("", + _("lima-business.document.carryforward"), + currentAmountDebit, currentAmountCredit)); + chapter.add(forwardParagraph); + } + //final amounts + if (i >= n - max) { + Paragraph finalAmountParagraph = new Paragraph(); + finalAmountParagraph.add(createLedgerAmountTable("", + _("lima-business.document.amounts"), + currentAmountDebit, currentAmountCredit)); + chapter.add(finalAmountParagraph); + } + //add page + document.add(chapter); + i = i + max; + nbpages++; + } + document.close(); + } catch (FileNotFoundException eeFNFE) { log.error("Can't create pdf file", eeFNFE); } catch (DocumentException eeDE) { log.error("Can't create document", eeDE); } - } - - public Table createLedgerHeaderTable(){ - Table t = null; - try { - t = new Table(7,1); - float[] widths = {0.1f, 0.05f, 0.1f, 0.3f, 0.15f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setWidth(100f); - t.setPadding(3.5f); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); - t.setDefaultCell(cell); - t.setOffset(8); - t.addCell(new Phrase(_("lima-business.document.date"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.entrybook"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.voucher"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.description"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.debit"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.credit"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.solde"), boldFont)); - - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - - } - - public Table createLedgerTable(List<Object> subList){ - int nbrow = subList.size(); - Table t = null; - try { - //define table - t = new Table(7, nbrow); - t.setWidth(100f); - float[] widths = {0.1f, 0.05f, 0.1f, 0.3f, 0.15f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setPadding(1.5f); - t.setBorderWidth(1); - t.setOffset(0); - //define default cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - t.setDefaultCell(cell); - - for (Object object : subList) { - if (object instanceof ReportsDatas) { + } - ReportsDatas reportsDatas = (ReportsDatas) object; - - String accountS = ""; - Account account = reportsDatas.getAccount(); - if (account != null){ - accountS = account.getAccountNumber()+"\t"+account.getLabel(); - } - BigDecimal amountCredit = reportsDatas.getAmountCredit(); - BigDecimal amountDebit = reportsDatas.getAmountDebit(); - - Cell c = new Cell(new Phrase(accountS, boldFont)); - c.setColspan(4); - c.setHorizontalAlignment(Element.ALIGN_LEFT); - t.addCell(c); - t.addCell(new Phrase(String.valueOf(amountDebit), boldFont)); - t.addCell(new Phrase(String.valueOf(amountCredit), boldFont)); - BigDecimal solde = amountDebit; - solde = solde.subtract(amountCredit); - t.addCell(new Phrase(String.valueOf(solde), boldFont)); - } - else { - Entry entry = (Entry) object; - - String entryBookCode = ""; - EntryBook entryBook = entry.getFinancialTransaction().getEntryBook(); - if (entryBook != null){ - entryBookCode = entryBook.getCode(); - } - BigDecimal amountDebit = new BigDecimal(0), - amountCredit = new BigDecimal(0); - if (entry.getDebit()){ - amountDebit = entry.getAmount(); - } - else { - amountCredit = entry.getAmount(); - } - - t.addCell(new Phrase(dateFormat.format( - entry.getFinancialTransaction().getTransactionDate()), - normalFont)); - t.addCell(new Phrase(entryBookCode, normalFont)); - t.addCell(new Phrase(entry.getVoucher(), normalFont)); - t.addCell(new Phrase(entry.getDescription(), normalFont)); - t.addCell(new Phrase(amountDebit.toString(), - normalFont)); - t.addCell(new Phrase(amountCredit.toString(), - normalFont)); - BigDecimal solde = amountDebit.subtract(amountCredit); - t.addCell(new Phrase(solde.toString(), - normalFont)); - - } - } - } catch (DocumentException eeDE) { - log.error("Can't create table", eeDE); + public Table createLedgerHeaderTable() { + Table t = null; + try { + t = new Table(7, 1); + float[] widths = {0.1f, 0.05f, 0.1f, 0.3f, 0.15f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setWidth(100f); + t.setPadding(3.5f); + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + t.setDefaultCell(cell); + t.setOffset(8); + t.addCell(new Phrase(_("lima-business.document.date"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.entrybook"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.voucher"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.description"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.debit"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.credit"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.solde"), boldFont)); + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); } - return t; - } - - public Table createLedgerAmountTable(String account, String title, BigDecimal debit, BigDecimal credit){ - Table t = null; - try { - t = new Table(5,1); - float[] widths = {0.4f,0.15f, 0.15f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setWidth(100f); - t.setPadding(3f); - t.setOffset(0); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.RIGHT); - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - t.setDefaultCell(cell); - Cell accountCell = new Cell(new Phrase(account, boldFont)); - accountCell.setHorizontalAlignment(Element.ALIGN_LEFT); - accountCell.setBorder(Rectangle.NO_BORDER); - t.addCell(accountCell); - t.addCell(new Phrase(title, boldFont)); - t.addCell(new Phrase(debit.toString(), boldFont)); - t.addCell(new Phrase(credit.toString(), boldFont)); - BigDecimal solde = debit.subtract(credit); - t.addCell(new Phrase(solde.toString(), boldFont)); - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - } - + return t; + + } + + public Table createLedgerTable(List<Object> subList) { + int nbrow = subList.size(); + Table t = null; + try { + //define table + t = new Table(7, nbrow); + t.setWidth(100f); + float[] widths = {0.1f, 0.05f, 0.1f, 0.3f, 0.15f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setPadding(1.5f); + t.setBorderWidth(1); + t.setOffset(0); + //define default cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_RIGHT); + t.setDefaultCell(cell); + + for (Object object : subList) { + if (object instanceof ReportsDatas) { + + ReportsDatas reportsDatas = (ReportsDatas) object; + + String accountS = ""; + Account account = reportsDatas.getAccount(); + if (account != null) { + accountS = account.getAccountNumber() + "\t" + account.getLabel(); + } + BigDecimal amountCredit = reportsDatas.getAmountCredit(); + BigDecimal amountDebit = reportsDatas.getAmountDebit(); + + Cell c = new Cell(new Phrase(accountS, boldFont)); + c.setColspan(4); + c.setHorizontalAlignment(Element.ALIGN_LEFT); + t.addCell(c); + t.addCell(new Phrase(String.valueOf(amountDebit), boldFont)); + t.addCell(new Phrase(String.valueOf(amountCredit), boldFont)); + BigDecimal solde = amountDebit; + solde = solde.subtract(amountCredit); + t.addCell(new Phrase(String.valueOf(solde), boldFont)); + } else { + Entry entry = (Entry) object; + + String entryBookCode = ""; + EntryBook entryBook = entry.getFinancialTransaction().getEntryBook(); + if (entryBook != null) { + entryBookCode = entryBook.getCode(); + } + BigDecimal amountDebit = new BigDecimal(0), + amountCredit = new BigDecimal(0); + if (entry.getDebit()) { + amountDebit = entry.getAmount(); + } else { + amountCredit = entry.getAmount(); + } + + t.addCell(new Phrase(dateFormat.format( + entry.getFinancialTransaction().getTransactionDate()), + normalFont)); + t.addCell(new Phrase(entryBookCode, normalFont)); + t.addCell(new Phrase(entry.getVoucher(), normalFont)); + t.addCell(new Phrase(entry.getDescription(), normalFont)); + t.addCell(new Phrase(amountDebit.toString(), + normalFont)); + t.addCell(new Phrase(amountCredit.toString(), + normalFont)); + BigDecimal solde = amountDebit.subtract(amountCredit); + t.addCell(new Phrase(solde.toString(), + normalFont)); + + } + } + } catch (DocumentException eeDE) { + log.error("Can't create table", eeDE); + + } + return t; + } + + public Table createLedgerAmountTable(String account, + String title, + BigDecimal debit, + BigDecimal credit) { + Table t = null; + try { + t = new Table(5, 1); + float[] widths = {0.4f, 0.15f, 0.15f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setWidth(100f); + t.setPadding(3f); + t.setOffset(0); + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.RIGHT); + cell.setHorizontalAlignment(Element.ALIGN_RIGHT); + t.setDefaultCell(cell); + Cell accountCell = new Cell(new Phrase(account, boldFont)); + accountCell.setHorizontalAlignment(Element.ALIGN_LEFT); + accountCell.setBorder(Rectangle.NO_BORDER); + t.addCell(accountCell); + t.addCell(new Phrase(title, boldFont)); + t.addCell(new Phrase(debit.toString(), boldFont)); + t.addCell(new Phrase(credit.toString(), boldFont)); + BigDecimal solde = debit.subtract(credit); + t.addCell(new Phrase(solde.toString(), boldFont)); + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + } + //############## EntryBooks ############## - - - + + @Override - public void createEntryBooksDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException { - Document document = new Document(PageSize.A4, 8, 8, 8, 8); - TopiaContext transaction = null; + public void createEntryBooksDocuments(Date beginDate, + Date endDate, + FormatsEnum format) throws LimaException { + Document document = new Document(PageSize.A4, 8, 8, 8, 8); + TopiaContext transaction = beginTransaction(rootContext); + ; - try { - transaction = beginTransaction(); - + try { Date newDate = new Date(); String dateS = dateFormat.format(newDate); String hourS = hourFormat.format(newDate); - - String filePath = path+File.separator+DocumentsEnum.ENTRYBOOKS.getFileName(); - FileOutputStream fileOut = new FileOutputStream(filePath+format.getExtension()); + + String filePath = path + File.separator + DocumentsEnum.ENTRYBOOKS.getFileName(); + FileOutputStream fileOut = new FileOutputStream(filePath + format.getExtension()); switch (format) { - case HTML: - HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); - break; - case PDF: - PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); - break; + case HTML: + HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); + break; + case PDF: + PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); + break; } document.open(); int nbpages = 1; - + Identity identity = identityService.getIdentity(); - + ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = - LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(transaction); + LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(transaction); EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(transaction); //Split list by financialstatement type List<ClosedPeriodicEntryBook> closedPeriodicEntryBookList = - closedPeriodicEntryBookDAO.findAllByDates(beginDate, endDate); + closedPeriodicEntryBookDAO.findAllByDates(beginDate, endDate); for (ClosedPeriodicEntryBook closedPeriodicEntryBook : closedPeriodicEntryBookList) { - + TopiaQuery query = entryDAO.createQuery(); String financialPeriodProperty = - TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, - FinancialTransaction.FINANCIAL_PERIOD); + TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, + FinancialTransaction.FINANCIAL_PERIOD); String entryBookProperty = - TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, - FinancialTransaction.ENTRY_BOOK); + TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, + FinancialTransaction.ENTRY_BOOK); query.addWhere(financialPeriodProperty, Op.EQ, - closedPeriodicEntryBook.getFinancialPeriod()) - .addWhere(entryBookProperty, Op.EQ, - closedPeriodicEntryBook.getEntryBook()); - + closedPeriodicEntryBook.getFinancialPeriod()) + .addWhere(entryBookProperty, Op.EQ, + closedPeriodicEntryBook.getEntryBook()); + List<Entry> entries = entryDAO.findAllByQuery(query); - - List<Object[]> results = new ArrayList<Object[]>(); + + List<Object[]> results; BigDecimal debit = new BigDecimal(0); BigDecimal credit = new BigDecimal(0); - query.setSelect(Entry.DEBIT, "SUM("+Entry.AMOUNT+")"); + query.setSelect(Entry.DEBIT, "SUM(" + Entry.AMOUNT + ")"); query.addGroup(Entry.DEBIT); results = query.execute(transaction); int nbAmount = results.size(); - if(nbAmount==2){ - debit = (BigDecimal)results.get(0)[1]; - credit = (BigDecimal)results.get(1)[1]; + if (nbAmount == 2) { + debit = (BigDecimal) results.get(0)[1]; + credit = (BigDecimal) results.get(1)[1]; } - if (nbAmount==1){ - if ((Boolean)results.get(0)[0]){ - debit = (BigDecimal)results.get(0)[1]; + if (nbAmount == 1) { + if ((Boolean) results.get(0)[0]) { + debit = (BigDecimal) results.get(0)[1]; + } else { + credit = (BigDecimal) results.get(0)[1]; } - else { - credit = (BigDecimal)results.get(0)[1]; - } } - + //create pages String title = closedPeriodicEntryBook.getEntryBook().getLabel() - + "\n" + monthYearFormat.format( - closedPeriodicEntryBook.getFinancialPeriod().getBeginDate()); + + "\n" + monthYearFormat.format( + closedPeriodicEntryBook.getFinancialPeriod().getBeginDate()); //list = list.subList(1, list.size()); int i = 0; int n = entries.size(); int max = n; // alloc nb rows max for pdf documents on one page - if (format == FormatsEnum.PDF){ + if (format == FormatsEnum.PDF) { max = 35; } - while (i < n){ + while (i < n) { int j = i + max; - if (j > n){ + if (j > n) { j = n; } - List <Entry> subEntries = - entries.subList(i, j); + List<Entry> subEntries = + entries.subList(i, j); //create page : header + table + footer Table headerTable = createEntryBooksHeaderTable(); Table table = createEntryBooksTable(subEntries); //new page Chapter chapter = new Chapter(0); - //headerPage - chapter.add(createHeaderPage(title, identity, - dateFormat.format(beginDate), dateFormat.format(endDate))); - //n° page - chapter.add(createNumberPage(nbpages, dateS, hourS)); + //headerPage + chapter.add(createHeaderPage(title, identity, + dateFormat.format(beginDate), dateFormat.format(endDate))); + //n° page + chapter.add(createNumberPage(nbpages, dateS, hourS)); //headerTable Paragraph paragraphHeaderTable = new Paragraph(); paragraphHeaderTable.add(headerTable); @@ -855,85 +843,82 @@ Paragraph paragraphTable = new Paragraph(); paragraphTable.add(table); chapter.add(paragraphTable); - //final amounts - if (i>=n-max){ - Paragraph finalAmountParagraph = new Paragraph(); - finalAmountParagraph.add(createEntryBooksAmountTable( - _("lima-business.document.amounts"), debit, credit)); - chapter.add(finalAmountParagraph); - } + //final amounts + if (i >= n - max) { + Paragraph finalAmountParagraph = new Paragraph(); + finalAmountParagraph.add(createEntryBooksAmountTable( + _("lima-business.document.amounts"), debit, credit)); + chapter.add(finalAmountParagraph); + } //add page document.add(chapter); i = i + max; nbpages++; } } - + document.close(); - - } catch (FileNotFoundException eeFNFE) { - log.error("Can't create pdf file", eeFNFE); - } catch (DocumentException eeDE) { - log.error("Can't create document", eeDE); - } catch (TopiaException eeTE) { - log.error("Can't get entries", eeTE); - } - + } catch (Exception eee) { + doCatch(transaction, eee); + } finally { + doFinally(transaction); + } + } - public Table createEntryBooksHeaderTable(){ - Table t = null; - try { - t = new Table(6,1); - float[] widths = {0.1f, 0.1f, 0.1f, 0.4f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setWidth(100f); - t.setPadding(3f); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); - t.setDefaultCell(cell); - t.setOffset(8); - t.addCell(new Phrase(_("lima-business.document.date"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.accountnumber"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.voucher"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.description"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.debit"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.credit"), boldFont)); - - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - - } - - public Table createEntryBooksTable(List<Entry> entries){ - int nbrow = entries.size(); - Table t = null; - try { - //define table - t = new Table(6,nbrow); - t.setWidth(100f); - float[] widths = {0.1f, 0.1f, 0.1f, 0.4f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setPadding(1.5f); - t.setBorderWidth(1); - t.setOffset(0); - //define default cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - t.setDefaultCell(cell); - - for (Entry entry : entries) { + public Table createEntryBooksHeaderTable() { + Table t = null; + try { + t = new Table(6, 1); + float[] widths = {0.1f, 0.1f, 0.1f, 0.4f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setWidth(100f); + t.setPadding(3f); + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + t.setDefaultCell(cell); + t.setOffset(8); + t.addCell(new Phrase(_("lima-business.document.date"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.accountnumber"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.voucher"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.description"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.debit"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.credit"), boldFont)); + + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + + } + + public Table createEntryBooksTable(List<Entry> entries) { + int nbrow = entries.size(); + Table t = null; + try { + //define table + t = new Table(6, nbrow); + t.setWidth(100f); + float[] widths = {0.1f, 0.1f, 0.1f, 0.4f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setPadding(1.5f); + t.setBorderWidth(1); + t.setOffset(0); + //define default cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_RIGHT); + t.setDefaultCell(cell); + + for (Entry entry : entries) { t.addCell(new Phrase(dateFormat.format( entry.getFinancialTransaction().getTransactionDate()), - normalFont)); + normalFont)); String account = ""; - if (entry.getAccount() != null){ + if (entry.getAccount() != null) { account = entry.getAccount().getAccountNumber(); } t.addCell(new Phrase(account, normalFont)); @@ -943,310 +928,319 @@ entry.getDebit() ? entry.getAmount() : 0), normalFont)); t.addCell(new Phrase(String.valueOf( entry.getDebit() ? entry.getAmount() : 0), normalFont)); - } - - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - } + } - public Table createEntryBooksAmountTable(String title, BigDecimal credit, BigDecimal debit){ - Table t = null; - try { - t = new Table(3,1); - float[] widths = {0.7f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setWidth(100f); - t.setPadding(3f); - t.setOffset(0); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.RIGHT); - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - t.setDefaultCell(cell); + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + } - t.addCell(new Phrase(title, boldFont)); - t.addCell(new Phrase(debit.toString(), boldFont)); - t.addCell(new Phrase(credit.toString(), boldFont)); - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - } - + public Table createEntryBooksAmountTable(String title, + BigDecimal credit, + BigDecimal debit) { + Table t = null; + try { + t = new Table(3, 1); + float[] widths = {0.7f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setWidth(100f); + t.setPadding(3f); + t.setOffset(0); + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.RIGHT); + cell.setHorizontalAlignment(Element.ALIGN_RIGHT); + t.setDefaultCell(cell); + + t.addCell(new Phrase(title, boldFont)); + t.addCell(new Phrase(debit.toString(), boldFont)); + t.addCell(new Phrase(credit.toString(), boldFont)); + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + } + //############## Balance ############## - @Override - public void createBalanceDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException { - Document document = new Document(PageSize.A4, 8, 8, 8, 8); - - BalanceTrial balanceTrial = - reportService.generateBalanceTrial(beginDate, endDate, null, false, true); + @Override + public void createBalanceDocuments(Date beginDate, + Date endDate, + FormatsEnum format) throws LimaException { + Document document = new Document(PageSize.A4, 8, 8, 8, 8); - List<ReportsDatas> list = (List<ReportsDatas>) balanceTrial.getReportsDatas(); - + BalanceTrial balanceTrial = + reportService.generateBalanceTrial(beginDate, endDate, null, false, true); + + List<ReportsDatas> list = (List<ReportsDatas>) balanceTrial.getReportsDatas(); + try { Date newDate = new Date(); String dateS = dateFormat.format(newDate); String hourS = hourFormat.format(newDate); - String fileDateS = filedateFormat.format(newDate); +// String fileDateS = filedateFormat.format(newDate); BigDecimal currentAmountDebit = new BigDecimal(0); BigDecimal currentAmountCredit = new BigDecimal(0); BigDecimal currentSoldeDebit = new BigDecimal(0); BigDecimal currentSoldeCredit = new BigDecimal(0); - - String filePath = path+File.separator+DocumentsEnum.BALANCE.getFileName(); - FileOutputStream fileOut = new FileOutputStream(filePath+format.getExtension()); + + String filePath = path + File.separator + DocumentsEnum.BALANCE.getFileName(); + FileOutputStream fileOut = new FileOutputStream(filePath + format.getExtension()); switch (format) { - case HTML: - HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); - break; - case PDF: - PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); - break; + case HTML: + HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); + break; + case PDF: + PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); + break; } - document.open(); - int nbpages = 1; - Identity identity = identityService.getIdentity(); + document.open(); + int nbpages = 1; + Identity identity = identityService.getIdentity(); - //create pages - int i = 0; - int n = list.size(); - int max = n; - // alloc nb rows max for pdf documents on one page - if (format == FormatsEnum.PDF){ - max = 26; - } - while (i < n){ - int j = i + max; - if (j > n){ - j = n; - } - List <ReportsDatas> subList = list.subList(i, j); - //create page : header + table + footer - Table headerTable = createBalanceHeaderTable(); - //new page - Chapter chapter = new Chapter(0); - //headerPage - chapter.add(createHeaderPage(DocumentsEnum.BALANCE.getDescription(), identity, dateFormat.format(beginDate), dateFormat.format(endDate))); - //n° page - chapter.add(createNumberPage(nbpages, dateS, hourS)); - //headerTable - Paragraph paragraphHeaderTable = new Paragraph(); - paragraphHeaderTable.add(headerTable); - chapter.add(paragraphHeaderTable); - //backward amounts - if (n>max && nbpages>1){ - Paragraph backwardParagraph = new Paragraph(); - backwardParagraph.add(createBalanceAmountTable( - _("lima-business.document.carryback"), - currentAmountDebit, currentAmountCredit, - currentSoldeDebit, currentSoldeCredit)); - chapter.add(backwardParagraph); - } - //table - Paragraph paragraphTable = new Paragraph(); - Table table = createBalanceTable(subList); - paragraphTable.add(table); - chapter.add(paragraphTable); - for (ReportsDatas reportsDatas : subList){ - currentAmountDebit = currentAmountDebit.add(reportsDatas.getAmountDebit()); - currentAmountCredit = currentAmountCredit.add(reportsDatas.getAmountCredit()); - if (reportsDatas.getSoldeDebit()){ - currentSoldeDebit = currentSoldeDebit.add(reportsDatas.getAmountSolde()); - } - else { - currentSoldeCredit = currentSoldeCredit.add(reportsDatas.getAmountSolde()); - } - } - //forward amounts - if (n > max && i <= n-max){ - Paragraph forwardParagraph = new Paragraph(); - forwardParagraph.add(createBalanceAmountTable( - _("lima-business.document.carryforward"), - currentAmountDebit, currentAmountCredit, - currentSoldeDebit, currentSoldeCredit)); - chapter.add(forwardParagraph); - } - //final amounts - if (i >= n-max){ - Paragraph finalAmountParagraph = new Paragraph(); - finalAmountParagraph.add(createBalanceAmountTable( - _("lima-business.document.amounts"), - currentAmountDebit, currentAmountCredit, - currentSoldeDebit, currentSoldeCredit)); - chapter.add(finalAmountParagraph); - } - //add page - document.add(chapter); - i = i + max; - nbpages++; - } - document.close(); - + //create pages + int i = 0; + int n = list.size(); + int max = n; + // alloc nb rows max for pdf documents on one page + if (format == FormatsEnum.PDF) { + max = 26; + } + while (i < n) { + int j = i + max; + if (j > n) { + j = n; + } + List<ReportsDatas> subList = list.subList(i, j); + //create page : header + table + footer + Table headerTable = createBalanceHeaderTable(); + //new page + Chapter chapter = new Chapter(0); + //headerPage + chapter.add(createHeaderPage(DocumentsEnum.BALANCE.getDescription(), identity, dateFormat.format(beginDate), dateFormat.format(endDate))); + //n° page + chapter.add(createNumberPage(nbpages, dateS, hourS)); + //headerTable + Paragraph paragraphHeaderTable = new Paragraph(); + paragraphHeaderTable.add(headerTable); + chapter.add(paragraphHeaderTable); + //backward amounts + if (n > max && nbpages > 1) { + Paragraph backwardParagraph = new Paragraph(); + backwardParagraph.add(createBalanceAmountTable( + _("lima-business.document.carryback"), + currentAmountDebit, currentAmountCredit, + currentSoldeDebit, currentSoldeCredit)); + chapter.add(backwardParagraph); + } + //table + Paragraph paragraphTable = new Paragraph(); + Table table = createBalanceTable(subList); + paragraphTable.add(table); + chapter.add(paragraphTable); + for (ReportsDatas reportsDatas : subList) { + currentAmountDebit = currentAmountDebit.add(reportsDatas.getAmountDebit()); + currentAmountCredit = currentAmountCredit.add(reportsDatas.getAmountCredit()); + if (reportsDatas.getSoldeDebit()) { + currentSoldeDebit = currentSoldeDebit.add(reportsDatas.getAmountSolde()); + } else { + currentSoldeCredit = currentSoldeCredit.add(reportsDatas.getAmountSolde()); + } + } + //forward amounts + if (n > max && i <= n - max) { + Paragraph forwardParagraph = new Paragraph(); + forwardParagraph.add(createBalanceAmountTable( + _("lima-business.document.carryforward"), + currentAmountDebit, currentAmountCredit, + currentSoldeDebit, currentSoldeCredit)); + chapter.add(forwardParagraph); + } + //final amounts + if (i >= n - max) { + Paragraph finalAmountParagraph = new Paragraph(); + finalAmountParagraph.add(createBalanceAmountTable( + _("lima-business.document.amounts"), + currentAmountDebit, currentAmountCredit, + currentSoldeDebit, currentSoldeCredit)); + chapter.add(finalAmountParagraph); + } + //add page + document.add(chapter); + i = i + max; + nbpages++; + } + document.close(); + } catch (FileNotFoundException eeFNFE) { log.error("Can't create pdf file", eeFNFE); } catch (DocumentException eeDE) { log.error("Can't create document", eeDE); } - } - - public Table createBalanceHeaderTable(){ - Table t = null; - try { - t = new Table(6,1); - float[] widths = {0.07f, 0.33f, 0.15f, 0.15f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setWidth(100f); - t.setPadding(3.5f); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); - t.setDefaultCell(cell); - t.setOffset(8); - t.addCell(new Phrase(_("lima-business.document.accountnumber"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.description"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.movementdebit"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.movementcredit"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.soldedebit"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.soldecredit"), boldFont)); - - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - - } - - public Table createBalanceTable(List<ReportsDatas> subList){ - int nbrow = subList.size(); - Table t = null; - try { - //define table - t = new Table(6, nbrow); - t.setWidth(100f); - float[] widths = {0.07f, 0.33f, 0.15f, 0.15f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setPadding(1.5f); - t.setBorderWidth(1); - t.setOffset(0); - //define default cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - t.setDefaultCell(cell); - - for (ReportsDatas reportsDatas : subList) { - + } + + public Table createBalanceHeaderTable() { + Table t = null; + try { + t = new Table(6, 1); + float[] widths = {0.07f, 0.33f, 0.15f, 0.15f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setWidth(100f); + t.setPadding(3.5f); + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + t.setDefaultCell(cell); + t.setOffset(8); + t.addCell(new Phrase(_("lima-business.document.accountnumber"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.description"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.movementdebit"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.movementcredit"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.soldedebit"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.soldecredit"), boldFont)); + + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + + } + + public Table createBalanceTable(List<ReportsDatas> subList) { + int nbrow = subList.size(); + Table t = null; + try { + //define table + t = new Table(6, nbrow); + t.setWidth(100f); + float[] widths = {0.07f, 0.33f, 0.15f, 0.15f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setPadding(1.5f); + t.setBorderWidth(1); + t.setOffset(0); + //define default cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_RIGHT); + t.setDefaultCell(cell); + + for (ReportsDatas reportsDatas : subList) { + String soldeDebit = String.valueOf(reportsDatas.getSoldeDebit() ? reportsDatas.getAmountSolde() : 0); String soldeCredit = String.valueOf(reportsDatas.getSoldeDebit() ? 0 : reportsDatas.getAmountSolde()); - - t.addCell(new Phrase(reportsDatas.getAccount().getAccountNumber(), normalFont)); - t.addCell(new Phrase(reportsDatas.getAccount().getLabel(), normalFont)); - t.addCell(new Phrase(String.valueOf(reportsDatas.getAmountDebit()), normalFont)); - t.addCell(new Phrase(String.valueOf(reportsDatas.getAmountCredit()), normalFont)); - t.addCell(new Phrase(soldeDebit, normalFont)); - t.addCell(new Phrase(soldeCredit, normalFont)); - } - } catch (DocumentException eeDE) { - log.error("Can't create table", eeDE); + t.addCell(new Phrase(reportsDatas.getAccount().getAccountNumber(), normalFont)); + t.addCell(new Phrase(reportsDatas.getAccount().getLabel(), normalFont)); + t.addCell(new Phrase(String.valueOf(reportsDatas.getAmountDebit()), normalFont)); + t.addCell(new Phrase(String.valueOf(reportsDatas.getAmountCredit()), normalFont)); + t.addCell(new Phrase(soldeDebit, normalFont)); + t.addCell(new Phrase(soldeCredit, normalFont)); + } + } catch (DocumentException eeDE) { + log.error("Can't create table", eeDE); + } - return t; - } - - public Table createBalanceAmountTable(String title, BigDecimal amountDebit, BigDecimal amountCredit, BigDecimal soldeDebit, BigDecimal soldeCredit){ - Table t = null; - try { - t = new Table(5,1); - float[] widths = {0.4f,0.15f, 0.15f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setWidth(100f); - t.setPadding(3f); - t.setOffset(0); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.RIGHT); - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - t.setDefaultCell(cell); + return t; + } - t.addCell(new Phrase(title, boldFont)); - t.addCell(new Phrase(amountDebit.toString(), boldFont)); - t.addCell(new Phrase(amountCredit.toString(), boldFont)); - t.addCell(new Phrase(soldeDebit.toString(), boldFont)); - t.addCell(new Phrase(soldeCredit.toString(), boldFont)); - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - } - - //############## General EntryBook ############## - - - @Override - public void createGeneralEntryBooksDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException { - Document document = new Document(PageSize.A4, 8, 8, 8, 8); - TopiaContext transaction = null; + public Table createBalanceAmountTable(String title, + BigDecimal amountDebit, + BigDecimal amountCredit, + BigDecimal soldeDebit, + BigDecimal soldeCredit) { + Table t = null; + try { + t = new Table(5, 1); + float[] widths = {0.4f, 0.15f, 0.15f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setWidth(100f); + t.setPadding(3f); + t.setOffset(0); + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.RIGHT); + cell.setHorizontalAlignment(Element.ALIGN_RIGHT); + t.setDefaultCell(cell); - try { - transaction = beginTransaction(); - - Date newDate = new Date(); - String dateS = dateFormat.format(newDate); - String hourS = hourFormat.format(newDate); - - String filePath = path+File.separator+DocumentsEnum.GENERAL_ENTRYBOOK.getFileName(); - FileOutputStream fileOut = new FileOutputStream(filePath+format.getExtension()); + t.addCell(new Phrase(title, boldFont)); + t.addCell(new Phrase(amountDebit.toString(), boldFont)); + t.addCell(new Phrase(amountCredit.toString(), boldFont)); + t.addCell(new Phrase(soldeDebit.toString(), boldFont)); + t.addCell(new Phrase(soldeCredit.toString(), boldFont)); + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + } + + //############## General EntryBook ############## + + + @Override + public void createGeneralEntryBooksDocuments(Date beginDate, + Date endDate, + FormatsEnum format) throws LimaException { + TopiaContext transaction = beginTransaction(rootContext); + ; + Document document = new Document(PageSize.A4, 8, 8, 8, 8); + + try { + + Date newDate = new Date(); + String dateS = dateFormat.format(newDate); + String hourS = hourFormat.format(newDate); + + String filePath = path + File.separator + DocumentsEnum.GENERAL_ENTRYBOOK.getFileName(); + FileOutputStream fileOut = new FileOutputStream(filePath + format.getExtension()); switch (format) { - case HTML: - HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); - break; - case PDF: - PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); - break; + case HTML: + HtmlWriter htmlWriter = HtmlWriter.getInstance(document, fileOut); + break; + case PDF: + PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOut); + break; } document.open(); int nbpages = 1; - + Identity identity = identityService.getIdentity(); - + FinancialPeriodDAO financialPeriodDAO = - LimaCallaoDAOHelper.getFinancialPeriodDAO(transaction); + LimaCallaoDAOHelper.getFinancialPeriodDAO(transaction); ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = - LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(transaction); + LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(transaction); EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(transaction); - + TopiaQuery financialPeriodsQuery = financialPeriodDAO.createQuery(); String beginDateProperty = TopiaQuery.getProperty(FinancialPeriod.BEGIN_DATE); String endDateProperty = TopiaQuery.getProperty(FinancialPeriod.BEGIN_DATE); financialPeriodsQuery.addWhere(beginDateProperty, Op.GE, beginDate) - .addWhere(endDateProperty, Op.LE, endDate) - .addOrder(beginDateProperty); + .addWhere(endDateProperty, Op.LE, endDate) + .addOrder(beginDateProperty); List<FinancialPeriod> financialPeriods = - financialPeriodDAO.findAllByQuery(financialPeriodsQuery); - + financialPeriodDAO.findAllByQuery(financialPeriodsQuery); + List<GeneralEntryBooksDatas> list = new ArrayList<GeneralEntryBooksDatas>(); BigDecimal amountDebit = new BigDecimal(0); BigDecimal amountCredit = new BigDecimal(0); for (FinancialPeriod financialPeriod : financialPeriods) { List<ClosedPeriodicEntryBook> closedPeriodicEntryBookList = - closedPeriodicEntryBookDAO.findAllByDates( - financialPeriod.getBeginDate(), financialPeriod.getEndDate()); - + closedPeriodicEntryBookDAO.findAllByDates( + financialPeriod.getBeginDate(), financialPeriod.getEndDate()); + BigDecimal subAmountDebit = new BigDecimal(0); BigDecimal subAmountCredit = new BigDecimal(0); for (ClosedPeriodicEntryBook closedPeriodicEntryBook : closedPeriodicEntryBookList) { - - List<Object[]> results = new ArrayList<Object[]>(); + + List<Object[]> results; TopiaQuery query = entryDAO.createQuery(); BigDecimal debit = new BigDecimal(0); BigDecimal credit = new BigDecimal(0); - + String financialPeriodProperty = TopiaQuery.getProperty( Entry.FINANCIAL_TRANSACTION, FinancialTransaction.FINANCIAL_PERIOD); @@ -1254,28 +1248,27 @@ Entry.FINANCIAL_TRANSACTION, FinancialTransaction.ENTRY_BOOK); query.addWhere(financialPeriodProperty, Op.EQ, - closedPeriodicEntryBook.getFinancialPeriod()) - .addWhere(entryBookProperty, Op.EQ, - closedPeriodicEntryBook.getEntryBook()) - .setSelect(Entry.DEBIT, "SUM("+Entry.AMOUNT+")") - .addGroup(Entry.DEBIT); + closedPeriodicEntryBook.getFinancialPeriod()) + .addWhere(entryBookProperty, Op.EQ, + closedPeriodicEntryBook.getEntryBook()) + .setSelect(Entry.DEBIT, "SUM(" + Entry.AMOUNT + ")") + .addGroup(Entry.DEBIT); results = query.execute(transaction); - + int nbAmount = results.size(); - if(nbAmount == 2){ - debit = (BigDecimal)results.get(0)[1]; - credit = (BigDecimal)results.get(1)[1]; + if (nbAmount == 2) { + debit = (BigDecimal) results.get(0)[1]; + credit = (BigDecimal) results.get(1)[1]; } - if (nbAmount == 1){ - if ((Boolean)results.get(0)[0]){ - debit = (BigDecimal)results.get(0)[1]; + if (nbAmount == 1) { + if ((Boolean) results.get(0)[0]) { + debit = (BigDecimal) results.get(0)[1]; + } else { + credit = (BigDecimal) results.get(0)[1]; } - else { - credit = (BigDecimal)results.get(0)[1]; - } } GeneralEntryBooksDatas generalEntryBooksDatas = - new GeneralEntryBooksDatasImpl(); + new GeneralEntryBooksDatasImpl(); generalEntryBooksDatas.setCode( closedPeriodicEntryBook.getEntryBook().getCode()); generalEntryBooksDatas.setDescription( @@ -1289,7 +1282,7 @@ subAmountDebit = subAmountDebit.add(debit); } GeneralEntryBooksDatas generalEntryBooksDatas = - new GeneralEntryBooksDatasImpl(); + new GeneralEntryBooksDatasImpl(); generalEntryBooksDatas.setSubAmount(true); generalEntryBooksDatas.setCredit(subAmountCredit); generalEntryBooksDatas.setDebit(subAmountDebit); @@ -1300,28 +1293,28 @@ amountDebit = amountDebit.add(subAmountDebit); } GeneralEntryBooksDatas generalEntryBooksDatas = - new GeneralEntryBooksDatasImpl(); + new GeneralEntryBooksDatasImpl(); generalEntryBooksDatas.setAmount(true); generalEntryBooksDatas.setCredit(amountCredit); generalEntryBooksDatas.setDebit(amountDebit); list.add(generalEntryBooksDatas); - + //create pages int i = 0; int n = list.size(); int max = n; // alloc nb rows max for pdf documents on one page - if (format == FormatsEnum.PDF){ + if (format == FormatsEnum.PDF) { max = 35; } - while (i < n){ + while (i < n) { int j = i + max; - if (j > n){ + if (j > n) { j = n; } - List <GeneralEntryBooksDatas> subList = - list.subList(i, j); + List<GeneralEntryBooksDatas> subList = + list.subList(i, j); //create page : header + table + footer Table headerTable = createGeneralEntryBooksHeaderTable(); Table table = createGeneralEntryBooksTable(subList); @@ -1347,164 +1340,158 @@ i = i + max; nbpages++; } - + document.close(); - - } catch (FileNotFoundException eeFNFE) { - log.error("Can't create pdf file", eeFNFE); - } catch (DocumentException eeDE) { - log.error("Can't create document", eeDE); - } catch (TopiaException eeTE) { - log.error("Can't get entries", eeTE); + + } catch (Exception eee) { + doCatch(transaction, eee); + } finally { + doFinally(transaction); } - - } - public Table createGeneralEntryBooksHeaderTable(){ - Table t = null; - try { - t = new Table(5,1); - float[] widths = {0.1f, 0.45f, 0.15f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setWidth(100f); - t.setPadding(3f); - //defaut cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_CENTER); - t.setDefaultCell(cell); - t.setOffset(8); - t.addCell(new Phrase(_("lima-business.document.entrybook"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.label"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.date"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.debit"), boldFont)); - t.addCell(new Phrase(_("lima-business.document.credit"), boldFont)); - - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - - } - - public Table createGeneralEntryBooksTable(List <GeneralEntryBooksDatas> list){ - int nbrow = list.size(); - Table t = null; - try { - //define table - t = new Table(5,nbrow); - t.setWidth(100f); - float[] widths = {0.1f, 0.45f, 0.15f, 0.15f, 0.15f}; - t.setWidths(widths); - t.setPadding(1.5f); - t.setBorderWidth(1); - t.setOffset(0); - //define default cell - Cell cell = new Cell(); - cell.setBorder(Rectangle.LEFT); - cell.setHorizontalAlignment(Element.ALIGN_RIGHT); - t.setDefaultCell(cell); - - for (GeneralEntryBooksDatas generalEntryBooksDatas : list) { - if (!generalEntryBooksDatas.getAmount() && !generalEntryBooksDatas.getSubAmount()){ - t.addCell(new Phrase( - generalEntryBooksDatas.getCode(), normalFont)); - t.addCell(new Phrase( - generalEntryBooksDatas.getDescription(), normalFont)); - t.addCell(new Phrase( - generalEntryBooksDatas.getPeriod(), normalFont)); - t.addCell(new Phrase( - String.valueOf(generalEntryBooksDatas.getDebit()), - normalFont)); - t.addCell(new Phrase( - String.valueOf(generalEntryBooksDatas.getCredit()), - normalFont)); - } - else { - Phrase phrase = null; - if (generalEntryBooksDatas.getAmount()){ - phrase = new Phrase(_("lima-business.document.amounts"), - boldFont); - } - else { - phrase = new Phrase(_("lima-business.document.amounts") - + " " + generalEntryBooksDatas.getPeriod(), - boldFont); - } - Cell cell2 = new Cell(phrase); - cell2.setBorder(Rectangle.TOP+Rectangle.BOTTOM); - cell2.setColspan(3); - t.addCell(cell2); - cell2 = new Cell(new Phrase( - String.valueOf(generalEntryBooksDatas.getDebit()), - boldFont)); - cell2.setBorder(Rectangle.TOP+Rectangle.BOTTOM); - t.addCell(cell2); - cell2 = new Cell(new Phrase( - String.valueOf(generalEntryBooksDatas.getCredit()), - boldFont)); - cell2.setBorder(Rectangle.TOP+Rectangle.BOTTOM); - t.addCell(cell2); - } - } - - } catch (BadElementException eeBEE) { - log.error("Can't create table", eeBEE); - } - return t; - } - + } + + public Table createGeneralEntryBooksHeaderTable() { + Table t = null; + try { + t = new Table(5, 1); + float[] widths = {0.1f, 0.45f, 0.15f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setWidth(100f); + t.setPadding(3f); + //defaut cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_CENTER); + t.setDefaultCell(cell); + t.setOffset(8); + t.addCell(new Phrase(_("lima-business.document.entrybook"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.label"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.date"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.debit"), boldFont)); + t.addCell(new Phrase(_("lima-business.document.credit"), boldFont)); + + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + + } + + protected Table createGeneralEntryBooksTable(List<GeneralEntryBooksDatas> list) { + int nbrow = list.size(); + Table t = null; + try { + //define table + t = new Table(5, nbrow); + t.setWidth(100f); + float[] widths = {0.1f, 0.45f, 0.15f, 0.15f, 0.15f}; + t.setWidths(widths); + t.setPadding(1.5f); + t.setBorderWidth(1); + t.setOffset(0); + //define default cell + Cell cell = new Cell(); + cell.setBorder(Rectangle.LEFT); + cell.setHorizontalAlignment(Element.ALIGN_RIGHT); + t.setDefaultCell(cell); + + for (GeneralEntryBooksDatas generalEntryBooksDatas : list) { + if (!generalEntryBooksDatas.getAmount() && !generalEntryBooksDatas.getSubAmount()) { + t.addCell(new Phrase( + generalEntryBooksDatas.getCode(), normalFont)); + t.addCell(new Phrase( + generalEntryBooksDatas.getDescription(), normalFont)); + t.addCell(new Phrase( + generalEntryBooksDatas.getPeriod(), normalFont)); + t.addCell(new Phrase( + String.valueOf(generalEntryBooksDatas.getDebit()), + normalFont)); + t.addCell(new Phrase( + String.valueOf(generalEntryBooksDatas.getCredit()), + normalFont)); + } else { + Phrase phrase; + if (generalEntryBooksDatas.getAmount()) { + phrase = new Phrase(_("lima-business.document.amounts"), + boldFont); + } else { + phrase = new Phrase(_("lima-business.document.amounts") + + " " + generalEntryBooksDatas.getPeriod(), + boldFont); + } + Cell cell2 = new Cell(phrase); + cell2.setBorder(Rectangle.TOP + Rectangle.BOTTOM); + cell2.setColspan(3); + t.addCell(cell2); + cell2 = new Cell(new Phrase( + String.valueOf(generalEntryBooksDatas.getDebit()), + boldFont)); + cell2.setBorder(Rectangle.TOP + Rectangle.BOTTOM); + t.addCell(cell2); + cell2 = new Cell(new Phrase( + String.valueOf(generalEntryBooksDatas.getCredit()), + boldFont)); + cell2.setBorder(Rectangle.TOP + Rectangle.BOTTOM); + t.addCell(cell2); + } + } + + } catch (BadElementException eeBEE) { + log.error("Can't create table", eeBEE); + } + return t; + } + //############## VAT ############## - + @Override - public void createVatDocuments(Date beginDate, Date endDate, FormatsEnum format, String autocomplete) - throws LimaException, IOException, COSVisitorException { - - TopiaContext transaction = null; - + public void createVatDocuments(Date beginDate, + Date endDate, + FormatsEnum format, + String autocomplete) throws LimaException { + String filePath = path + File.separator - + DocumentsEnum.VAT.getFileName() + format.getExtension(); - - String path = LimaConfig.getInstance().getReportsDir(); - + + DocumentsEnum.VAT.getFileName() + format.getExtension(); + + String path = LimaConfig.getInstance().getReportsDir().getAbsolutePath(); + String filePathDefault = path + File.separator - + DocumentsEnum.VAT.getFileName() + "_default.pdf"; - - PDDocument doc = null; - InputStream reportsStream = null; - + + DocumentsEnum.VAT.getFileName() + "_default.pdf"; + + PDDocument doc; + InputStream reportsStream; + String vatPDFUrl = LimaConfig.getInstance().getVatPDFUrl(); - + if (vatPDFUrl.equals("default")) { reportsStream = DocumentServiceImpl.class .getResourceAsStream("/reports/vat_form_fr.pdf"); if (reportsStream == null) { - throw new LimaException ("Could not find such file " - + "/reports/vat_form_fr.pdf"); + throw new LimaException("Could not find such file " + + "/reports/vat_form_fr.pdf"); } } else { try { reportsStream = new FileInputStream(filePathDefault); } catch (FileNotFoundException eee) { throw new LimaException("Could not find such file " - + filePathDefault, eee); + + filePathDefault, eee); } } - + try { - - transaction = beginTransaction(); - + // load the document doc = PDDocument.load(reportsStream); - + if (autocomplete.equals("true")) { SetField fields = new SetField(); - + //search for all VAT Statements from the report List<VatStatement> vatStatementsList = vatStatementService.getAllVatStatements(); - for (VatStatement vatStatement: vatStatementsList) { + for (VatStatement vatStatement : vatStatementsList) { //search for amount to display BigDecimal amount = vatStatementService.vatStatementAmounts(vatStatement, beginDate, endDate).getAmount(); //display amount only if it is a child and has a BoxName @@ -1519,16 +1506,7 @@ doc.close(); } catch (Exception eee) { - log.error("Can't create VAT form", eee); + doCatch(null, eee); } } - - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryBookServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryBookServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryBookServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,12 +25,6 @@ package org.chorem.lima.business.ejb; -import static org.nuiton.i18n.I18n._; -import java.util.ArrayList; -import java.util.List; -import javax.ejb.Stateless; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.business.AccountingRules; import org.chorem.lima.business.LimaBusinessException; import org.chorem.lima.business.LimaConfig; @@ -46,10 +40,14 @@ import org.chorem.lima.entity.FinancialPeriodDAO; import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; +import javax.ejb.Stateless; +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n._; + /** * Implémente la fonction multi-EntryBook. Il est possible de créer ici le * EntryBook des ventes, le EntryBook des achats, etc. @@ -59,56 +57,47 @@ @Stateless public class EntryBookServiceImpl extends AbstractLimaService implements EntryBookService, EntryBookServiceLocal { - private static final Log log = LogFactory.getLog(EntryBookServiceImpl.class); - private TopiaContext rootContext; - + protected AccountingRules accountingRules; public EntryBookServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - accountingRules = config.getAccountingRules(); + rootContext = acquireRootContext(); + accountingRules = LimaConfig.getInstance().getAccountingRules(); } - @Override - public void createEntryBookWithTransaction(EntryBook entryBook, TopiaContext topiaContext) + public void createEntryBookWithTransaction(EntryBook entryBook, + TopiaContext topiaContext) throws LimaException { try { // check if entrybook with is name already exist EntryBookDAO entryBookDAO = - LimaCallaoDAOHelper.getEntryBookDAO(topiaContext); + LimaCallaoDAOHelper.getEntryBookDAO(topiaContext); EntryBook existingEntryBook = - entryBookDAO.findByLabel(entryBook.getCode()); + entryBookDAO.findByLabel(entryBook.getCode()); if (existingEntryBook != null) { throw new LimaBusinessException( _("lima-business.entrybook.entrybookalreadyexist", - entryBook.getLabel())); + entryBook.getLabel())); } // creation du EntryBook entryBookDAO.create(entryBook); - + //create ClosedPeriodicEntryBook for all unblocked financial period - ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = - LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); + ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = + LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); FinancialPeriodDAO financialPeriodDAO = - LimaCallaoDAOHelper.getFinancialPeriodDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialPeriodDAO(topiaContext); // for all unblocked financialperiod for (FinancialPeriod financialPeriod : financialPeriodDAO.findAllByLocked(false)) { - + //new closed periodic entrybook ClosedPeriodicEntryBook closedPeriodicEntryBook = - new ClosedPeriodicEntryBookImpl(); + new ClosedPeriodicEntryBookImpl(); // set entrybook closedPeriodicEntryBook.setEntryBook(entryBook); // set financial period @@ -118,168 +107,111 @@ } commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - + } - - /** - * Création d'un EntryBook. Il peut être unique sur son label (au choix). - * - * @param EntryBook EntryBook - * @return - * @throws LimaException - */ + + @Override public void createEntryBook(EntryBook entryBook) throws LimaException { - - TopiaContext transaction = null; - + + TopiaContext transaction = beginTransaction(rootContext); + try { - transaction = beginTransaction(); createEntryBookWithTransaction(entryBook, transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - /** - * return all entrybook - */ + @Override public List<EntryBook> getAllEntryBooks() throws LimaException { - + List<EntryBook> entryBooksList = new ArrayList<EntryBook>(); - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); // check if entrybook with is name already exist EntryBookDAO entryBookDAO = - LimaCallaoDAOHelper.getEntryBookDAO(transaction); + LimaCallaoDAOHelper.getEntryBookDAO(transaction); List<EntryBook> entryBooks = entryBookDAO.findAll(); entryBooksList.addAll(entryBooks); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return entryBooksList; } - + @Override - public List<EntryBook> getAllEntryByProperty(String propertyName, String value) throws LimaException { + public List<EntryBook> getAllEntryByProperty(String propertyName, + String value) throws LimaException { List<EntryBook> entryBookList = null; - - TopiaContext transaction = null; - + + TopiaContext transaction = beginTransaction(rootContext); + try { - transaction = beginTransaction(); - + EntryBookDAO entryBookDAO = - LimaCallaoDAOHelper.getEntryBookDAO(transaction); + LimaCallaoDAOHelper.getEntryBookDAO(transaction); entryBookList = entryBookDAO.findAllByProperty(propertyName, value); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return entryBookList; } - - /** - * Permet de modifier un journal. - * - * @param entryBook journal - * @throws LimaException - * - */ + + @Override public void updateEntryBook(EntryBook entryBook) throws LimaException { - TopiaContext transaction = null; - + TopiaContext transaction = beginTransaction(rootContext); + try { - transaction = beginTransaction(); EntryBookDAO entryBookDAO = - LimaCallaoDAOHelper.getEntryBookDAO(transaction); + LimaCallaoDAOHelper.getEntryBookDAO(transaction); // creation du EntryBook entryBookDAO.update(entryBook); commitTransaction(transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - /** - * Permet d'effacer un EntryBook dans la base de données. - * - * ATTENTION : si un EntryBook est associé avec des entrées, il est alors - * impossible de supprimer celui-ci. - * - * @param prefix préfixe du EntryBook à supprimer - * @throws LimaException - */ + @Override public void removeEntryBook(EntryBook entryBook) throws LimaException { - TopiaContext topiaTransaction = null; - + TopiaContext topiaTransaction = beginTransaction(rootContext); + try { - topiaTransaction = beginTransaction(); //check accountingRules.removeEntryBookRules(entryBook, topiaTransaction); - + //delete EntryBookDAO entryBookDAO = - LimaCallaoDAOHelper.getEntryBookDAO(topiaTransaction); + LimaCallaoDAOHelper.getEntryBookDAO(topiaTransaction); entryBookDAO.delete(entryBook); commitTransaction(topiaTransaction); + } catch (Exception ex) { + doCatch(topiaTransaction, ex); + } finally { + doFinally(topiaTransaction); } - catch (TopiaException ex) { - doCatch(topiaTransaction, ex, log); - } - finally { - doFinally(topiaTransaction, log); - } } - - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } - - protected void commitTransaction(TopiaContext topiaTransaction) throws TopiaException { - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ExportServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ExportServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ExportServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,16 +25,9 @@ package org.chorem.lima.business.ejb; -import java.io.IOException; -import java.io.StringWriter; -import java.text.SimpleDateFormat; -import java.util.List; -import javax.ejb.Stateless; +import au.com.bytecode.opencsv.CSVWriter; import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.FinancialStatementWayEnum; -import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; import org.chorem.lima.business.ejbinterface.ExportService; import org.chorem.lima.business.ejbinterface.ExportServiceLocal; @@ -58,43 +51,36 @@ import org.chorem.lima.entity.VatStatement; import org.chorem.lima.entity.VatStatementDAO; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; -import au.com.bytecode.opencsv.CSVWriter; +import javax.ejb.Stateless; +import java.io.StringWriter; +import java.text.SimpleDateFormat; +import java.util.List; /** * CSV import export service. - * + * * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Stateless public class ExportServiceImpl extends AbstractLimaService implements ExportService, ExportServiceLocal { - private static final Log log = - LogFactory.getLog(ExportServiceImpl.class); - private TopiaContext rootContext; - - private static final SimpleDateFormat SDATEFORMAT = new SimpleDateFormat("dd,MM,yyyy HH:mm:ss"); + private static final SimpleDateFormat SDATEFORMAT = + new SimpleDateFormat("dd,MM,yyyy HH:mm:ss"); + public ExportServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } + rootContext = acquireRootContext(); } //############## EXPORT EBP + /** * Export entries to EBP * Struturce example : 1,010101,VE,411ART,, "Ventes d’ordinateur ", "123 ",12548.95,D,010301, @@ -102,105 +88,96 @@ */ @Override public String exportEntriesAsEBP() throws LimaException { - TopiaContext topiaContext = null; SimpleDateFormat epbDateFormat = new SimpleDateFormat("ddMMyyyy"); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); int num = 0; - + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); + //export entries FinancialTransactionDAO financialTransactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); List<FinancialTransaction> listFinancialTransaction = - financialTransactionDAO.findAll(); + financialTransactionDAO.findAll(); // For all financialTransaction for (FinancialTransaction financialTransaction : listFinancialTransaction) { String date = epbDateFormat.format(financialTransaction.getTransactionDate()); String entrybookCode = ""; EntryBook entryBook = financialTransaction.getEntryBook(); - - if (entryBook != null){ + + if (entryBook != null) { entrybookCode = entryBook.getCode(); } - + String[] nextLine = new String[11]; for (Entry entry : financialTransaction.getEntry()) { num++; Account account = entry.getAccount(); - + String accountNumber = ""; - if (account != null){ + if (account != null) { accountNumber = entry.getAccount().getAccountNumber(); } - + String debitcredit = ""; - if (entry.getDebit()){ + if (entry.getDebit()) { debitcredit = "D"; - } - else { + } else { debitcredit = "C"; } - + nextLine[0] = String.valueOf(num); nextLine[1] = date; nextLine[2] = entrybookCode; nextLine[3] = accountNumber; - nextLine[5] = '"'+entry.getDescription()+'"'; - nextLine[6] = '"'+entry.getVoucher()+'"'; + nextLine[5] = '"' + entry.getDescription() + '"'; + nextLine[6] = '"' + entry.getVoucher() + '"'; nextLine[7] = entry.getAmount().toString(); nextLine[8] = debitcredit; // Ajoute la ligne au fichier - for (int i=0; i<9; i++){ + for (int i = 0; i < 9; i++) { String string = ""; String nextln = nextLine[i]; - if (nextln != null){ + if (nextln != null) { string = nextln; } - if (i==8){ - result.append(string+"\r\n"); + if (i == 8) { + result.append(string).append("\r\n"); + } else { + result.append(string).append(","); } - else { - result.append(string+","); - } } } } + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); + } finally { + doFinally(topiaContext); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } - /*catch (IOException eeeIO) { - log.debug("Can't create new CSV Writer",eeeIO); - }*/ - finally { - doFinally(topiaContext, log); - } - return result.toString(); + return result.toString(); } - + /** * Export accounts chart to EBP * Structure ebp - example : * 411DUPOND,DUPOND,,21 rue du bois, 78120, Rambouillet, France,,0135698475,0135698475 - * */ @Override public String exportAccountsAsEBP() throws LimaException { - TopiaContext topiaContext = null; StringWriter out = new StringWriter(); CSVWriter csvWriter; - + TopiaContext topiaContext = beginTransaction(rootContext); + try { - topiaContext = beginTransaction(); csvWriter = new CSVWriter(out, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); //export accounts String[] nextLine = new String[10]; // Récupère tous les comptes AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(topiaContext); + LimaCallaoDAOHelper.getAccountDAO(topiaContext); List<Account> listAccount = accountDAO.findAll(); // Pour tous les comptes for (Account account : listAccount) { @@ -212,35 +189,26 @@ // Write cache in string csvWriter.flush(); csvWriter.close(); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); + } finally { + doFinally(topiaContext); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } - catch (IOException eeeIO) { - log.error("Can't create new CSV Writer",eeeIO); - } - finally { - doFinally(topiaContext, log); - } - return out.getBuffer().toString(); + return out.getBuffer().toString(); } - - - + + //############## EXPORT CSV - - /** - * Export integrality of database in CSV - */ + + /** Export integrality of database in CSV */ @Override public String exportAsCSV() throws LimaException { - TopiaContext topiaContext = null; StringWriter out = new StringWriter(); CSVWriter csvWriter; - + TopiaContext topiaContext = beginTransaction(rootContext); + try { - topiaContext = beginTransaction(); csvWriter = new CSVWriter(out, ';'); exportAccountsChartAsCSV(csvWriter, topiaContext); exportEntryBookChartAsCSV(csvWriter, topiaContext); @@ -252,68 +220,61 @@ // Write cache in string csvWriter.flush(); csvWriter.close(); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); + } finally { + doFinally(topiaContext); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } - catch (IOException eeeIO) { - log.error("Can't create new CSV Writer",eeeIO); - } - finally { - doFinally(topiaContext, log); - } - return out.getBuffer().toString(); + return out.getBuffer().toString(); } - - /** - * Remote methode call from UI. - */ + + /** Remote methode call from UI. */ @Override public String exportFinancialStatementChartAsCSV() throws LimaException { - TopiaContext topiaContext = null; + StringWriter out = new StringWriter(); CSVWriter csvWriter; - + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); csvWriter = new CSVWriter(out, ';'); exportFinancialStatementChartAsCSV(csvWriter, topiaContext); // Write cache in file csvWriter.flush(); csvWriter.close(); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); + } finally { + doFinally(topiaContext); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } - catch (IOException eeeIO) { - log.error("Can't create new CSV Writer",eeeIO); - } - finally { - doFinally(topiaContext, log); - } return out.getBuffer().toString(); } - + /** * Local methode, export financialstatements from database * structure : TYPE | Label | Header | Accounts | DebitAccounts - * | CreditAccounts | ProvisionDeprecationAccounts | SubAmount - * | HeaderAmount | MasterFinancialStatement + * | CreditAccounts | ProvisionDeprecationAccounts | SubAmount + * | HeaderAmount | MasterFinancialStatement + * + * @param csvWriter + * @param topiaContext + * @throws LimaException */ - public void exportFinancialStatementChartAsCSV(CSVWriter csvWriter, TopiaContext topiaContext) throws LimaException { + public void exportFinancialStatementChartAsCSV(CSVWriter csvWriter, + TopiaContext topiaContext) throws LimaException { try { String[] nextLine = new String[12]; // Get all Financialstatements FinancialStatementDAO financialStatementDAO = - LimaCallaoDAOHelper.getFinancialStatementDAO(topiaContext); - - TopiaQuery query = financialStatementDAO.createQuery(); - query.addOrder(FinancialStatement.TOPIA_CREATE_DATE); + LimaCallaoDAOHelper.getFinancialStatementDAO(topiaContext); + + TopiaQuery query = financialStatementDAO.createQuery(); + query.addOrder(FinancialStatement.TOPIA_CREATE_DATE); List<FinancialStatement> listFinancialStatements = - financialStatementDAO.findAllByQuery(query); - + financialStatementDAO.findAllByQuery(query); + // For all Financialstatements for (FinancialStatement financialStatement : listFinancialStatements) { nextLine[0] = ImportExportEntityEnum.FINANCIALSTATEMENT.getLabel(); @@ -324,82 +285,79 @@ nextLine[4] = financialStatement.getDebitAccounts(); nextLine[5] = financialStatement.getCreditAccounts(); nextLine[6] = financialStatement. - getProvisionDeprecationAccounts(); + getProvisionDeprecationAccounts(); nextLine[7] = Boolean.toString( financialStatement.getSubAmount()); nextLine[8] = Boolean.toString( financialStatement.getHeaderAmount()); FinancialStatement masterFinancialStatement = - financialStatement.getMasterFinancialStatement(); + financialStatement.getMasterFinancialStatement(); String masterFinancialStatementString = ""; - if (masterFinancialStatement != null){ + if (masterFinancialStatement != null) { masterFinancialStatementString = - masterFinancialStatement.getLabel(); + masterFinancialStatement.getLabel(); } nextLine[9] = masterFinancialStatementString; FinancialStatementWayEnum financialStatementWayEnum = financialStatement.getWay(); String financialStatementWay = ""; - if (financialStatementWayEnum != null){ + if (financialStatementWayEnum != null) { financialStatementWay = financialStatementWayEnum.name(); } nextLine[10] = financialStatementWay; // Add line in file csvWriter.writeNext(nextLine); } + } catch (TopiaException eeeTE) { + doCatch(topiaContext, eeeTE); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } } - - /** - * Remote method call from UI. - */ + + /** Remote method call from UI. */ @Override public String exportVatStatementChartAsCSV() throws LimaException { - - TopiaContext topiaContext = null; + StringWriter out = new StringWriter(); CSVWriter csvWriter; - + + TopiaContext topiaContext = beginTransaction(rootContext); + try { - topiaContext = beginTransaction(); csvWriter = new CSVWriter(out, ';'); exportVatStatementChartAsCSV(csvWriter, topiaContext); // Write cache in file csvWriter.flush(); csvWriter.close(); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); + } finally { + doFinally(topiaContext); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } - catch (IOException eeeIO) { - log.error("Can't create new CSV Writer",eeeIO); - } - finally { - doFinally(topiaContext, log); - } return out.getBuffer().toString(); - + } - + /** * Local methode, export vatstatements from database * vatstatement Structure : TYPE | boxName | label | header * | accounts | masterVatStatement + * + * @param csvWriter + * @param topiaContext + * @throws LimaException */ - public void exportVatStatementChartAsCSV(CSVWriter csvWriter, TopiaContext topiaContext) throws LimaException { + public void exportVatStatementChartAsCSV(CSVWriter csvWriter, + TopiaContext topiaContext) throws LimaException { try { String[] nextLine = new String[6]; // Get all Vatstatements VatStatementDAO vatStatementDAO = - LimaCallaoDAOHelper.getVatStatementDAO(topiaContext); - - TopiaQuery query = vatStatementDAO.createQuery(); - query.addOrder(VatStatement.TOPIA_CREATE_DATE); + LimaCallaoDAOHelper.getVatStatementDAO(topiaContext); + + TopiaQuery query = vatStatementDAO.createQuery(); + query.addOrder(VatStatement.TOPIA_CREATE_DATE); List<VatStatement> listVatStatements = - vatStatementDAO.findAllByQuery(query); - + vatStatementDAO.findAllByQuery(query); + // For all Vatstatements for (VatStatement vatStatement : listVatStatements) { nextLine[0] = ImportExportEntityEnum.VATSTATEMENT.getLabel(); @@ -411,121 +369,116 @@ VatStatement masterVatStatement = vatStatement.getMasterVatStatement(); String masterVatStatementString = ""; - if (masterVatStatement != null){ + if (masterVatStatement != null) { masterVatStatementString = - masterVatStatement.getLabel(); + masterVatStatement.getLabel(); } nextLine[5] = masterVatStatementString; - + csvWriter.writeNext(nextLine); } + } catch (TopiaException eeeTE) { + doCatch(topiaContext, eeeTE); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } } - - /** - * Remote methode call from UI. - */ + + /** Remote methode call from UI. */ @Override public String exportEntryBookChartAsCSV() throws LimaException { - TopiaContext topiaContext = null; + StringWriter out = new StringWriter(); CSVWriter csvWriter; + TopiaContext topiaContext = beginTransaction(rootContext); + try { - topiaContext = beginTransaction(); csvWriter = new CSVWriter(out, ';'); exportEntryBookChartAsCSV(csvWriter, topiaContext); // Write cache in file csvWriter.flush(); csvWriter.close(); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); + } finally { + doFinally(topiaContext); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } - catch (IOException eeeIO) { - log.error("Can't create new CSV Writer",eeeIO); - } - finally { - doFinally(topiaContext, log); - } return out.getBuffer().toString(); } - - + + /** * Local methode, export entrybooks from database * Structure : TYPE | Code | Label | Type - */ - public void exportEntryBookChartAsCSV(CSVWriter csvWriter, TopiaContext topiaContext) throws LimaException { + * + * @param csvWriter + * @param topiaContext + * @throws LimaException + */ + public void exportEntryBookChartAsCSV(CSVWriter csvWriter, + TopiaContext topiaContext) throws LimaException { try { String[] nextLine = new String[3]; // Get all entrybook EntryBookDAO entryBookDAO = - LimaCallaoDAOHelper.getEntryBookDAO(topiaContext); + LimaCallaoDAOHelper.getEntryBookDAO(topiaContext); List<EntryBook> listEntryBook = entryBookDAO.findAll(); // For all EntryBook for (EntryBook entryBook : listEntryBook) { - nextLine[0] = ImportExportEntityEnum.ENTRYBOOK.getLabel(); + nextLine[0] = ImportExportEntityEnum.ENTRYBOOK.getLabel(); nextLine[1] = entryBook.getCode(); nextLine[2] = entryBook.getLabel(); // Ajoute la ligne au fichier csvWriter.writeNext(nextLine); } + } catch (TopiaException eeeTE) { + doCatch(topiaContext, eeeTE); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } } - - /** - * Remote methode call from UI. - */ + + /** Remote methode call from UI. */ @Override public String exportAccountsChartAsCSV() throws LimaException { - TopiaContext topiaContext = null; StringWriter out = new StringWriter(); CSVWriter csvWriter; - + + TopiaContext topiaContext = beginTransaction(rootContext); + try { - topiaContext = beginTransaction(); csvWriter = new CSVWriter(out, ';'); exportAccountsChartAsCSV(csvWriter, topiaContext); // Write cache in file csvWriter.flush(); csvWriter.close(); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); + } finally { + doFinally(topiaContext); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } - catch (IOException eeeIO) { - log.error("Can't create new CSV Writer",eeeIO); - } - finally { - doFinally(topiaContext, log); - } return out.getBuffer().toString(); } - + /** * Local methode, export accounts from database * Structure : TYPE | AccountNumber | Label | ThirdParty | MasterAccount | GeneralLedger + * + * @param csvWriter + * @param topiaContext + * @throws LimaException */ - public void exportAccountsChartAsCSV(CSVWriter csvWriter, TopiaContext topiaContext) throws LimaException { + public void exportAccountsChartAsCSV(CSVWriter csvWriter, + TopiaContext topiaContext) throws LimaException { try { String[] nextLine = new String[6]; // Récupère tous les comptes AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(topiaContext); + LimaCallaoDAOHelper.getAccountDAO(topiaContext); List<Account> listAccount = accountDAO.findAll(); // Pour tous les comptes for (Account account : listAccount) { - nextLine[0] = ImportExportEntityEnum.ACCOUNT.getLabel(); + nextLine[0] = ImportExportEntityEnum.ACCOUNT.getLabel(); nextLine[1] = account.getAccountNumber(); nextLine[2] = account.getLabel(); nextLine[3] = account.getThirdParty(); @@ -533,11 +486,11 @@ Account generalLedger = account.getGeneralLedger(); String masterAccountString = ""; String generalLedgerString = ""; - if (masterAccount != null){ + if (masterAccount != null) { masterAccountString = masterAccount.getAccountNumber(); } nextLine[4] = masterAccountString; - if (generalLedger != null){ + if (generalLedger != null) { generalLedgerString = generalLedger.getAccountNumber(); } nextLine[5] = generalLedgerString; @@ -545,48 +498,52 @@ // Ajoute la ligne au fichier csvWriter.writeNext(nextLine); } + } catch (TopiaException eeeTE) { + doCatch(topiaContext, eeeTE); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } } - + /** * Local methode, export financialtransactions from database * Structure : TYPE | TransactionDate | AmountDebit | AmountCredit - * | FinancialPeriod BeginDate | FinancialPeriod EndDate | EntryBook Code + * | FinancialPeriod BeginDate | FinancialPeriod EndDate | EntryBook Code + * + * @param csvWriter + * @param topiaContext + * @throws LimaException */ - public void exportFinancialTransactionsAndEntriesAsCSV(CSVWriter csvWriter, TopiaContext topiaContext) throws LimaException { + public void exportFinancialTransactionsAndEntriesAsCSV(CSVWriter csvWriter, + TopiaContext topiaContext) throws LimaException { int numTransaction = 0; // Get all financialtransactions try { FinancialTransactionDAO financialTransactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); List<FinancialTransaction> listFinancialTransaction = - financialTransactionDAO.findAll(); + financialTransactionDAO.findAll(); // For all financialTransaction for (FinancialTransaction financialTransaction : listFinancialTransaction) { String[] nextLine = new String[8]; - nextLine[0] = ImportExportEntityEnum.FINANCIALTRANSACTION.getLabel(); + nextLine[0] = ImportExportEntityEnum.FINANCIALTRANSACTION.getLabel(); nextLine[1] = String.valueOf(numTransaction); nextLine[2] = - SDATEFORMAT.format(financialTransaction.getTransactionDate()); + SDATEFORMAT.format(financialTransaction.getTransactionDate()); nextLine[3] = financialTransaction.getAmountDebit().toString(); nextLine[4] = financialTransaction.getAmountCredit().toString(); nextLine[5] = - SDATEFORMAT.format(financialTransaction.getFinancialPeriod(). - getBeginDate()); + SDATEFORMAT.format(financialTransaction.getFinancialPeriod(). + getBeginDate()); nextLine[6] = - SDATEFORMAT.format(financialTransaction.getFinancialPeriod(). - getEndDate()); + SDATEFORMAT.format(financialTransaction.getFinancialPeriod(). + getEndDate()); EntryBook entryBook = financialTransaction.getEntryBook(); - if (entryBook != null){ + if (entryBook != null) { nextLine[7] = entryBook.getCode(); } // Ajoute la ligne au fichier csvWriter.writeNext(nextLine); - + nextLine = new String[10]; for (Entry entry : financialTransaction.getEntry()) { nextLine[0] = ImportExportEntityEnum.ENTRY.getLabel(); @@ -604,25 +561,29 @@ } numTransaction++; } + } catch (TopiaException eeeTE) { + doCatch(topiaContext, eeeTE); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } } - + /** * Local methode, export fiscalperiods from database * Structure : TYPE | BeginDate | EndDate | Locked + * + * @param csvWriter + * @param topiaContext + * @throws LimaException */ - public void exportFiscalPeriodAsCSV(CSVWriter csvWriter, TopiaContext topiaContext) throws LimaException { + public void exportFiscalPeriodAsCSV(CSVWriter csvWriter, + TopiaContext topiaContext) throws LimaException { try { String[] nextLine = new String[4]; // Get all fiscalperiod FiscalPeriodDAO fiscalPeriodDAO = - LimaCallaoDAOHelper.getFiscalPeriodDAO(topiaContext); + LimaCallaoDAOHelper.getFiscalPeriodDAO(topiaContext); List<FiscalPeriod> listFiscalPeriod = - fiscalPeriodDAO.findAll(); + fiscalPeriodDAO.findAll(); // For all Entry for (FiscalPeriod fiscalPeriod : listFiscalPeriod) { nextLine[0] = ImportExportEntityEnum.FISCALPERIOD.getLabel(); @@ -632,82 +593,76 @@ // Ajoute la ligne au fichier csvWriter.writeNext(nextLine); } + } catch (TopiaException eeeTE) { + doCatch(topiaContext, eeeTE); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } } - - + /** * Local methode, export ClosedPeriodicEntryBooks from database * Structure : TYPE | Locked | FinancialPeriod beginDate | FinancialPeriod endDate | EntryBook Code + * + * @param csvWriter + * @param topiaContext + * @throws LimaException */ - public void exportClosedPeriodicEntryBooksAsCSV(CSVWriter csvWriter, TopiaContext topiaContext) throws LimaException { + public void exportClosedPeriodicEntryBooksAsCSV(CSVWriter csvWriter, + TopiaContext topiaContext) throws LimaException { try { String[] nextLine = new String[5]; // Get all fiscalperiod ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = - LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); + LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); List<ClosedPeriodicEntryBook> listClosedPeriodicEntryBook = - closedPeriodicEntryBookDAO.findAll(); + closedPeriodicEntryBookDAO.findAll(); // For all Entry for (ClosedPeriodicEntryBook closedPeriodicEntryBook : listClosedPeriodicEntryBook) { - nextLine[0] = ImportExportEntityEnum.CLOSEDPERIODICENTRYBOOK.getLabel(); + nextLine[0] = ImportExportEntityEnum.CLOSEDPERIODICENTRYBOOK.getLabel(); nextLine[1] = Boolean.toString( closedPeriodicEntryBook.getLocked()); nextLine[2] = - SDATEFORMAT.format(closedPeriodicEntryBook.getFinancialPeriod(). - getBeginDate()); + SDATEFORMAT.format(closedPeriodicEntryBook.getFinancialPeriod(). + getBeginDate()); nextLine[3] = - SDATEFORMAT.format(closedPeriodicEntryBook.getFinancialPeriod(). - getEndDate()); + SDATEFORMAT.format(closedPeriodicEntryBook.getFinancialPeriod(). + getEndDate()); nextLine[4] = closedPeriodicEntryBook.getEntryBook().getCode(); // Ajoute la ligne au fichier csvWriter.writeNext(nextLine); } + } catch (TopiaException eeeTE) { + doCatch(topiaContext, eeeTE); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } } - - public void exportIdentityAsCSV(CSVWriter csvWriter, TopiaContext topiaContext) throws LimaException{ - try { - String[] nextLine = new String[12]; - // Get identity - IdentityDAO identityDAO = LimaCallaoDAOHelper.getIdentityDAO(topiaContext); - List<Identity> identities = identityDAO.findAll(); - if (identities.size() != 0){ - - Identity identity = identities.get(0); - nextLine[0] = ImportExportEntityEnum.IDENTITY.getLabel(); - nextLine[1] = identity.getName(); - nextLine[2] = identity.getDescription(); - nextLine[3] = identity.getAddress(); - nextLine[4] = identity.getAddress2(); - nextLine[5] = identity.getCity(); - nextLine[6] = identity.getPhoneNumber(); - nextLine[7] = identity.getEmail(); - nextLine[8] = identity.getZipCode(); - nextLine[9] = identity.getVatNumber(); - nextLine[10] = identity.getClassificationCode(); - nextLine[11] = identity.getBusinessNumber(); - // Ajoute la ligne au fichier - csvWriter.writeNext(nextLine); - } + + public void exportIdentityAsCSV(CSVWriter csvWriter, + TopiaContext topiaContext) throws LimaException { + try { + String[] nextLine = new String[12]; + // Get identity + IdentityDAO identityDAO = LimaCallaoDAOHelper.getIdentityDAO(topiaContext); + List<Identity> identities = identityDAO.findAll(); + if (identities.size() != 0) { + + Identity identity = identities.get(0); + nextLine[0] = ImportExportEntityEnum.IDENTITY.getLabel(); + nextLine[1] = identity.getName(); + nextLine[2] = identity.getDescription(); + nextLine[3] = identity.getAddress(); + nextLine[4] = identity.getAddress2(); + nextLine[5] = identity.getCity(); + nextLine[6] = identity.getPhoneNumber(); + nextLine[7] = identity.getEmail(); + nextLine[8] = identity.getZipCode(); + nextLine[9] = identity.getVatNumber(); + nextLine[10] = identity.getClassificationCode(); + nextLine[11] = identity.getBusinessNumber(); + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); } - catch (TopiaException eeeTE){ - doCatch(topiaContext, eeeTE, log); - } + } catch (TopiaException eeeTE) { + doCatch(topiaContext, eeeTE); + } } - - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialPeriodServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialPeriodServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialPeriodServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,11 +25,6 @@ package org.chorem.lima.business.ejb; -import java.util.Date; -import java.util.List; -import javax.ejb.Stateless; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.business.AccountingRules; import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; @@ -45,12 +40,14 @@ import org.chorem.lima.entity.FiscalPeriod; import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; +import javax.ejb.Stateless; +import java.util.Date; +import java.util.List; + /** * Gestion des périodes intermédiaires durant l'exercice. * Chaque timeSpan sera fixe, et devra correspondre à un mois complet. @@ -60,71 +57,58 @@ @Stateless public class FinancialPeriodServiceImpl extends AbstractLimaService implements FinancialPeriodService, FinancialPeriodServiceLocal { - /** log */ - private static final Log log = - LogFactory.getLog(FinancialPeriodServiceImpl.class); - private TopiaContext rootContext; - + protected AccountingRules accountingRules; public FinancialPeriodServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - - accountingRules = config.getAccountingRules(); + rootContext = acquireRootContext(); + accountingRules = LimaConfig.getInstance().getAccountingRules(); } /** * Création d'une période timeSpan mensuelle avec une date de début et de fin. Une période * peut être bloquée ou non - * @return */ @Override public void createFinancialPeriods(List<FinancialPeriod> financialPeriods) throws LimaException { - - TopiaContext topiaTransaction = null; + + TopiaContext topiaTransaction = beginTransaction(rootContext); try { - topiaTransaction = beginTransaction(); createFinancialPeriodsWithTransaction( financialPeriods, topiaTransaction); - + + } catch (Exception ex) { + doCatch(topiaTransaction, ex); + } finally { + doFinally(topiaTransaction); } - catch (TopiaException ex) { - doCatch(topiaTransaction, ex, log); - } } - - + + /** * Création d'une période timeSpan mensuelle avec une date de début et de fin. Une période * peut être bloquée ou non - * @return */ @Override - public void createFinancialPeriodsWithTransaction(List<FinancialPeriod> financialPeriods, TopiaContext topiaContext) throws LimaException { - + public void createFinancialPeriodsWithTransaction(List<FinancialPeriod> financialPeriods, + TopiaContext topiaContext) throws LimaException { + try { - + FinancialPeriodDAO financialPeriodDAO = - LimaCallaoDAOHelper.getFinancialPeriodDAO(topiaContext); - ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = - LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); - EntryBookDAO entryBookDAO = - LimaCallaoDAOHelper.getEntryBookDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialPeriodDAO(topiaContext); + ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = + LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); + EntryBookDAO entryBookDAO = + LimaCallaoDAOHelper.getEntryBookDAO(topiaContext); //create all financial period for (FinancialPeriod financialPeriod : financialPeriods) { //create ClosedPeriodicEntryBook for all entrybook for (EntryBook entryBook : entryBookDAO.findAll()) { //new closed periodic entrybook ClosedPeriodicEntryBook closedPeriodicEntryBook - = new ClosedPeriodicEntryBookImpl(); + = new ClosedPeriodicEntryBookImpl(); // set entrybook closedPeriodicEntryBook.setEntryBook(entryBook); // set financial period @@ -134,242 +118,194 @@ } //create financial period financialPeriodDAO.create(financialPeriod); - } + } commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } } - - /** - * Return all financial period - */ + + /** @return all financial period */ @Override public List<FinancialPeriod> getAllFinancialPeriods() throws LimaException { - + List<FinancialPeriod> result = null; - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); FinancialPeriodDAO financialPeriodDAO = LimaCallaoDAOHelper. - getFinancialPeriodDAO(transaction); - + getFinancialPeriodDAO(transaction); + TopiaQuery query = financialPeriodDAO.createQuery() - .addOrder(FinancialPeriod.BEGIN_DATE); - + .addOrder(FinancialPeriod.BEGIN_DATE); + result = financialPeriodDAO.findAllByQuery(query); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return result; } - - /** - * Return all unblocked financial period - */ + + /** @return all unblocked financial period */ @Override public List<FinancialPeriod> getUnblockedFinancialPeriods() throws LimaException { - + List<FinancialPeriod> result = null; - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); FinancialPeriodDAO financialPeriodDAO = LimaCallaoDAOHelper. - getFinancialPeriodDAO(transaction); - + getFinancialPeriodDAO(transaction); + TopiaQuery query = financialPeriodDAO.createQuery() - .addEquals(FinancialPeriod.LOCKED, Boolean.FALSE) - .addOrder(FinancialPeriod.BEGIN_DATE); - + .addEquals(FinancialPeriod.LOCKED, Boolean.FALSE) + .addOrder(FinancialPeriod.BEGIN_DATE); + result = financialPeriodDAO.findAllByQuery(query); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return result; } - - /** - * Return all financial period from a fiscal period - */ + + /** @return all financial period from a fiscal period */ @Override - public List<FinancialPeriod> getFinancialPeriods(Date beginDate, Date endDate) throws LimaException { - + public List<FinancialPeriod> getFinancialPeriods(Date beginDate, Date endDate) throws LimaException { + List<FinancialPeriod> result = null; - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - FinancialPeriodDAO financialPeriodDAO = LimaCallaoDAOHelper. - getFinancialPeriodDAO(transaction); - + getFinancialPeriodDAO(transaction); + TopiaQuery query = financialPeriodDAO.createQuery() - .addBetween(FinancialPeriod.BEGIN_DATE, beginDate, endDate) - .addOrder(FinancialPeriod.BEGIN_DATE); - + .addBetween(FinancialPeriod.BEGIN_DATE, beginDate, endDate) + .addOrder(FinancialPeriod.BEGIN_DATE); + result = financialPeriodDAO.findAllByQuery(query); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return result; } - + @Override public void blockClosedPeriodicEntryBookWithTransaction( ClosedPeriodicEntryBook closedPeriodicEntryBook, TopiaContext topiaContext) throws LimaException { - try { + try { //check rules before create the account accountingRules.blockClosedPeriodicEntryBookRules( closedPeriodicEntryBook, topiaContext); - + ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = - LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); - + LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); + ClosedPeriodicEntryBook closedPeriodicEntryBook2 = - closedPeriodicEntryBookDAO.findByTopiaId( - closedPeriodicEntryBook.getTopiaId()); - + closedPeriodicEntryBookDAO.findByTopiaId( + closedPeriodicEntryBook.getTopiaId()); + closedPeriodicEntryBook2.setLocked(true); closedPeriodicEntryBookDAO.update(closedPeriodicEntryBook2); - + commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } } - + @Override public void blockClosedPeriodicEntryBook(ClosedPeriodicEntryBook closedPeriodicEntryBook) throws LimaException { - - TopiaContext topiaContext = null; + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - + blockClosedPeriodicEntryBookWithTransaction(closedPeriodicEntryBook, topiaContext); - + commitTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } - + } @Override - public ClosedPeriodicEntryBook getClosedPeriodicEntryBook(EntryBook entryBook, FinancialPeriod financialPeriod) throws LimaException { + public ClosedPeriodicEntryBook getClosedPeriodicEntryBook(EntryBook entryBook, + FinancialPeriod financialPeriod) throws LimaException { ClosedPeriodicEntryBook closedPeriodicEntryBook = null; - - - TopiaContext topiaContext = null; + + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - + ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO = - LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); - + LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(topiaContext); + closedPeriodicEntryBook = closedPeriodicEntryBookDAO.findByEntryBookAndFinancialPeriod(entryBook, financialPeriod); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } - + return closedPeriodicEntryBook; } - + @Override public List<ClosedPeriodicEntryBook> getAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod() throws LimaException { - + List<ClosedPeriodicEntryBook> result = null; - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - + ClosedPeriodicEntryBookDAO closedPeriodicEntryBookDAO - = LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(transaction); - + = LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(transaction); + //Get closedperiodicentrybook from unlocked fiscalperiod TopiaQuery query = closedPeriodicEntryBookDAO.createQuery("E"); query.addFrom(FiscalPeriod.class, "F") - .addInElements("E." + ClosedPeriodicEntryBook.FINANCIAL_PERIOD, - "F."+FiscalPeriod.FINANCIAL_PERIOD) - .addEquals("F."+FiscalPeriod.LOCKED, Boolean.FALSE); + .addInElements("E." + ClosedPeriodicEntryBook.FINANCIAL_PERIOD, + "F." + FiscalPeriod.FINANCIAL_PERIOD) + .addEquals("F." + FiscalPeriod.LOCKED, Boolean.FALSE); String orderProperty = - TopiaQuery.getProperty("E", ClosedPeriodicEntryBook.FINANCIAL_PERIOD, - FinancialPeriod.BEGIN_DATE); + TopiaQuery.getProperty("E", ClosedPeriodicEntryBook.FINANCIAL_PERIOD, + FinancialPeriod.BEGIN_DATE); query.addOrder(orderProperty); - + //IMPORTANT : LOADING ClosedPeriodicEntryBook AND IS COLUMN FOR NO LAZY EXCEPTION String loadEntryBookProperty = - TopiaQuery.getProperty(ClosedPeriodicEntryBook.ENTRY_BOOK, - EntryBook.LABEL); + TopiaQuery.getProperty(ClosedPeriodicEntryBook.ENTRY_BOOK, + EntryBook.LABEL); query.addLoad(loadEntryBookProperty); String loadFinancialPeriodProperty = - TopiaQuery.getProperty(ClosedPeriodicEntryBook.FINANCIAL_PERIOD, - FinancialPeriod.BEGIN_DATE); + TopiaQuery.getProperty(ClosedPeriodicEntryBook.FINANCIAL_PERIOD, + FinancialPeriod.BEGIN_DATE); query.addLoad(loadFinancialPeriodProperty); - + //call query - result = closedPeriodicEntryBookDAO.findAllByQuery(query); + result = closedPeriodicEntryBookDAO.findAllByQuery(query); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return result; } - - - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } - - protected void commitTransaction(TopiaContext topiaTransaction) throws TopiaException { - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } - } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialStatementServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialStatementServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialStatementServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,17 +25,7 @@ package org.chorem.lima.business.ejb; -import static org.nuiton.i18n.I18n._; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.StringTokenizer; -import javax.ejb.EJB; -import javax.ejb.Stateless; import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.FinancialStatementWayEnum; import org.chorem.lima.beans.Amounts; import org.chorem.lima.beans.AmountsImpl; @@ -56,55 +46,52 @@ import org.chorem.lima.entity.FinancialStatementDAO; import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; import org.nuiton.topia.framework.TopiaQuery.Op; -@Stateless -public class FinancialStatementServiceImpl extends AbstractLimaService implements FinancialStatementService, FinancialStatementServiceLocal{ +import javax.ejb.EJB; +import javax.ejb.Stateless; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.StringTokenizer; - private static final Log log = - LogFactory.getLog(FinancialStatementServiceImpl.class); +import static org.nuiton.i18n.I18n._; +@Stateless +public class FinancialStatementServiceImpl extends AbstractLimaService implements FinancialStatementService, FinancialStatementServiceLocal { + private TopiaContext rootContext; protected AccountingRules accountingRules; - + @EJB private ReportServiceLocal reportServiceLocal; - + public FinancialStatementServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - accountingRules = config.getAccountingRules(); + rootContext = acquireRootContext(); + accountingRules = LimaConfig.getInstance().getAccountingRules(); } - + @Override - public void createFinancialStatementWithTransaction( - FinancialStatement masterFinancialStatement, - FinancialStatement financialStatement, TopiaContext topiaContext) - throws LimaException { + public void createFinancialStatementWithTransaction(FinancialStatement masterFinancialStatement, + FinancialStatement financialStatement, + TopiaContext topiaContext) throws LimaException { try { FinancialStatementDAO financialStatementDAO = - LimaCallaoDAOHelper.getFinancialStatementDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialStatementDAO(topiaContext); financialStatementDAO.create(financialStatement); FinancialStatement masterfinancialStatementUpdate = null; - if (masterFinancialStatement != null){ + if (masterFinancialStatement != null) { masterfinancialStatementUpdate = financialStatementDAO.findByLabel(masterFinancialStatement.getLabel()); } - + // check if parent account exist; if (masterfinancialStatementUpdate != null) { masterfinancialStatementUpdate.addSubFinancialStatements(financialStatement); @@ -112,58 +99,53 @@ } commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - + } - + @Override - public void createFinancialStatement(FinancialStatement masterFinancialStatement, FinancialStatement financialStatement) throws LimaException { - - TopiaContext transaction = null; - try { - transaction = beginTransaction(); + public void createFinancialStatement(FinancialStatement masterFinancialStatement, + FinancialStatement financialStatement) throws LimaException { + TopiaContext transaction = beginTransaction(rootContext); + try { createFinancialStatementWithTransaction(masterFinancialStatement, financialStatement, transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (Exception ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - + @Override public void removeFinancialStatement(FinancialStatement financialStatement) throws LimaException { - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); FinancialStatementDAO financialStatementDAO = - LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); - - + LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); + + // remove financialstatement FinancialStatement financialStatementToDelete = - financialStatementDAO.findByTopiaId( - financialStatement.getTopiaId()); + financialStatementDAO.findByTopiaId( + financialStatement.getTopiaId()); financialStatementDAO.delete(financialStatementToDelete); - + //get all subFinancialStatement List<FinancialStatement> financialStatements = - getAllChildrenFinancialStatement(financialStatement, - new ArrayList<FinancialStatement>()); - + getAllChildrenFinancialStatement(financialStatement, + new ArrayList<FinancialStatement>()); + //if FinancialStatement have subFinancialStatement - if (financialStatements.size() > 0){ + if (financialStatements.size() > 0) { for (FinancialStatement subFinancialStatement : financialStatements) { FinancialStatement subFinancialStatementToDelete = - financialStatementDAO.findByTopiaId( - subFinancialStatement.getTopiaId()); + financialStatementDAO.findByTopiaId( + subFinancialStatement.getTopiaId()); financialStatementDAO.delete(subFinancialStatementToDelete); } } @@ -171,17 +153,14 @@ //commit commitTransaction(transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - - + @Override public void removeAllFinancialStatement() throws LimaException { for (FinancialStatement financialStatement : getChildrenFinancialStatement(null)) { @@ -191,267 +170,271 @@ @Override public List<FinancialStatement> getAllFinancialStatements() throws LimaException { - TopiaContext transaction = null; List<FinancialStatement> financialStatements = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); FinancialStatementDAO financialStatementDAO = - LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); + LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); financialStatements = financialStatementDAO.findAll(); - } catch (TopiaException ex) { - doCatch(transaction, ex, log); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } return financialStatements; } @Override - public List<FinancialStatement> getAllChildrenFinancialStatement(FinancialStatement financialStatement, List<FinancialStatement> result) throws LimaException { + public List<FinancialStatement> getAllChildrenFinancialStatement(FinancialStatement financialStatement, + List<FinancialStatement> result) throws LimaException { List<FinancialStatement> childFinancialStatements = - getChildrenFinancialStatement(financialStatement); - for (FinancialStatement childFinancialStatement: childFinancialStatements) { + getChildrenFinancialStatement(financialStatement); + for (FinancialStatement childFinancialStatement : childFinancialStatements) { result.add(childFinancialStatement); getAllChildrenFinancialStatement(childFinancialStatement, result); } return result; } - + @Override public List<FinancialStatement> getChildrenFinancialStatement(FinancialStatement masterFinancialStatement) throws LimaException { List<FinancialStatement> financialStatements = null; - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); FinancialStatementDAO financialStatementDAO = - LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); + LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); - TopiaQuery query = financialStatementDAO.createQuery(); - query.addEquals("masterFinancialStatement", masterFinancialStatement) - .addOrder(FinancialStatement.TOPIA_CREATE_DATE); - financialStatements = financialStatementDAO.findAllByQuery(query); + TopiaQuery query = financialStatementDAO.createQuery(); + query.addEquals(FinancialStatement.MASTER_FINANCIAL_STATEMENT, masterFinancialStatement) + .addOrder(FinancialStatement.TOPIA_CREATE_DATE); + financialStatements = financialStatementDAO.findAllByQuery(query); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } return financialStatements; } - - + + @Override public void updateFinancialStatement(FinancialStatement financialStatement) throws LimaException { - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - + // DAO FinancialStatementDAO financialStatementHeaderDAO = - LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); + LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); //update financialStatementHeaderDAO.update(financialStatement); //commit commitTransaction(transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - - /** - * remote methode to get list of financial statement - */ + /** remote methode to get list of financial statement */ @Override - public List<FinancialStatementAmounts> financialStatementReport(Date selectedBeginDate, Date selectedEndDate) throws LimaException{ - TopiaContext transaction = null; + public List<FinancialStatementAmounts> financialStatementReport(Date selectedBeginDate, + Date selectedEndDate) throws LimaException { List<FinancialStatementAmounts> result = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); //create list form tree result = financialStatementReport(null, selectedBeginDate, - selectedEndDate, new FinancialStatementDatasImpl(), - transaction).getListResult(); - + selectedEndDate, new FinancialStatementDatasImpl(), + transaction).getListResult(); + + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - return result; + return result; } - /** - * Créé la liste de postes contenant les calculs de comptes - */ - public FinancialStatementDatas financialStatementReport(FinancialStatement financialStatement, Date selectedBeginDate, Date selectedEndDate,FinancialStatementDatas result, TopiaContext topiaContext) throws LimaException{ - + /** Créé la liste de postes contenant les calculs de comptes + * @param financialStatement + * @param selectedBeginDate + * @param selectedEndDate + * @param result + * @param topiaContext + * @return + * @throws LimaException*/ + public FinancialStatementDatas financialStatementReport(FinancialStatement financialStatement, + Date selectedBeginDate, + Date selectedEndDate, + FinancialStatementDatas result, + TopiaContext topiaContext) throws LimaException { + List<FinancialStatement> financialStatements = - getChildrenFinancialStatement(financialStatement); + getChildrenFinancialStatement(financialStatement); try { BigDecimal grossAmount = new BigDecimal(0), - provisionDeprecationAmount = new BigDecimal(0); + provisionDeprecationAmount = new BigDecimal(0); List<FinancialStatementAmounts> subResult = - new ArrayList<FinancialStatementAmounts>(); + new ArrayList<FinancialStatementAmounts>(); for (FinancialStatement subFinancialStatement : financialStatements) { FinancialStatementAmounts financialStatementAmounts = - financialStatementAmounts(subFinancialStatement, - selectedBeginDate, selectedEndDate, topiaContext); - if (!subFinancialStatement.getHeader()){ + financialStatementAmounts(subFinancialStatement, + selectedBeginDate, selectedEndDate, topiaContext); + if (!subFinancialStatement.getHeader()) { //on calcul grossAmount = - grossAmount.add(financialStatementAmounts.getGrossAmount()); + grossAmount.add(financialStatementAmounts.getGrossAmount()); provisionDeprecationAmount = provisionDeprecationAmount.add( - financialStatementAmounts.getProvisionDeprecationAmount()); + financialStatementAmounts.getProvisionDeprecationAmount()); subResult.add(financialStatementAmounts); - } - else { + } else { FinancialStatementDatas financialStatementDatas = - financialStatementReport(subFinancialStatement, - selectedBeginDate, selectedEndDate, result, topiaContext); + financialStatementReport(subFinancialStatement, + selectedBeginDate, selectedEndDate, result, topiaContext); grossAmount = grossAmount.add(financialStatementDatas. - getFinancialStatementAmounts().getGrossAmount()); + getFinancialStatementAmounts().getGrossAmount()); provisionDeprecationAmount = provisionDeprecationAmount. - add(financialStatementDatas.getFinancialStatementAmounts(). - getProvisionDeprecationAmount()); + add(financialStatementDatas.getFinancialStatementAmounts(). + getProvisionDeprecationAmount()); FinancialStatementAmounts headerfinancialStatementAmounts = - financialStatementDatas.getFinancialStatementAmounts(); + financialStatementDatas.getFinancialStatementAmounts(); //Si sous-total - if (subFinancialStatement.getSubAmount()){ + if (subFinancialStatement.getSubAmount()) { FinancialStatementAmounts header = - new FinancialStatementAmountsImpl(); + new FinancialStatementAmountsImpl(); header.setLabel(headerfinancialStatementAmounts.getLabel()); header.setLevel(headerfinancialStatementAmounts.getLevel()); header.setHeader(true); //ajoute header subResult.add(header); //ajoute liste - if (financialStatementDatas.getListResult() != null){ + if (financialStatementDatas.getListResult() != null) { subResult.addAll(financialStatementDatas.getListResult()); } //ajoute sstotal FinancialStatementAmounts subAmount = - new FinancialStatementAmountsImpl(); + new FinancialStatementAmountsImpl(); subAmount.setLabel( - "TOTAL "+headerfinancialStatementAmounts.getLabel()); + "TOTAL " + headerfinancialStatementAmounts.getLabel()); subAmount.setLevel( headerfinancialStatementAmounts.getLevel()); subAmount.setGrossAmount( headerfinancialStatementAmounts.getGrossAmount()); subAmount.setProvisionDeprecationAmount( headerfinancialStatementAmounts. - getProvisionDeprecationAmount()); + getProvisionDeprecationAmount()); subAmount.setSubAmount(true); subResult.add(subAmount); //ajoute une ligne vide subResult.add(new FinancialStatementAmountsImpl()); - + }//sinon else { - if (subFinancialStatement.getHeaderAmount()){ + if (subFinancialStatement.getHeaderAmount()) { subResult.add(headerfinancialStatementAmounts); - } - else { + } else { headerfinancialStatementAmounts. - setGrossAmount(new BigDecimal(0)); + setGrossAmount(new BigDecimal(0)); headerfinancialStatementAmounts. - setProvisionDeprecationAmount(new BigDecimal(0)); + setProvisionDeprecationAmount(new BigDecimal(0)); subResult.add(headerfinancialStatementAmounts); } //ajoute liste - if (financialStatementDatas.getListResult() != null){ + if (financialStatementDatas.getListResult() != null) { subResult.addAll(financialStatementDatas.getListResult()); } } } } FinancialStatementAmounts financialStatementAmounts = - new FinancialStatementAmountsImpl(); + new FinancialStatementAmountsImpl(); financialStatementAmounts.setGrossAmount(grossAmount); financialStatementAmounts.setProvisionDeprecationAmount( provisionDeprecationAmount); - if (financialStatement != null){ + if (financialStatement != null) { financialStatementAmounts.setLabel(financialStatement.getLabel()); financialStatementAmounts.setHeader(financialStatement.getHeader()); financialStatementAmounts.setLevel(financialStatement.getLevel()); } result.setFinancialStatementAmounts(financialStatementAmounts); result.setListResult(subResult); + } catch (LimaException eee) { + doCatch(topiaContext, eee); } - catch (LimaException eee) { - doCatch(topiaContext, eee, log); - } return result; } - - - /** - * Permet de calculer le montant de tous les comptes contenu dans un mouvement - */ - public FinancialStatementAmounts financialStatementAmounts(FinancialStatement financialStatement, Date selectedBeginDate, Date selectedEndDate, TopiaContext topiaContext) throws LimaException{ + + + /** Permet de calculer le montant de tous les comptes contenu dans un mouvement + * @param financialStatement + * @param selectedBeginDate + * @param selectedEndDate + * @param topiaContext + * @return + * @throws LimaException*/ + public FinancialStatementAmounts financialStatementAmounts(FinancialStatement financialStatement, + Date selectedBeginDate, + Date selectedEndDate, + TopiaContext topiaContext) throws LimaException { FinancialStatementAmounts financialStatementAmounts = - new FinancialStatementAmountsImpl(); + new FinancialStatementAmountsImpl(); BigDecimal amount = new BigDecimal(0); BigDecimal debitAmount = new BigDecimal(0); BigDecimal creditAmount = new BigDecimal(0); BigDecimal provisionDeprecationAmount = new BigDecimal(0); - - FinancialStatement masterFinancialStatement = + + FinancialStatement masterFinancialStatement = financialStatement.getMasterFinancialStatement(); - FinancialStatementWayEnum financialStatementWayEnum = + FinancialStatementWayEnum financialStatementWayEnum = FinancialStatementWayEnum.BOTH; - if (masterFinancialStatement != null){ - financialStatementWayEnum = masterFinancialStatement.getWay(); - } + if (masterFinancialStatement != null) { + financialStatementWayEnum = masterFinancialStatement.getWay(); + } - // DEBIT & CREDIT ACCOUNTS LIST - Amounts amounts = new AmountsImpl(); - String accountsString = financialStatement.getAccounts(); - if (accountsString != null && !accountsString.equals("")){ - amounts = amountFromAccountList(accountsString, - selectedBeginDate, selectedEndDate, topiaContext); - debitAmount = debitAmount.add(amounts.getDebit()); - creditAmount = creditAmount.add(amounts.getCredit()); - } - // DEBIT ACCOUNTS LIST - String debitAccountsString = financialStatement.getDebitAccounts(); - if (debitAccountsString != null && !debitAccountsString.equals("")){ - amounts = amountFromAccountList(debitAccountsString, - selectedBeginDate, selectedEndDate, topiaContext); - debitAmount = debitAmount.add(amounts.getDebit()); - } - //CREDIT ACCOUNTS LIST - String creditAccountsString = financialStatement.getCreditAccounts(); - if (creditAccountsString != null && !creditAccountsString.equals("")){ - amounts = amountFromAccountList(creditAccountsString, - selectedBeginDate, selectedEndDate, topiaContext); - creditAmount = creditAmount.add(amounts.getCredit()); - } - // PROVISION & DEPRECATION - String provisionDeprecationAccountsString = + // DEBIT & CREDIT ACCOUNTS LIST + Amounts amounts = new AmountsImpl(); + String accountsString = financialStatement.getAccounts(); + if (accountsString != null && !accountsString.equals("")) { + amounts = amountFromAccountList(accountsString, + selectedBeginDate, selectedEndDate, topiaContext); + debitAmount = debitAmount.add(amounts.getDebit()); + creditAmount = creditAmount.add(amounts.getCredit()); + } + // DEBIT ACCOUNTS LIST + String debitAccountsString = financialStatement.getDebitAccounts(); + if (debitAccountsString != null && !debitAccountsString.equals("")) { + amounts = amountFromAccountList(debitAccountsString, + selectedBeginDate, selectedEndDate, topiaContext); + debitAmount = debitAmount.add(amounts.getDebit()); + } + //CREDIT ACCOUNTS LIST + String creditAccountsString = financialStatement.getCreditAccounts(); + if (creditAccountsString != null && !creditAccountsString.equals("")) { + amounts = amountFromAccountList(creditAccountsString, + selectedBeginDate, selectedEndDate, topiaContext); + creditAmount = creditAmount.add(amounts.getCredit()); + } + // PROVISION & DEPRECATION + String provisionDeprecationAccountsString = financialStatement.getProvisionDeprecationAccounts(); - if (provisionDeprecationAccountsString != null && !provisionDeprecationAccountsString.equals("")){ - amounts = amountFromAccountList( - provisionDeprecationAccountsString, selectedBeginDate, - selectedEndDate, topiaContext); - provisionDeprecationAmount = + if (provisionDeprecationAccountsString != null && !provisionDeprecationAccountsString.equals("")) { + amounts = amountFromAccountList( + provisionDeprecationAccountsString, selectedBeginDate, + selectedEndDate, topiaContext); + provisionDeprecationAmount = provisionDeprecationAmount.add(amounts.getCredit()); - provisionDeprecationAmount = + provisionDeprecationAmount = provisionDeprecationAmount.subtract(amounts.getDebit()); - } - switch (financialStatementWayEnum) { + } + switch (financialStatementWayEnum) { case BOTH: amount = amount.add(debitAmount); amount = amount.subtract(creditAmount); @@ -464,20 +447,23 @@ case DEBIT: amount = amount.add(debitAmount); amount = amount.subtract(creditAmount); - } - - financialStatementAmounts.setGrossAmount(amount); - financialStatementAmounts.setLabel(financialStatement.getLabel()); - financialStatementAmounts.setProvisionDeprecationAmount( - provisionDeprecationAmount); - financialStatementAmounts.setLevel( - financialStatement.getLevel()); - + } + + financialStatementAmounts.setGrossAmount(amount); + financialStatementAmounts.setLabel(financialStatement.getLabel()); + financialStatementAmounts.setProvisionDeprecationAmount( + provisionDeprecationAmount); + financialStatementAmounts.setLevel( + financialStatement.getLevel()); + return financialStatementAmounts; } - - - public Amounts amountFromAccountList(String accountsNumberList, Date selectedBeginDate, Date selectedEndDate, TopiaContext topiaContext) throws LimaException{ + + + public Amounts amountFromAccountList(String accountsNumberList, + Date selectedBeginDate, + Date selectedEndDate, + TopiaContext topiaContext) throws LimaException { Amounts amounts = new AmountsImpl(); BigDecimal debit = new BigDecimal(0); BigDecimal credit = new BigDecimal(0); @@ -494,16 +480,15 @@ BigDecimal creditTemp = new BigDecimal(0); for (Account account : accountsList) { ReportsDatas reportsDatas = reportServiceLocal. - generateAccountReportsWithTransaction(account, true, - selectedBeginDate, selectedEndDate, topiaContext); - if (reportsDatas.getSoldeDebit()){ + generateAccountReportsWithTransaction(account, true, + selectedBeginDate, selectedEndDate, topiaContext); + if (reportsDatas.getSoldeDebit()) { debitTemp = debitTemp.add(reportsDatas.getAmountSolde()); - } - else { + } else { creditTemp = creditTemp.add(reportsDatas.getAmountSolde()); } } - if (!substract){ + if (!substract) { debit = debitTemp; credit = creditTemp; } @@ -517,107 +502,86 @@ amounts.setCredit(credit); amounts.setDebit(debit); } catch (TopiaException e) { - doCatch(topiaContext, e, log); + doCatch(topiaContext, e); } return amounts; } - + @Override public String checkFinancialStatementChart() throws LimaException { - StringBuffer result = - new StringBuffer(_("lima-business.financialstatement.check.warn")); + StringBuilder result = + new StringBuilder(_("lima-business.financialstatement.check.warn")); TopiaContext transaction = null; try { - transaction = beginTransaction(); + transaction = beginTransaction(rootContext); AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(transaction); + LimaCallaoDAOHelper.getAccountDAO(transaction); FinancialStatementDAO financialStatementDAO = - LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); - + LimaCallaoDAOHelper.getFinancialStatementDAO(transaction); + List<Account> accountsList = accountDAO.findAllSubAccounts(); List<FinancialStatement> financialStatementsList = - financialStatementDAO.findAll(); - + financialStatementDAO.findAll(); + for (FinancialStatement financialStatement : financialStatementsList) { - + accountsList.removeAll( accountDAO.stringToListAccounts( - financialStatement.getAccounts(), true)); - + financialStatement.getAccounts(), true)); + accountsList.removeAll( accountDAO.stringToListAccounts( - financialStatement.getCreditAccounts(), true)); - + financialStatement.getCreditAccounts(), true)); + accountsList.removeAll( accountDAO.stringToListAccounts( - financialStatement.getDebitAccounts(), true)); - + financialStatement.getDebitAccounts(), true)); + accountsList.removeAll( accountDAO.stringToListAccounts( - financialStatement.getProvisionDeprecationAccounts(), true)); + financialStatement.getProvisionDeprecationAccounts(), true)); } - + for (Account account : accountsList) { - + result.append(_("lima-business.financialstatement.check.nothing", - account.getAccountNumber(), account.getLabel())); + account.getAccountNumber(), account.getLabel())); } - + + } catch (TopiaException ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } return result.toString(); } - - public List<FinancialStatement> findFinancialStatementByAccountNumber(String accountNumber, TopiaContext topiaContext) throws TopiaException{ - + + public List<FinancialStatement> findFinancialStatementByAccountNumber(String accountNumber, + TopiaContext topiaContext) throws TopiaException { + FinancialStatementDAO financialStatementDAO = - LimaCallaoDAOHelper.getFinancialStatementDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialStatementDAO(topiaContext); TopiaQuery query = financialStatementDAO.createQuery(); - + String accountProperty = - TopiaQuery.getProperty(FinancialStatement.ACCOUNTS); + TopiaQuery.getProperty(FinancialStatement.ACCOUNTS); String creditAccountProperty = - TopiaQuery.getProperty(FinancialStatement.CREDIT_ACCOUNTS); + TopiaQuery.getProperty(FinancialStatement.CREDIT_ACCOUNTS); String debitAccountProperty = - TopiaQuery.getProperty(FinancialStatement.DEBIT_ACCOUNTS); + TopiaQuery.getProperty(FinancialStatement.DEBIT_ACCOUNTS); String provisionDeprecationProperty = - TopiaQuery.getProperty(FinancialStatement.PROVISION_DEPRECATION_ACCOUNTS); - String likeCondition = " " + Op.LIKE + " '%"+accountNumber + "%'"; - + TopiaQuery.getProperty(FinancialStatement.PROVISION_DEPRECATION_ACCOUNTS); + String likeCondition = " " + Op.LIKE + " '%" + accountNumber + "%'"; + query.addWhere(accountProperty + likeCondition - + " OR " + creditAccountProperty + likeCondition - + " OR " + debitAccountProperty + likeCondition - + " OR " + provisionDeprecationProperty + likeCondition); + + " OR " + creditAccountProperty + likeCondition + + " OR " + debitAccountProperty + likeCondition + + " OR " + provisionDeprecationProperty + likeCondition); return financialStatementDAO.findAllByQuery(query); } - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } - - protected void commitTransaction(TopiaContext topiaTransaction) throws TopiaException { - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } - } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialTransactionServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialTransactionServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialTransactionServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -26,28 +26,17 @@ package org.chorem.lima.business.ejb; -import java.math.BigDecimal; -import java.util.ArrayList; - -import java.util.Date; -import java.util.List; - -import javax.ejb.EJB; -import javax.ejb.Stateless; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.FinancialStatementWayEnum; import org.chorem.lima.beans.FinancialTransactionSearch; import org.chorem.lima.business.AccountingRules; import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; -import org.chorem.lima.business.ejbinterface.EntryBookService; -import org.chorem.lima.business.ejbinterface.FinancialPeriodService; +import org.chorem.lima.business.ejbinterface.EntryBookServiceLocal; +import org.chorem.lima.business.ejbinterface.FinancialPeriodServiceLocal; import org.chorem.lima.business.ejbinterface.FinancialTransactionService; import org.chorem.lima.business.ejbinterface.FinancialTransactionServiceLocal; -import org.chorem.lima.business.ejbinterface.ReportService; -import org.chorem.lima.business.ejbinterface.OptionsService; +import org.chorem.lima.business.ejbinterface.OptionsServiceLocal; +import org.chorem.lima.business.ejbinterface.ReportServiceLocal; import org.chorem.lima.entity.Account; import org.chorem.lima.entity.AccountDAO; import org.chorem.lima.entity.Entry; @@ -55,20 +44,25 @@ import org.chorem.lima.entity.EntryDAO; import org.chorem.lima.entity.FinancialPeriod; import org.chorem.lima.entity.FinancialPeriodDAO; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionDAO; import org.chorem.lima.entity.FiscalPeriod; import org.chorem.lima.entity.Letter; import org.chorem.lima.entity.LetterDAO; import org.chorem.lima.entity.LetterImpl; import org.chorem.lima.entity.LimaCallaoDAOHelper; -import org.chorem.lima.entity.FinancialTransaction; -import org.chorem.lima.entity.FinancialTransactionDAO; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; import org.nuiton.topia.framework.TopiaQuery.Op; +import javax.ejb.EJB; +import javax.ejb.Stateless; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + /** * Cette classe permet la création d'une transaction comptable dans l'application. * Toute action sur une transaction entraîne automatiquement une création de log. @@ -81,35 +75,25 @@ @Stateless public class FinancialTransactionServiceImpl extends AbstractLimaService implements FinancialTransactionService, FinancialTransactionServiceLocal { - private static final Log log = - LogFactory.getLog(FinancialTransactionServiceImpl.class); - private TopiaContext rootContext; - + protected AccountingRules accountingRules; - + @EJB - protected FinancialPeriodService financialPeriodService; - + protected FinancialPeriodServiceLocal financialPeriodService; + @EJB - protected ReportService reportService; - + protected ReportServiceLocal reportService; + @EJB - protected EntryBookService entryBookService; - + protected EntryBookServiceLocal entryBookService; + @EJB - protected OptionsService optionsService; + protected OptionsServiceLocal optionsService; public FinancialTransactionServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - accountingRules = config.getAccountingRules(); + rootContext = acquireRootContext(); + accountingRules = LimaConfig.getInstance().getAccountingRules(); } @Override @@ -117,315 +101,285 @@ FinancialTransaction financialtransaction, TopiaContext topiaContext) throws LimaException { FinancialTransaction fTransaction = null; - try { + try { //check if the financial period is blocked accountingRules.checkFinancialPeriodBlockedWithFinancialTransaction( financialtransaction, topiaContext); FinancialTransactionDAO financialtransactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); - fTransaction = (FinancialTransaction) - financialtransactionDAO.create(financialtransaction); + fTransaction = financialtransactionDAO.create(financialtransaction); commitTransaction(topiaContext); - + + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } return fTransaction; } - - /** - * Permet de créer une transaction comptable contenant des entrées - * - */ + + /** Permet de créer une transaction comptable contenant des entrées */ @Override public FinancialTransaction createFinancialTransaction(FinancialTransaction financialtransaction) throws LimaException { - - TopiaContext topiaContext = null; + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - return createFinancialTransactionWithTransaction(financialtransaction, topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } return null; } - - /** - * Return the list of all financial transaction of a financial period - */ + + /** Return the list of all financial transaction of a financial period */ @Override public List<FinancialTransaction> getAllFinancialTransactionsForFinancialPeriod( FinancialPeriod period) throws LimaException { return getAllFinancialTransactionsForEntryBookAndFinancialPeriod(null, period); } - - /** - * Return the list of all financial transaction from two dates - */ + + /** Return the list of all financial transaction from two dates */ @Override public List<FinancialTransaction> getAllFinancialTransactionsFromDateToDate( Date beginDate, Date endDate) throws LimaException { List<FinancialTransaction> financialTransactions = null; - TopiaContext topiaTransaction = null; + TopiaContext topiaTransaction = beginTransaction(rootContext); try { - topiaTransaction = beginTransaction(); FinancialTransactionDAO transactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaTransaction); - - String financialPeriodProperty = TopiaQuery.getProperty(FinancialTransaction.FINANCIAL_PERIOD); + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaTransaction); + + String financialPeriodProperty = TopiaQuery.getProperty(FinancialTransaction.FINANCIAL_PERIOD); String entryBookLabelProperty = TopiaQuery.getProperty(FinancialTransaction.ENTRY_BOOK); - + // filter with topia query TopiaQuery query = transactionDAO.createQuery("T") - - .addBetween(FinancialTransaction.TRANSACTION_DATE, beginDate, endDate) - - .addDistinct() - .addOrder("T." + FinancialTransaction.TRANSACTION_DATE) - .addOrder("T." + FinancialTransaction.TOPIA_CREATE_DATE) - //load for lazy - .addLoad(financialPeriodProperty) - .addLoad(entryBookLabelProperty) - .addLeftJoin("T."+FinancialTransaction.ENTRY, "E", true) - .addFetch("E."+Entry.ACCOUNT) - .addFetch("E."+Entry.LETTER); + + .addBetween(FinancialTransaction.TRANSACTION_DATE, beginDate, endDate) + + .addDistinct() + .addOrder("T." + FinancialTransaction.TRANSACTION_DATE) + .addOrder("T." + FinancialTransaction.TOPIA_CREATE_DATE) + //load for lazy + .addLoad(financialPeriodProperty) + .addLoad(entryBookLabelProperty) + .addLeftJoin("T." + FinancialTransaction.ENTRY, "E", true) + .addFetch("E." + Entry.ACCOUNT) + .addFetch("E." + Entry.LETTER); financialTransactions = transactionDAO.findAllByQuery(query); + } catch (Exception ex) { + doCatch(topiaTransaction, ex); + } finally { + doFinally(topiaTransaction); } - catch (TopiaException ex) { - doCatch(topiaTransaction, ex, log); - } - finally { - doFinally(topiaTransaction, log); - } return financialTransactions; } - - /** - * Return the list of all financial transaction of a financial period and an entrybook - */ + + /** Return the list of all financial transaction of a financial period and an entrybook */ @Override public List<FinancialTransaction> getAllFinancialTransactionsForEntryBookAndFinancialPeriod(EntryBook entryBook, FinancialPeriod financialPeriod) throws LimaException { - + List<FinancialTransaction> financialTransactions = null; - TopiaContext topiaTransaction = null; + TopiaContext topiaTransaction = beginTransaction(rootContext); try { - topiaTransaction = beginTransaction(); FinancialTransactionDAO transactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaTransaction); - - String financialPeriodProperty = TopiaQuery.getProperty(FinancialTransaction.FINANCIAL_PERIOD); + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaTransaction); + + String financialPeriodProperty = TopiaQuery.getProperty(FinancialTransaction.FINANCIAL_PERIOD); String entryBookLabelProperty = TopiaQuery.getProperty(FinancialTransaction.ENTRY_BOOK); - + // filter with topia query TopiaQuery query = transactionDAO.createQuery("T"); - + if (entryBook != null) { - query.addEquals("entryBook", entryBook); + query.addEquals(FinancialTransaction.ENTRY_BOOK, entryBook); } - + if (financialPeriod != null) { - query.addEquals("financialPeriod", financialPeriod); + query.addEquals(FinancialTransaction.FINANCIAL_PERIOD, financialPeriod); } query.addDistinct() - .addOrder("T." + FinancialTransaction.TRANSACTION_DATE) - .addOrder("T." + FinancialTransaction.TOPIA_CREATE_DATE) - //load for lazy - .addLoad(financialPeriodProperty) - .addLoad(entryBookLabelProperty) - .addLeftJoin("T."+FinancialTransaction.ENTRY, "E", true) - .addFetch("E."+Entry.ACCOUNT) - .addFetch("E."+Entry.LETTER); + .addOrder("T." + FinancialTransaction.TRANSACTION_DATE) + .addOrder("T." + FinancialTransaction.TOPIA_CREATE_DATE) + //load for lazy + .addLoad(financialPeriodProperty) + .addLoad(entryBookLabelProperty) + .addLeftJoin("T." + FinancialTransaction.ENTRY, "E", true) + .addFetch("E." + Entry.ACCOUNT) + .addFetch("E." + Entry.LETTER); financialTransactions = transactionDAO.findAllByQuery(query); + } catch (Exception ex) { + doCatch(topiaTransaction, ex); + } finally { + doFinally(topiaTransaction); } - catch (TopiaException ex) { - doCatch(topiaTransaction, ex, log); - } - finally { - doFinally(topiaTransaction, log); - } return financialTransactions; } - - - /** - * Get unbalanced financialtransaction from selected fiscalperiod - */ + + + /** Get unbalanced financialtransaction from selected fiscalperiod */ @Override public List<FinancialTransaction> getAllInexactFinancialTransactions(FiscalPeriod fiscalPeriod) throws LimaException { - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); List<FinancialTransaction> result = null; List<FinancialTransaction> checkedResult = new ArrayList<FinancialTransaction>(); try { - topiaContext = beginTransaction(); - + FinancialTransactionDAO financialTransactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); - - String financialPeriodProperty = TopiaQuery.getProperty(FinancialTransaction.FINANCIAL_PERIOD); - String entryBookLabelProperty = TopiaQuery.getProperty(FinancialTransaction.ENTRY_BOOK); - - + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); + + String financialPeriodProperty = TopiaQuery.getProperty(FinancialTransaction.FINANCIAL_PERIOD); + String entryBookLabelProperty = TopiaQuery.getProperty(FinancialTransaction.ENTRY_BOOK); + + TopiaQuery query = financialTransactionDAO.createQuery("T"); query.addDistinct() - .addOrder("T." + FinancialTransaction.TRANSACTION_DATE) - .addOrder("T." + FinancialTransaction.TOPIA_CREATE_DATE) - .addFrom(FiscalPeriod.class, "F") - .addLeftJoin("T."+FinancialTransaction.ENTRY, "E", true) - .addWhere("T.amountCredit != T.amountDebit OR E.account = null OR T.entryBook = null OR E.voucher = null OR E.voucher = '' OR E.description = null OR E.description = ''") - .addInElements("T.financialPeriod", "F.financialPeriod") - .addEquals("F", fiscalPeriod) - // load lazy - .addFetch("E."+Entry.ACCOUNT) - .addFetch("E."+Entry.LETTER) - .addLoad(financialPeriodProperty) - .addLoad(entryBookLabelProperty); - + .addOrder("T." + FinancialTransaction.TRANSACTION_DATE) + .addOrder("T." + FinancialTransaction.TOPIA_CREATE_DATE) + .addFrom(FiscalPeriod.class, "F") + .addLeftJoin("T." + FinancialTransaction.ENTRY, "E", true) + .addWhere("T.amountCredit != T.amountDebit OR E.account = null OR T.entryBook = null OR E.voucher = null OR E.voucher = '' OR E.description = null OR E.description = ''") + .addInElements("T.financialPeriod", "F.financialPeriod") + .addEquals("F", fiscalPeriod) + // load lazy + .addFetch("E." + Entry.ACCOUNT) + .addFetch("E." + Entry.LETTER) + .addLoad(financialPeriodProperty) + .addLoad(entryBookLabelProperty); + result = financialTransactionDAO.findAllByQuery(query); for (FinancialTransaction fTransaction : result) { BigDecimal credit = fTransaction.getAmountCredit(); BigDecimal debit = fTransaction.getAmountDebit(); credit = credit.setScale(optionsService.getScale(), - BigDecimal.ROUND_HALF_UP); + BigDecimal.ROUND_HALF_UP); debit = debit.setScale(optionsService.getScale(), - BigDecimal.ROUND_HALF_UP); + BigDecimal.ROUND_HALF_UP); if (credit.equals(debit)) { checkedResult.add(fTransaction); } } + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } return result; } - + @Override public List<FinancialTransaction> getAllFinancialTransactionsBalanced(FiscalPeriod fiscalPeriod) throws LimaException { - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); List<FinancialTransaction> result = null; try { - topiaContext = beginTransaction(); result = getAllFinancialTransactionsBalanced(fiscalPeriod, topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } return result; } - + /** * Get balanced financialtransaction from selected fiscalperiod + * + * @param fiscalPeriod + * @param topiaContext + * @return + * @throws LimaException */ - public List<FinancialTransaction> getAllFinancialTransactionsBalanced(FiscalPeriod fiscalPeriod, TopiaContext topiaContext) throws LimaException { + public List<FinancialTransaction> getAllFinancialTransactionsBalanced(FiscalPeriod fiscalPeriod, + TopiaContext topiaContext) throws LimaException { List<FinancialTransaction> result = null; - try { + try { FinancialTransactionDAO financialTransactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); - + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); + // WARN No load lazy, modify query with addLoad or addFetch if loading is necessary TopiaQuery query = financialTransactionDAO.createQuery("T"); query.addFrom(FiscalPeriod.class, "F") - .addLeftJoin("T."+FinancialTransaction.ENTRY, "E", false) - .addWhere("T.amountCredit = T.amountDebit") - .addNotNull("E.account") - .addNotNull("T.entryBook") - .addInElements("T.financialPeriod", "F.financialPeriod") - .addEquals("F", fiscalPeriod); - - result = financialTransactionDAO.findAllByQuery(query); - + .addLeftJoin("T." + FinancialTransaction.ENTRY, "E", false) + .addWhere("T.amountCredit = T.amountDebit") + .addNotNull("E.account") + .addNotNull("T.entryBook") + .addInElements("T.financialPeriod", "F.financialPeriod") + .addEquals("F", fiscalPeriod); + + result = financialTransactionDAO.findAllByQuery(query); + + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } return result; } - - + + /** * update date and amount of a financial transaction * call accounting rules - * */ @Override public void updateFinancialTransaction(FinancialTransaction financialtransaction) throws LimaException { - - TopiaContext topiaContext = null; - try { - topiaContext = beginTransaction(); - updateFinancialTransactionWithTransaction( - financialtransaction, topiaContext); - commitTransaction(topiaContext); + + TopiaContext topiaContext = beginTransaction(rootContext); + try { + updateFinancialTransactionWithTransaction( + financialtransaction, topiaContext); + commitTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } - - /** - * Method used by update entry and remove entry for update amounts - */ + + /** Method used by update entry and remove entry for update amounts */ @Override - public void updateFinancialTransactionWithTransaction(FinancialTransaction financialtransaction, TopiaContext topiaContext) throws LimaException{ + public void updateFinancialTransactionWithTransaction(FinancialTransaction financialtransaction, + TopiaContext topiaContext) throws LimaException { try { FinancialTransactionDAO transactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); FinancialTransaction financialTransactionOld = - transactionDAO.findByTopiaId(financialtransaction.getTopiaId()); - + transactionDAO.findByTopiaId(financialtransaction.getTopiaId()); + /* if update date change - check : - * - if old financialtransaction date are on periodblocked - * - if new date are on fiscalperiod - * - new financialtransaction date are on periodunblocked - * - if all closedperiod are open - */ + * - if old financialtransaction date are on periodblocked + * - if new date are on fiscalperiod + * - new financialtransaction date are on periodunblocked + * - if all closedperiod are open + */ Date oldDate = financialTransactionOld.getTransactionDate(); Date newDate = financialtransaction.getTransactionDate(); - if (newDate.compareTo(oldDate) != 0){ + if (newDate.compareTo(oldDate) != 0) { financialTransactionOld.setTransactionDate(newDate); //change financial period FinancialPeriodDAO financialPeriodDAO = - LimaCallaoDAOHelper.getFinancialPeriodDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialPeriodDAO(topiaContext); FinancialPeriod financialPeriod = financialPeriodDAO.findByDate(newDate); - if (financialPeriod != null){ + if (financialPeriod != null) { financialTransactionOld.setFinancialPeriod(financialPeriod); } } accountingRules.updateFinancialTransactionDateRules( financialtransaction, financialTransactionOld, topiaContext); - - financialTransactionOld.setAmountDebit( - financialtransaction.getAmountDebit()); - financialTransactionOld.setAmountCredit( - financialtransaction.getAmountCredit()); - financialTransactionOld.setEntryBook( - financialtransaction.getEntryBook()); - transactionDAO.update(financialTransactionOld); - } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } + + financialTransactionOld.setAmountDebit( + financialtransaction.getAmountDebit()); + financialTransactionOld.setAmountCredit( + financialtransaction.getAmountCredit()); + financialTransactionOld.setEntryBook( + financialtransaction.getEntryBook()); + transactionDAO.update(financialTransactionOld); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); + } } /** @@ -434,36 +388,33 @@ */ @Override public void removeFinancialTransaction(FinancialTransaction financialtransaction) throws LimaException { - - TopiaContext topiaTransaction = null; + + TopiaContext topiaTransaction = beginTransaction(rootContext); try { - topiaTransaction = beginTransaction(); - + //check if the financial period is blocked accountingRules.checkFinancialPeriodBlockedWithFinancialTransaction( financialtransaction, topiaTransaction); - + FinancialTransactionDAO transactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaTransaction); + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaTransaction); FinancialTransaction financialTransaction2 = - //patch : conflict object already instanciate - transactionDAO.findByTopiaId(financialtransaction.getTopiaId()); + //patch : conflict object already instanciate + transactionDAO.findByTopiaId(financialtransaction.getTopiaId()); transactionDAO.delete(financialTransaction2); commitTransaction(topiaTransaction); + } catch (Exception ex) { + doCatch(topiaTransaction, ex); + } finally { + doFinally(topiaTransaction); } - catch (TopiaException ex) { - doCatch(topiaTransaction, ex, log); - } - finally { - doFinally(topiaTransaction, log); - } - } - + @Override public Entry createEntryWithTransaction(Entry entry, - TopiaContext topiaContext) throws LimaException, TopiaException { + TopiaContext topiaContext) throws LimaException { Entry newEntry = null; + try { //check if the financial period is blocked accountingRules.checkFinancialPeriodBlockedWithFinancialTransaction( entry.getFinancialTransaction(), topiaContext); @@ -471,114 +422,106 @@ EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); newEntry = entryDAO.create(entry); - + //get new entry amounts BigDecimal entryAmount = entry.getAmount(); Boolean entryAmountIsDebit = entry.getDebit(); BigDecimal entryDebit = new BigDecimal(0), entryCredit = new BigDecimal(0); - if (entryAmountIsDebit){ + if (entryAmountIsDebit) { entryDebit = entryAmount; - } - else { + } else { entryCredit = entryAmount; } - + //calculate financial transaction amounts FinancialTransaction financialTransaction = - entry.getFinancialTransaction(); - + entry.getFinancialTransaction(); + BigDecimal amountDebit = financialTransaction.getAmountDebit(); - if (amountDebit == null){ + if (amountDebit == null) { amountDebit = new BigDecimal(0); } amountDebit = amountDebit.add(entryDebit); financialTransaction.setAmountDebit(amountDebit); - + BigDecimal amountCredit = financialTransaction.getAmountCredit(); - if (amountCredit == null){ + if (amountCredit == null) { amountCredit = new BigDecimal(0); } amountCredit = amountCredit.add(entryCredit); financialTransaction.setAmountCredit(amountCredit); - + //update financial transaction updateFinancialTransactionWithTransaction( financialTransaction, topiaContext); - - //commitTransaction(topiaContext); + + } catch (TopiaException e) { + doCatch(topiaContext, e); + } return newEntry; } - + /** * Create new entry * the period must not be blocked, call accounting rules * * @return */ - @Override public Entry createEntry(Entry entry) throws LimaException { - - TopiaContext topiaContext = null; + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - + Entry newEntry = createEntryWithTransaction(entry, topiaContext); - + commitTransaction(topiaContext); - + return newEntry; + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } return null; } - - - /** - * update entry, calculate amount of the financial transaction - */ + + + /** update entry, calculate amount of the financial transaction */ @Override public void updateEntry(Entry entry) throws LimaException { - - TopiaContext topiaContext = null; + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); - + Entry entryOld = entryDAO.findByTopiaId(entry.getTopiaId()); - + //check rules accountingRules.updateEntryRules(entry, entryOld, topiaContext); - + //get new entry amounts BigDecimal entryAmount = entry.getAmount(); Boolean entryAmountIsDebit = entry.getDebit(); BigDecimal entryDebit = new BigDecimal(0), entryCredit = new BigDecimal(0); - if (entryAmountIsDebit){ + if (entryAmountIsDebit) { entryDebit = entryAmount; - } - else { + } else { entryCredit = entryAmount; } - + //get old entry amounts BigDecimal entryAmountOld = entryOld.getAmount(); Boolean entryAmountOldIsDebit = entryOld.getDebit(); BigDecimal entryDebitOld = new BigDecimal(0), entryCreditOld = new BigDecimal(0); - if (entryAmountOldIsDebit){ + if (entryAmountOldIsDebit) { entryDebitOld = entryAmountOld; - } - else { + } else { entryCreditOld = entryAmountOld; } - + //FIXME PEPIN 20100520 conflict object already instanciate // Exist best solution ? entryOld.setAccount(entry.getAccount()); @@ -589,66 +532,59 @@ entryOld.setFinancialTransaction(entry.getFinancialTransaction()); entryOld.setPosition(entry.getPosition()); entryOld.setLetter(entry.getLetter()); - + //calculate financial transaction amounts FinancialTransaction financialTransaction = - entryOld.getFinancialTransaction(); - - BigDecimal amountDebit = financialTransaction.getAmountDebit(); + entryOld.getFinancialTransaction(); + + BigDecimal amountDebit = financialTransaction.getAmountDebit(); amountDebit = amountDebit.subtract(entryDebitOld); amountDebit = amountDebit.add(entryDebit); financialTransaction.setAmountDebit(amountDebit); - + BigDecimal amountCredit = financialTransaction.getAmountCredit(); amountCredit = amountCredit.subtract(entryCreditOld); amountCredit = amountCredit.add(entryCredit); financialTransaction.setAmountCredit(amountCredit); - + //update financial transaction updateFinancialTransactionWithTransaction( financialTransaction, topiaContext); - + //update entry entryDAO.update(entryOld); commitTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } - - - /** - * Remove entry, update amounts for the financial transaction - */ + + /** Remove entry, update amounts for the financial transaction */ @Override public void removeEntry(Entry entry) throws LimaException { - - TopiaContext topiaContext = null; + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - + //check if the financial period is blocked accountingRules.checkFinancialPeriodBlockedWithFinancialTransaction( entry.getFinancialTransaction(), topiaContext); - + //get entry amounts BigDecimal entryAmount = entry.getAmount(); Boolean entryAmountIsDebit = entry.getDebit(); BigDecimal entryDebit = new BigDecimal(0), entryCredit = new BigDecimal(0); - if (entryAmountIsDebit){ + if (entryAmountIsDebit) { entryDebit = entryAmount; - } - else { + } else { entryCredit = entryAmount; } - + //calculate financial transaction amounts FinancialTransaction financialTransaction = - entry.getFinancialTransaction(); + entry.getFinancialTransaction(); BigDecimal amountDebit = financialTransaction.getAmountDebit(); amountDebit = amountDebit.subtract(entryDebit); financialTransaction.setAmountDebit(amountDebit); @@ -656,27 +592,23 @@ BigDecimal amountCredit = financialTransaction.getAmountCredit(); amountCredit = amountCredit.subtract(entryCredit); financialTransaction.setAmountCredit(amountCredit); - + //update financial transaction updateFinancialTransactionWithTransaction( financialTransaction, topiaContext); - + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); //delete entryDAO.delete(entry); //commit commitTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } - - - + /** * Get letter from count of existing letter * 1 -> A, 2 -> B, 26 -> Z, 27 -> AA, 28 -> AB, ... @@ -684,112 +616,100 @@ @Override public Letter getNewLetter() throws LimaException { Letter letter = new LetterImpl(); - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); LetterDAO letterDAO = LimaCallaoDAOHelper.getLetterDAO(topiaContext); long n = letterDAO.count(); String res = numberToString(n, null); - + //if already exist - while (letterDAO.findByCode(res) != null){ + while (letterDAO.findByCode(res) != null) { res = numberToString(n++, null); } letter.setCode(res); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } return letter; } - - public static String numberToString(long n, StringBuffer result){ - if (result == null){ + + public String numberToString(long n, StringBuffer result) { + if (result == null) { result = new StringBuffer(); } - long mod = (n-1) % 26; - long div = (n-1) / 26; - if (div > 0){ + long mod = (n - 1) % 26; + long div = (n - 1) / 26; + if (div > 0) { result.append(numberToString(div, result)); } - return (result.append((char) (mod+65))).toString(); + return result.append((char) (mod + 65)).toString(); } @Override public void createLetter(Letter letter) throws LimaException { - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); createLetterWithTransaction(letter, topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } - public void createLetterWithTransaction(Letter letter, TopiaContext topiaContext) throws LimaException { + public void createLetterWithTransaction(Letter letter, + TopiaContext topiaContext) throws LimaException { try { LetterDAO letterDAO = LimaCallaoDAOHelper.getLetterDAO(topiaContext); letterDAO.create(letter); commitTransaction(topiaContext); } catch (TopiaException ex) { - doCatch(topiaContext, ex, log); + doCatch(topiaContext, ex); } } - + @Override public void removeLetter(Letter letter) throws LimaException { - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); LetterDAO letterDAO = LimaCallaoDAOHelper.getLetterDAO(topiaContext); letterDAO.delete(letter); commitTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } - + @Override public List<Letter> getAllLetters() throws LimaException { List<Letter> letters = null; - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); LetterDAO letterDAO = LimaCallaoDAOHelper.getLetterDAO(topiaContext); letters = letterDAO.findAll(); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } return letters; } - - + @Override - public void setEntryLetter(Entry entry, Letter letter) throws LimaException { - - TopiaContext topiaContext = null; + public void setEntryLetter(Entry entry, + Letter letter) throws LimaException { + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); LetterDAO letterDAO = LimaCallaoDAOHelper.getLetterDAO(topiaContext); Letter letterOld = letterDAO.findByCode(letter.getCode()); - if (letterOld == null){ + if (letterOld == null) { createLetterWithTransaction(letter, topiaContext); letterOld = letter; } @@ -797,131 +717,120 @@ Entry entryOld = entryDAO.findByTopiaId(entry.getTopiaId()); entryOld.setLetter(letterOld); commitTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } - - @Override public void removeEntryLetter(Entry entry) throws LimaException { - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - - EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); + + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); Entry entryOld = entryDAO.findByTopiaId(entry.getTopiaId()); entryOld.setLetter(null); commitTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } @Override public List<Object> searchFinancialTransaction(FinancialTransactionSearch financialTransactionSearch) throws LimaException { List<Object> result = new ArrayList<Object>(); - List<FinancialTransaction> financialTransactions = null; - TopiaContext topiaContext = null; + List<FinancialTransaction> financialTransactions; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); FinancialTransactionDAO financialTransactionDAO = - LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); + LimaCallaoDAOHelper.getFinancialTransactionDAO(topiaContext); TopiaQuery query = financialTransactionDAO.createQuery("T"); - - String dateProperty = TopiaQuery.getProperty(FinancialTransaction.TRANSACTION_DATE); + + String dateProperty = TopiaQuery.getProperty(FinancialTransaction.TRANSACTION_DATE); String accountNumberProperty = TopiaQuery.getProperty(Entry.ACCOUNT, Account.ACCOUNT_NUMBER); - + query.addDistinct(); - query.addLeftJoin("T."+FinancialTransaction.ENTRY, "E", true); + query.addLeftJoin("T." + FinancialTransaction.ENTRY, "E", true); //Load for lazy query.addLoad(FinancialTransaction.ENTRY_BOOK) - .addLoad(FinancialTransaction.FINANCIAL_PERIOD); - + .addLoad(FinancialTransaction.FINANCIAL_PERIOD); + Date beginDate = financialTransactionSearch.getBeginDate(); Date endDate = financialTransactionSearch.getEndDate(); - if (beginDate != null && endDate != null){ + if (beginDate != null && endDate != null) { query.addBetween(dateProperty, beginDate, endDate); - } - else if (beginDate != null){ + } else if (beginDate != null) { query.addEquals(dateProperty, beginDate); } String voucher = financialTransactionSearch.getVoucher(); - if (voucher != null){ - query.addWhere("E.voucher", Op.LIKE, "%"+voucher+"%"); + if (voucher != null) { + query.addWhere("E.voucher", Op.LIKE, "%" + voucher + "%"); } String description = financialTransactionSearch.getDescription(); - if (description != null){ - query.addWhere("E.description", Op.LIKE, "%"+description+"%"); + if (description != null) { + query.addWhere("E.description", Op.LIKE, "%" + description + "%"); } Letter letter = financialTransactionSearch.getLetter(); - if (letter != null){ + if (letter != null) { query.addEquals("E.letter", letter); } Account account = financialTransactionSearch.getAccount(); String accountsList = financialTransactionSearch.getAccountList(); - if (account != null){ + if (account != null) { query.addEquals("E.account", account); - } - else if (accountsList != null){ + } else if (accountsList != null) { AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(topiaContext); - List<Account> accounts = - accountDAO.stringToListAccounts(accountsList, false); + List<Account> accounts = + accountDAO.stringToListAccounts(accountsList, false); StringBuffer accountNumbers = new StringBuffer("0,"); int max = accounts.size(); for (int i = 1; i <= max; i++) { - accountNumbers.append(accounts.get(i-1).getAccountNumber()); - if (i != max){ + accountNumbers.append(accounts.get(i - 1).getAccountNumber()); + if (i != max) { accountNumbers.append(","); } } - if (accounts.size() > 0){ - query.addWhere("E."+accountNumberProperty + " in (" + accountNumbers + ")"); + if (accounts.size() > 0) { + query.addWhere("E." + accountNumberProperty + " in (" + accountNumbers + ")"); } - + } EntryBook entryBook = financialTransactionSearch.getEntryBook(); String amount = financialTransactionSearch.getAmount(); String amount2 = financialTransactionSearch.getAmount2(); String operator = financialTransactionSearch.getOperator(); FinancialStatementWayEnum fStWayEnum = financialTransactionSearch.getAmountWayEnum(); - if (entryBook != null){ - query.addEquals("T."+FinancialTransaction.ENTRY_BOOK, entryBook); - } - if (amount != null){ - if (amount2 != null){ + if (entryBook != null) { + query.addEquals("T." + FinancialTransaction.ENTRY_BOOK, entryBook); + } + if (amount != null) { + if (amount2 != null) { BigDecimal value1 = new BigDecimal(amount); BigDecimal value2 = new BigDecimal(amount2); query.addBetween("E.amount", value1, value2); + } else if (operator != null) { + query.addWhere("E.amount" + " " + operator + " " + amount); } - else if (operator != null) { - query.addWhere("E.amount"+" "+operator+" "+amount); - } switch (fStWayEnum) { - case CREDIT: - query.addEquals("E.debit", false); - break; - case DEBIT: - query.addEquals("E.debit", true); - break; + case CREDIT: + query.addEquals("E.debit", false); + break; + case DEBIT: + query.addEquals("E.debit", true); + break; } } financialTransactions = financialTransactionDAO.findAllByQuery(query); - + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); for (FinancialTransaction financialTransaction : financialTransactions) { result.add(financialTransaction); - + TopiaQuery query2 = entryDAO.createQuery(); query2.addEquals(Entry.FINANCIAL_TRANSACTION, financialTransaction); //Load for lazy @@ -929,34 +838,12 @@ List<Entry> entries = entryDAO.findAllByQuery(query2); result.addAll(entries); } + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } return result; } - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } - - protected void commitTransaction(TopiaContext topiaTransaction) throws TopiaException { - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } - } \ No newline at end of file Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FiscalPeriodServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FiscalPeriodServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FiscalPeriodServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,34 +25,20 @@ package org.chorem.lima.business.ejb; -import static org.nuiton.i18n.I18n._; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import javax.ejb.EJB; -import javax.ejb.Stateless; import org.apache.commons.lang.time.DateUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.beans.BalanceTrial; import org.chorem.lima.beans.ReportsDatas; import org.chorem.lima.business.AccountingRules; import org.chorem.lima.business.LimaBusinessException; import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; -import org.chorem.lima.business.ejbinterface.AccountService; -import org.chorem.lima.business.ejbinterface.EntryBookService; +import org.chorem.lima.business.ejbinterface.AccountServiceLocal; +import org.chorem.lima.business.ejbinterface.EntryBookServiceLocal; import org.chorem.lima.business.ejbinterface.FinancialPeriodServiceLocal; import org.chorem.lima.business.ejbinterface.FinancialTransactionServiceLocal; import org.chorem.lima.business.ejbinterface.FiscalPeriodService; import org.chorem.lima.business.ejbinterface.FiscalPeriodServiceLocal; -import org.chorem.lima.business.ejbinterface.ReportService; +import org.chorem.lima.business.ejbinterface.ReportServiceLocal; import org.chorem.lima.business.utils.FinancialPeriodComparator; import org.chorem.lima.entity.Account; import org.chorem.lima.entity.AccountImpl; @@ -67,12 +53,23 @@ import org.chorem.lima.entity.FiscalPeriodDAO; import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; +import javax.ejb.EJB; +import javax.ejb.Stateless; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import static org.nuiton.i18n.I18n._; + + /** * Gestion des exercices. * Un exercice ne peut être supprimée et débloquée après cloture. @@ -82,265 +79,233 @@ @Stateless public class FiscalPeriodServiceImpl extends AbstractLimaService implements FiscalPeriodService, FiscalPeriodServiceLocal { - private static final Log log = LogFactory.getLog(FiscalPeriodServiceImpl.class); + private TopiaContext rootContext; - private static TopiaContext rootContext; - protected AccountingRules accountingRules; - + @EJB - protected AccountService accountService; - + protected AccountServiceLocal accountService; + @EJB protected FinancialPeriodServiceLocal financialPeriodService; - + @EJB - protected EntryBookService entryBookService; - + protected EntryBookServiceLocal entryBookService; + @EJB - protected ReportService reportService; - + protected ReportServiceLocal reportService; + @EJB protected FinancialTransactionServiceLocal financialTransactionService; public FiscalPeriodServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - accountingRules = config.getAccountingRules(); + rootContext = acquireRootContext(); + accountingRules = LimaConfig.getInstance().getAccountingRules(); } - + @Override - public void createFiscalPeriodWithTransaction(FiscalPeriod fiscalPeriod, TopiaContext topiaContext) throws LimaException { + public void createFiscalPeriodWithTransaction(FiscalPeriod fiscalPeriod, + TopiaContext topiaContext) throws LimaException { try { - + Date beginDate = fiscalPeriod.getBeginDate(); beginDate = DateUtils.truncate(beginDate, Calendar.DATE); Date endDate = fiscalPeriod.getEndDate(); endDate = DateUtils.addDays(endDate, 1); endDate = DateUtils.truncate(endDate, Calendar.DATE); - endDate = DateUtils.addMilliseconds(endDate,-1); + endDate = DateUtils.addMilliseconds(endDate, -1); fiscalPeriod.setBeginDate(beginDate); fiscalPeriod.setEndDate(endDate); - + //check rules before create the account List<FinancialPeriod> financialPeriods = - accountingRules.createFiscalPeriodRules(fiscalPeriod, topiaContext); + accountingRules.createFiscalPeriodRules(fiscalPeriod, topiaContext); financialPeriodService. - createFinancialPeriodsWithTransaction(financialPeriods, topiaContext); - - FiscalPeriodDAO fiscalPeriodDAO = - LimaCallaoDAOHelper.getFiscalPeriodDAO(topiaContext); - + createFinancialPeriodsWithTransaction(financialPeriods, topiaContext); + + FiscalPeriodDAO fiscalPeriodDAO = + LimaCallaoDAOHelper.getFiscalPeriodDAO(topiaContext); + //create fiscalPeriodDAO.create(fiscalPeriod); commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } } - + /** * To create a fiscalperiod * Check localized rules before create */ @Override public void createFiscalPeriod(FiscalPeriod fiscalPeriod) throws LimaException { - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - + createFiscalPeriodWithTransaction(fiscalPeriod, transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - } - /** - * return all fiscal period - */ + /** return all fiscal period */ + @Override public List<FiscalPeriod> getAllFiscalPeriods() throws LimaException { - + List<FiscalPeriod> result = null; - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); FiscalPeriodDAO fiscalPeriodDAO = - LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); - result = fiscalPeriodDAO.findAll(); + LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); + result = fiscalPeriodDAO.findAll(); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return result; } - - - /** - * return all blocked fiscal periods - */ + + + /** return all blocked fiscal periods */ + @Override public List<FiscalPeriod> getAllBlockedFiscalPeriods() throws LimaException { - + List<FiscalPeriod> result = null; - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - + FiscalPeriodDAO fiscalPeriodDAO = - LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); + LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); result = fiscalPeriodDAO.findAllByLocked(true); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return result; } - - /** - * return all unblocked fiscal periods - */ + + /** return all unblocked fiscal periods */ + @Override public List<FiscalPeriod> getAllUnblockedFiscalPeriods() throws LimaException { - + List<FiscalPeriod> result = null; - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); FiscalPeriodDAO fiscalPeriodDAO = - LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); + LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); result = fiscalPeriodDAO.findAllByLocked(false); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return result; } - + @Override public FiscalPeriod getLastFiscalPeriod() throws LimaException { FiscalPeriod result = null; - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); FiscalPeriodDAO fiscalPeriodDAO = - LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); + LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); TopiaQuery query = fiscalPeriodDAO.createQuery(); - query.addOrderDesc(FiscalPeriod.END_DATE); - + query.addOrderDesc(FiscalPeriod.END_DATE); + //get the last fiscal period result = fiscalPeriodDAO.findByQuery(query); - + + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + return result; } - + /** * to block a fiscal period - * + * <p/> * check localized rules before block it */ @Override public void blockFiscalPeriod(FiscalPeriod fiscalPeriod) throws LimaException { - TopiaContext transaction = null; - + TopiaContext transaction = beginTransaction(rootContext); + //open transaction for update try { - transaction = beginTransaction(); - - if (fiscalPeriod.getLocked()){ + + if (fiscalPeriod.getLocked()) { throw new LimaBusinessException(_("lima-business.fiscalperiod.fiscalperiodalreadyblocked")); } //check rules accountingRules.blockFiscalPeriodRules(fiscalPeriod, transaction); - + FiscalPeriodDAO fiscalPeriodDAO = - LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); - + LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); + // Get the old fiscal period instance for no object conflict FiscalPeriod oldFiscalPeriod = - fiscalPeriodDAO.findByTopiaId(fiscalPeriod.getTopiaId()); - + fiscalPeriodDAO.findByTopiaId(fiscalPeriod.getTopiaId()); + // lock fiscalperiod oldFiscalPeriod.setLocked(true); // locked all financialperiod of the fiscalperiod - for ( FinancialPeriod financialPeriod : oldFiscalPeriod.getFinancialPeriod()) { + for (FinancialPeriod financialPeriod : oldFiscalPeriod.getFinancialPeriod()) { financialPeriod.setLocked(true); } - + fiscalPeriodDAO.update(oldFiscalPeriod); - + commitTransaction(transaction); - - } catch (TopiaException ex) { - doCatch(transaction, ex, log); + + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - finally { - doFinally(transaction, log); - } } - + @Override public void addRetainedEarnings(FiscalPeriod fiscalPeriod, boolean newyear, - EntryBook entryBook) throws LimaException { - - TopiaContext topiaContext = null; + EntryBook entryBook) throws LimaException { + + TopiaContext topiaContext = beginTransaction(rootContext); try { - + //sets dates // - endRetainedEarnings: last day of the closing year // - beginRetainedEarnings: first open day of the following year - Date endRetainedEarnings = fiscalPeriod.getBeginDate(); - Date beginRetainedEarnings = null; - - topiaContext = beginTransaction(); - +// Date endRetainedEarnings = fiscalPeriod.getBeginDate(); +// Date beginRetainedEarnings = null; + //Sets entryBook //search for the entryBook to use using param boolean found = false; List<EntryBook> entryBooksList = entryBookService.getAllEntryBooks(); for (EntryBook entry : entryBooksList) { if (!found && entry.getCode().equals(entryBook.getCode()) - && entry.getLabel().equals(entryBook.getLabel())) { + && entry.getLabel().equals(entryBook.getLabel())) { entryBook = entry; found = true; } @@ -352,19 +317,19 @@ entryBooksList = entryBookService.getAllEntryBooks(); for (EntryBook entry : entryBooksList) { if (!found && entry.getCode().equals(entryBook.getCode()) - && entry.getLabel().equals(entryBook.getLabel())) { + && entry.getLabel().equals(entryBook.getLabel())) { entryBook = entry; found = true; } } } - + //Sets accounts, check if they exist, if not create them //-> 8 COMPTES SPECIAUX // -> 89 BILAN // -> 890 Bilan d'ouverture // -> 891 Bilan de cloture - + //89 BILAN Account accountMaster = accountService.getAccountByNumber("89"); if (accountMaster == null) { @@ -374,7 +339,7 @@ accountService.createAccount(accountSuperMaster, accountMaster); accountMaster = accountService.getAccountByNumber("89"); } - + //890 Bilan d'ouverture Account beginRetainedAccount = accountService.getAccountByNumber("890"); if (beginRetainedAccount == null) { @@ -384,7 +349,7 @@ accountService.createAccount(accountMaster, beginRetainedAccount); beginRetainedAccount = accountService.getAccountByNumber("890"); } - + //891 Bilan de cloture Account endRetainedAccount = accountService.getAccountByNumber("891"); if (endRetainedAccount == null) { @@ -394,14 +359,14 @@ accountService.createAccount(accountMaster, endRetainedAccount); endRetainedAccount = accountService.getAccountByNumber("891"); } - + //look for the last financial period from the previous fiscal year Collection<FinancialPeriod> fperiod = fiscalPeriod.getFinancialPeriod(); - - Iterator itr = fperiod.iterator(); + + Iterator<FinancialPeriod> itr = fperiod.iterator(); FinancialPeriod lastFPeriod = null; while (itr.hasNext()) { - lastFPeriod = (FinancialPeriod) itr.next(); + lastFPeriod = itr.next(); } //check if the last financial period isn't blocked if (lastFPeriod.getLocked()) { @@ -414,9 +379,9 @@ //look for the first financial period on the new fiscal year which is unlocked found = false; List<ClosedPeriodicEntryBook> resultsArray = - new ArrayList<ClosedPeriodicEntryBook>(); + new ArrayList<ClosedPeriodicEntryBook>(); List<ClosedPeriodicEntryBook> closedPeriodicEntryBook = - financialPeriodService.getAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod(); + financialPeriodService.getAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod(); Collections.sort(closedPeriodicEntryBook, new FinancialPeriodComparator()); resultsArray.addAll(closedPeriodicEntryBook); for (ClosedPeriodicEntryBook cPeriodicEntryBook : resultsArray) { @@ -425,10 +390,10 @@ // - unlocked entrybook // - right code and label if (!found && !cPeriodicEntryBook.getFinancialPeriod().getLocked() - && cPeriodicEntryBook.getFinancialPeriod().getBeginDate().after(fiscalPeriod.getEndDate()) - && !cPeriodicEntryBook.getLocked() - && cPeriodicEntryBook.getEntryBook().getCode().equals(entryBook.getCode()) - && cPeriodicEntryBook.getEntryBook().getLabel().equals(entryBook.getLabel())) { + && cPeriodicEntryBook.getFinancialPeriod().getBeginDate().after(fiscalPeriod.getEndDate()) + && !cPeriodicEntryBook.getLocked() + && cPeriodicEntryBook.getEntryBook().getCode().equals(entryBook.getCode()) + && cPeriodicEntryBook.getEntryBook().getLabel().equals(entryBook.getLabel())) { found = true; beginfinancialPeriod = cPeriodicEntryBook.getFinancialPeriod(); } @@ -437,7 +402,7 @@ throw new LimaBusinessException(_("lima-business.fiscalperiod.newfinancialperioderror")); } } - + //holds entries of all closing transactions FinancialTransaction endfinancialTransaction = new FinancialTransactionImpl(); if (lastFPeriod != null) { @@ -449,7 +414,7 @@ endfinancialTransaction.setTransactionDate(fiscalPeriod.getEndDate()); financialTransactionService.createFinancialTransaction(endfinancialTransaction); } - + //holds entries of all opening transactions FinancialTransaction beginfinancialTransaction = new FinancialTransactionImpl(); if (newyear) { @@ -463,26 +428,26 @@ financialTransactionService.createFinancialTransaction(beginfinancialTransaction); } } - + //Sets date for description, e.g: Report à nouveau (DATE) Calendar calendar = Calendar.getInstance(); calendar.setTime(fiscalPeriod.getEndDate()); - + //Sets entries - Entry beginEntry = null; - - + Entry beginEntry; + + BalanceTrial results = reportService.generateBalanceTrial(fiscalPeriod.getBeginDate(), fiscalPeriod.getEndDate(), null, false, false); - List<ReportsDatas> reportsDatasList = (List<ReportsDatas>) results.getReportsDatas(); + List<ReportsDatas> reportsDatasList = (List<ReportsDatas>) results.getReportsDatas(); //check if at least one transaction has been reported boolean transaction = false; - + for (ReportsDatas report : reportsDatasList) { //Account class from 1 to 5 and only non zero amount if (Integer.valueOf(report.getAccount().getAccountNumber().substring(0, 1)) < 6 - && !report.getAmountSolde().equals(BigDecimal.ZERO)) { + && !report.getAmountSolde().equals(BigDecimal.ZERO)) { transaction = true; //close accounts by removing amounts from all class 1 to 5 accounts beginEntry = new EntryImpl(); @@ -528,38 +493,15 @@ //if no transaction has been reported if (!transaction) { topiaContext.rollbackTransaction(); - //if no problem appeared, commit + //if no problem appeared, commit } else { commitTransaction(topiaContext); } + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } - - - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } - - protected void commitTransaction(TopiaContext topiaTransaction) throws TopiaException { - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/HttpServerServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/HttpServerServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/HttpServerServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,31 +25,11 @@ package org.chorem.lima.business.ejb; -import static org.nuiton.i18n.I18n._; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import javax.ejb.EJB; -import javax.ejb.Stateless; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.time.DateUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.pdfbox.exceptions.COSVisitorException; import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; -import org.chorem.lima.business.ejbinterface.DocumentService; +import org.chorem.lima.business.ejbinterface.DocumentServiceLocal; import org.chorem.lima.business.ejbinterface.HttpServerService; import org.chorem.lima.business.ejbinterface.HttpServerServiceLocal; import org.chorem.lima.business.utils.DocumentsEnum; @@ -58,54 +38,72 @@ import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; +import org.nuiton.util.FileUtil; import org.nuiton.util.Resource; +import javax.ejb.EJB; +import javax.ejb.Stateless; +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import static org.nuiton.i18n.I18n._; + + @Stateless public class HttpServerServiceImpl extends AbstractLimaService implements HttpServerService, HttpServerServiceLocal { - private static final Log log = LogFactory.getLog(HttpServerServiceImpl.class); - @EJB - private DocumentService documentService; - + private DocumentServiceLocal documentService; + protected Server server; - + protected String path; - + protected int port; - + private static final SimpleDateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd"); - + public HttpServerServiceImpl() { - path = LimaConfig.getInstance().getReportsDir(); + path = LimaConfig.getInstance().getReportsDir().getAbsolutePath(); port = LimaConfig.getInstance().getHttpPort(); - } - - - + } + + /** start the server */ @Override public void start() { - if (server == null) { - new File(path).mkdir(); + if (server == null) { + try { + FileUtil.createDirectoryIfNecessary(new File(path)); + server = new Server(port); - + Context root = new Context(server, "/", Context.NO_SESSIONS); root.addServlet(new ServletHolder((Servlet) new MainServlet()), "/"); server.start(); - - log.info("Web server are running on port: "+port); - + + log.info("Web server are running on port: " + port); + } catch (Exception eee) { log.error("error while booting http server", eee); } } } - - - + + @Override public int getHttpPort() { return port; @@ -115,168 +113,167 @@ /** this servlet send a static html page */ public class MainServlet extends HttpServlet { private static final long serialVersionUID = 1L; + private String serverAddressConfig = LimaConfig.getInstance().getAddressServer(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - + try { - //get all params - String imageParam = req.getParameter("img"); - String model = req.getParameter("model"); - String format = req.getParameter("format"); - String beginDate = req.getParameter("beginDate"); - String endDate = req.getParameter("endDate"); - String autocomplete = req.getParameter("autocomplete"); + //get all params + String imageParam = req.getParameter("img"); + String model = req.getParameter("model"); + String format = req.getParameter("format"); + String beginDate = req.getParameter("beginDate"); + String endDate = req.getParameter("endDate"); + String autocomplete = req.getParameter("autocomplete"); - //if image - if (imageParam != null){ - URL image = Resource.getURLOrNull("images/"+imageParam); - if (image != null){ - resp.setContentType("image/png"); - InputStream in = image.openStream(); + //if image + if (imageParam != null) { + URL image = Resource.getURLOrNull("images/" + imageParam); + if (image != null) { + resp.setContentType("image/png"); + InputStream in = image.openStream(); + OutputStream out = resp.getOutputStream(); + IOUtils.copy(in, out); + } + } + //if doc pdf or html + else if (model != null && format != null && beginDate != null && endDate != null) { + FormatsEnum formatsEnum = FormatsEnum.valueOfExtension(format); + URL doc = new URL("file:" + path + File.separator + + model + formatsEnum.getExtension()); + //create docs + try { + Date beginDateFormat = DATEFORMAT.parse(beginDate); + Date endDateFormat = DATEFORMAT.parse(endDate); + + switch (DocumentsEnum.valueOfLink(model)) { + case BALANCE: + documentService.createBalanceDocuments( + beginDateFormat, endDateFormat, formatsEnum); + break; + case ENTRYBOOKS: + documentService.createEntryBooksDocuments( + beginDateFormat, endDateFormat, formatsEnum); + break; + case FINANCIALSTATEMENT: + documentService.createFinancialStatementsDocuments( + beginDateFormat, endDateFormat, formatsEnum); + break; + case GENERAL_ENTRYBOOK: + documentService.createGeneralEntryBooksDocuments( + beginDateFormat, endDateFormat, formatsEnum); + break; + case LEDGER: + documentService.createLedgerDocuments( + beginDateFormat, endDateFormat, formatsEnum); + break; + case VAT: + documentService.createVatDocuments( + beginDateFormat, endDateFormat, formatsEnum, + autocomplete); + break; + } + } catch (LimaException eeeLE) { + log.error("Can't call document service for create html document", eeeLE); + } catch (ParseException eeePE) { + log.error("Can't parse date", eeePE); + } + resp.setContentType(formatsEnum.getMimeType()); + InputStream in = doc.openStream(); OutputStream out = resp.getOutputStream(); IOUtils.copy(in, out); } - } - //if doc pdf or html - else if (model != null && format != null && beginDate != null && endDate != null){ - FormatsEnum formatsEnum = FormatsEnum.valueOfExtension(format); - URL doc = new URL("file:" + path + File.separator - + model +formatsEnum.getExtension()); - //create docs - try { - Date beginDateFormat = DATEFORMAT.parse(beginDate); - Date endDateFormat = DATEFORMAT.parse(endDate); - - switch (DocumentsEnum.valueOfLink(model)) { - case BALANCE: - documentService.createBalanceDocuments( - beginDateFormat, endDateFormat, formatsEnum); - break; - case ENTRYBOOKS: - documentService.createEntryBooksDocuments( - beginDateFormat, endDateFormat, formatsEnum); - break; - case FINANCIALSTATEMENT: - documentService.createFinancialStatementsDocuments( - beginDateFormat, endDateFormat, formatsEnum); - break; - case GENERAL_ENTRYBOOK: - documentService.createGeneralEntryBooksDocuments( - beginDateFormat, endDateFormat, formatsEnum); - break; - case LEDGER: - documentService.createLedgerDocuments( - beginDateFormat, endDateFormat, formatsEnum); - break; - case VAT: - documentService.createVatDocuments( - beginDateFormat, endDateFormat, formatsEnum, - autocomplete); - break; - } - } catch (LimaException eeeLE) { - log.error("Can't call document service for create html document", eeeLE); - } catch (ParseException eeePE) { - log.error("Can't parse date", eeePE); - } catch (COSVisitorException eeeCOSVE) { - log.error("Can't create document", eeeCOSVE); - } - resp.setContentType(formatsEnum.getMimeType()); - InputStream in = doc.openStream(); - OutputStream out = resp.getOutputStream(); - IOUtils.copy(in, out); - } - // else return home html - else { - resp.setContentType(FormatsEnum.HTML.getMimeType()); - StringBuffer pageContent = new StringBuffer(); - String serverAdress = "http://"; - - log.info("Page load"); - - /** create server Address : static config if exist or dynamical adress */ - if (serverAddressConfig.equals("")){ - serverAdress += req.getServerName() - + ":" + req.getServerPort(); - } + // else return home html else { - serverAdress += serverAddressConfig + ":" - + LimaConfig.getInstance().getHttpPort(); - } - - Calendar calendar = Calendar.getInstance(); - Date endDatePicker = calendar.getTime(); - Date beginDatePicker = calendar.getTime(); - beginDatePicker = - DateUtils.truncate(beginDatePicker, Calendar.YEAR); - - pageContent.append("<!DOCTYPE html>\n" - + "<html lang=\"fr\">\n" - + "<head>\n" - + "<title>LIMA Documents Report</title>\n" - + "<style type=\"text/css\">" - + "body { font: 14px sans-serif; }" - + "h1 { font: 20px sans-serif; text-align: center; }" - + "table.padding td {padding-right:20px;}" - + ".tdright {text-align: right;}" - + "</style>" - + "</head>\n" - + "<body>\n" - + "<table class=\"padding\">\n" - + "<tr><td><img src=\"?img=puzzle_icon_mini.png\"/></td>\n" - + "<td><h1>LIMA Documents Report</h1></td></tr>\n" - + "<tr><td class=\"tdright\"><img src=\"?img=identity.png\"/></td>\n" - + "<td rowspan=3><form method=GET action=" - + serverAdress + ">\n" - + _("lima-business.document.date.begin") - + "<input value=\""+DATEFORMAT.format(beginDatePicker) - + "\" type=\"date\" name=\"beginDate\">\n" - + _("lima-business.document.date.end") - + "<input value=\""+DATEFORMAT.format(endDatePicker) - + "\" type=\"date\" name=\"endDate\">\n<br/><br/>" - + "Format : <select name=\"format\">"); - - for (FormatsEnum formatsEnum : FormatsEnum.values()) { - pageContent.append("<option value=\"" - + formatsEnum.getExtension()+"\">" - + formatsEnum.getDescription()+"</option>\n"); - } - - pageContent.append("</select>\n" - + "Documents : <select name=\"model\">"); - - for (DocumentsEnum documentsEnum : DocumentsEnum.values()) { - pageContent.append("<option value=\"" - + documentsEnum.getFileName()+"\">" - + documentsEnum.getDescription()+"</option>\n"); - } - - pageContent.append("</select>\n" - + "<tr><td class=\"tdright\"><img src=\"?img=entries.png\"/></td></tr>\n" - + "<tr><td class=\"tdright\"><img src=\"?img=accounts.png\"/></td></tr>\n" - + "<tr><td class=\"tdright\"><img src=\"?img=entrybooks.png\"/></td>\n" - + "<td class=\"tdright\"><input type=\"submit\"></td></tr>" - + "</form>\n" - + "<tr><td class=\"tdright\"><img src=\"?img=fiscalperiods.png\"/></td></tr>\n" - + "</table>\n" - + "</body>\n" - + "</html>"); + resp.setContentType(FormatsEnum.HTML.getMimeType()); + StringBuilder pageContent = new StringBuilder(); + String serverAdress = "http://"; - resp.getWriter().write(pageContent.toString()); + log.info("Page load"); - } - }catch (GenericJDBCException eee) { + /** create server Address : static config if exist or dynamical adress */ + if (serverAddressConfig.equals("")) { + serverAdress += req.getServerName() + + ":" + req.getServerPort(); + } else { + serverAdress += serverAddressConfig + ":" + + LimaConfig.getInstance().getHttpPort(); + } + + Calendar calendar = Calendar.getInstance(); + Date endDatePicker = calendar.getTime(); + Date beginDatePicker = calendar.getTime(); + beginDatePicker = + DateUtils.truncate(beginDatePicker, Calendar.YEAR); + + pageContent.append("<!DOCTYPE html>\n" + + "<html lang=\"fr\">\n" + + "<head>\n" + + "<title>LIMA Documents Report</title>\n" + + "<style type=\"text/css\">" + + "body { font: 14px sans-serif; }" + + "h1 { font: 20px sans-serif; text-align: center; }" + + "table.padding td {padding-right:20px;}" + + ".tdright {text-align: right;}" + + "</style>" + + "</head>\n" + + "<body>\n" + + "<table class=\"padding\">\n" + + "<tr><td><img src=\"?img=puzzle_icon_mini.png\"/></td>\n" + + "<td><h1>LIMA Documents Report</h1></td></tr>\n" + + "<tr><td class=\"tdright\"><img src=\"?img=identity.png\"/></td>\n" + + "<td rowspan=3><form method=GET action=" + + serverAdress + ">\n" + + _("lima-business.document.date.begin") + + "<input value=\"" + DATEFORMAT.format(beginDatePicker) + + "\" type=\"date\" name=\"beginDate\">\n" + + _("lima-business.document.date.end") + + "<input value=\"" + DATEFORMAT.format(endDatePicker) + + "\" type=\"date\" name=\"endDate\">\n<br/><br/>" + + "Format : <select name=\"format\">"); + + for (FormatsEnum formatsEnum : FormatsEnum.values()) { + pageContent.append("<option value=\"" + + formatsEnum.getExtension() + "\">" + + formatsEnum.getDescription() + "</option>\n"); + } + + pageContent.append("</select>\n" + + "Documents : <select name=\"model\">"); + + for (DocumentsEnum documentsEnum : DocumentsEnum.values()) { + pageContent.append("<option value=\"" + + documentsEnum.getFileName() + "\">" + + documentsEnum.getDescription() + "</option>\n"); + } + + pageContent.append("</select>\n" + + "<tr><td class=\"tdright\"><img src=\"?img=entries.png\"/></td></tr>\n" + + "<tr><td class=\"tdright\"><img src=\"?img=accounts.png\"/></td></tr>\n" + + "<tr><td class=\"tdright\"><img src=\"?img=entrybooks.png\"/></td>\n" + + "<td class=\"tdright\"><input type=\"submit\"></td></tr>" + + "</form>\n" + + "<tr><td class=\"tdright\"><img src=\"?img=fiscalperiods.png\"/></td></tr>\n" + + "</table>\n" + + "</body>\n" + + "</html>"); + + resp.getWriter().write(pageContent.toString()); + + } + } catch (GenericJDBCException eee) { log.error("Can't read db", eee); } } + @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); - + } } - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/IdentityServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/IdentityServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/IdentityServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,13 +25,6 @@ package org.chorem.lima.business.ejb; -import java.util.List; - -import javax.ejb.Stateless; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; import org.chorem.lima.business.ejbinterface.IdentityService; import org.chorem.lima.business.ejbinterface.IdentityServiceLocal; @@ -39,30 +32,20 @@ import org.chorem.lima.entity.IdentityDAO; import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; +import javax.ejb.Stateless; +import java.util.List; + @Stateless public class IdentityServiceImpl extends AbstractLimaService implements IdentityService, IdentityServiceLocal { - private static final Log log = - LogFactory.getLog(AccountServiceImpl.class); - private TopiaContext rootContext; - + public IdentityServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } + rootContext = acquireRootContext(); } - - + @Override public Identity getIdentityWithTransaction(TopiaContext topiaContext) throws LimaException { @@ -71,89 +54,61 @@ IdentityDAO identityDAO = LimaCallaoDAOHelper.getIdentityDAO(topiaContext); List<Identity> identities = identityDAO.findAll(); - if (identities.size() != 0){ + if (identities.size() != 0) { identity = identities.get(0); } + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } return identity; } - + @Override public Identity getIdentity() throws LimaException { - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); Identity identity = null; try { - topiaContext = beginTransaction(); identity = getIdentityWithTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } return identity; } - - + + @Override public void updateIdentityWithTransaction(Identity identity, - TopiaContext topiaContext) throws LimaException { + TopiaContext topiaContext) throws LimaException { try { IdentityDAO identityDAO = LimaCallaoDAOHelper.getIdentityDAO(topiaContext); List<Identity> identities = identityDAO.findAll(); - if (identities.size() != 0){ + if (identities.size() != 0) { identityDAO.delete(identities.get(0)); } identityDAO.create(identity); commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } } - + @Override public void updateIdentity(Identity identity) throws LimaException { - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); updateIdentityWithTransaction(identity, topiaContext); commitTransaction(topiaContext); + } catch (Exception ex) { + doCatch(topiaContext, ex); + } finally { + doFinally(topiaContext); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - finally { - doFinally(topiaContext, log); - } } - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaContext; - topiaContext = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaContext); - return topiaContext; - } - - protected void commitTransaction(TopiaContext topiaContext) throws TopiaException { - try { - topiaContext.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } - } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ImportServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ImportServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ImportServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,32 +25,10 @@ package org.chorem.lima.business.ejb; -import static org.nuiton.i18n.I18n._; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.math.BigDecimal; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import javax.ejb.EJB; -import javax.ejb.Stateless; - +import au.com.bytecode.opencsv.CSVReader; +import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy; +import au.com.bytecode.opencsv.bean.CsvToBean; import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.interactive.form.PDField; @@ -121,27 +99,42 @@ import org.chorem.lima.entity.VatStatementDAO; import org.chorem.lima.entity.VatStatementImpl; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; -import au.com.bytecode.opencsv.CSVReader; -import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy; -import au.com.bytecode.opencsv.bean.CsvToBean; +import javax.ejb.EJB; +import javax.ejb.Stateless; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static org.nuiton.i18n.I18n._; + /** * CSV import export service. - * + * * @version $Revision$ - * + * <p/> * Last update : $Date: 2010-07-26 18:32:09 +0200 (lun., 26 juil. 2010) * $ By : $Author$ */ @Stateless -public class ImportServiceImpl extends AbstractLimaService implements - ImportService, ImportServiceLocal { +public class ImportServiceImpl extends AbstractLimaService implements ImportService, ImportServiceLocal { - private static final Log log = LogFactory.getLog(ImportServiceImpl.class); - private TopiaContext rootContext; // Services @@ -160,7 +153,7 @@ @EJB private FinancialStatementServiceLocal financialStatementService; - + @EJB private VatStatementServiceLocal vatStatementService; @@ -174,14 +167,7 @@ "dd,MM,yyyy HH:mm:ss"); public ImportServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } + rootContext = acquireRootContext(); } // ################ IMPORT THIRD PART ACCOUNTING SOFTWARE ################ @@ -189,12 +175,10 @@ @Override public String importEntriesFromEbp(String datas) throws LimaException { SimpleDateFormat epbDateFormat = new SimpleDateFormat("dd/MM/yyyy"); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - CSVReader csvReader = new CSVReader(new StringReader(datas)); ColumnPositionMappingStrategy<EntryEBPImpl> strat = new ColumnPositionMappingStrategy<EntryEBPImpl>(); strat.setType(EntryEBPImpl.class); @@ -242,22 +226,22 @@ // create entry Entry entry = new EntryImpl(); Account account = accountDAO.findByAccountNumber(entryEBP - .getCompte()); - + .getCompte()); + Date date = epbDateFormat.parse(entryEBP.getDatEcr()); Date beginDate = fiscalPeriods.get(0).getBeginDate(); - Date endDate = fiscalPeriods.get(nbFiscalPeriods-1).getEndDate(); + Date endDate = fiscalPeriods.get(nbFiscalPeriods - 1).getEndDate(); //if entry date have fiscalperiod open - if (date.compareTo(beginDate) < 0 || date.compareTo(endDate) > 0){ + if (date.compareTo(beginDate) < 0 || date.compareTo(endDate) > 0) { - result.append(_("lima-business.import.entriesoutofdatesrange",date)); + result.append(_("lima-business.import.entriesoutofdatesrange", date)); } // if account not exist not export else if (account == null) { - throw new LimaBusinessException( - _("lima-business.import.ebpmissingaccount", - entryEBP.getCompte())); + throw new LimaBusinessException( + _("lima-business.import.ebpmissingaccount", + entryEBP.getCompte())); } //create entry else { @@ -273,11 +257,11 @@ } entry.setDescription(entryEBP.getLibelle()); entry.setVoucher(entryEBP.getPiece()); - + Letter letter = createLetter( entryEBP.getLettre(), topiaContext); entry.setLetter(letter); - + String entryBookCode = entryEBP.getJournal(); EntryBook entryBook = entryBookDAO .findByCode(entryBookCode); @@ -287,13 +271,13 @@ entryBook.setCode(entryBookCode); // create it entryBookService.createEntryBook(entryBook); - result.append(_("lima-business.import.entrybooknotexist",entryBook)); + result.append(_("lima-business.import.entrybooknotexist", entryBook)); } //create transaction if (financialTransaction == null || !(date.equals(financialTransaction.getTransactionDate()) - && entryBook.getCode().equals(financialTransaction.getEntryBook().getCode()))) { - + && entryBook.getCode().equals(financialTransaction.getEntryBook().getCode()))) { + // update previous financial transaction before create // new if (financialTransaction != null) { @@ -332,25 +316,20 @@ } // commit commitTransaction(topiaContext); - } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); - } catch (IOException eeeIO) { - log.error("Can't read string", eeeIO); - } catch (ParseException eeePE) { - log.error("Can't parse date", eeePE); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); } finally { - doFinally(topiaContext, log); + doFinally(topiaContext); } return result.toString(); } @Override public String importAccountsChartFromEbp(String datas) throws LimaException { - StringBuffer result = new StringBuffer(); - TopiaContext topiaContext = null; + StringBuilder result = new StringBuilder(); + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); CSVReader csvReader = new CSVReader(new StringReader(datas)); ColumnPositionMappingStrategy<AccountEBPImpl> strat = new ColumnPositionMappingStrategy<AccountEBPImpl>(); strat.setType(AccountEBPImpl.class); @@ -384,7 +363,7 @@ account.setLabel(label); // if is thirdPart account - if (!StringUtils.isNumeric(accountNumber)){ + if (!StringUtils.isNumeric(accountNumber)) { Account masterAccount = null; int i = 1; while (masterAccount == null) { @@ -399,15 +378,14 @@ result.append(_("lima-business.import.accountadded", accountNumber, label)); } // else if account and exclude account start with 0 (fix from error on EBP) - else if (!accountNumber.startsWith("0")){ + else if (!accountNumber.startsWith("0")) { // if account is class account : 1, 2, 3, 4, 5, 6, 7,… int nbCharAccountNumber = accountNumber.length(); if (nbCharAccountNumber == 1) { accountService.createAccountWithTransaction(null, - account, topiaContext); + account, topiaContext); result.append(_("lima-business.import.accountadded", accountNumber, label)); - } - else { + } else { Account masterAccount = null; int i = 1; while (masterAccount == null) { @@ -420,16 +398,14 @@ accountService.createAccountWithTransaction( masterAccount, account, topiaContext); result.append(_("lima-business.import.accountadded", accountNumber, label)); - } + } } } } - } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); - } catch (IOException eeeIO) { - log.error("Can't read string", eeeIO); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); } finally { - doFinally(topiaContext, log); + doFinally(topiaContext); } return result.toString(); @@ -449,37 +425,34 @@ // ################ IMPORT ################ - /** - * Remote methode to call all entities import from UI - */ + /** Remote methode to call all entities import from UI */ @Override public String importAllAsCSV(String datas) throws LimaException { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); Map<String, AccountImport> accounts = new TreeMap<String, AccountImport>(); LinkedHashMap<String, ArrayList<FinancialStatementImport>> financialStatements = - new LinkedHashMap<String, ArrayList<FinancialStatementImport>>(); - - LinkedHashMap<String, ArrayList<VatStatementImport>> vatStatements = - new LinkedHashMap<String, ArrayList<VatStatementImport>>(); + new LinkedHashMap<String, ArrayList<FinancialStatementImport>>(); + LinkedHashMap<String, ArrayList<VatStatementImport>> vatStatements = + new LinkedHashMap<String, ArrayList<VatStatementImport>>(); + List<FiscalPeriod> fiscalPeriods = new ArrayList<FiscalPeriod>(); List<ClosedPeriodicEntryBookImport> closedPeriodicEntryBooks = - new ArrayList<ClosedPeriodicEntryBookImport>(); + new ArrayList<ClosedPeriodicEntryBookImport>(); Map<Integer, FinancialTransactionImport> financialTransactions = - new HashMap<Integer, FinancialTransactionImport>(); + new HashMap<Integer, FinancialTransactionImport>(); Map<Integer, List<EntryImport>> entries = - new HashMap<Integer, List<EntryImport>>(); + new HashMap<Integer, List<EntryImport>>(); - TopiaContext topiaContext = null; + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - String[] nextLine = new String[1]; + String[] nextLine; CSVReader csvReader = new CSVReader(new StringReader(datas), ';'); while ((nextLine = csvReader.readNext()) != null) { @@ -487,40 +460,40 @@ .valueOfLabel(nextLine[0]); if (importExportEntityEnum != null) { switch (importExportEntityEnum) { - case ACCOUNT: - result.append(importAccountsChartsCSV(nextLine, accounts, - topiaContext)); - break; - case ENTRYBOOK: - result.append(importEntryBooksChartCSV(nextLine, - topiaContext)); - break; - case FINANCIALSTATEMENT: - result.append(importFinancialsStatementChartCSV(nextLine, - financialStatements, topiaContext)); - break; - case VATSTATEMENT: - result.append(importVatStatementChartCSV(nextLine, - vatStatements, topiaContext)); - break; - case FISCALPERIOD: - result.append(importFiscalPeriodCSV(nextLine, - fiscalPeriods, topiaContext)); - break; - case CLOSEDPERIODICENTRYBOOK: - importClosedPeriodicEntryBookCSV(nextLine, - closedPeriodicEntryBooks, topiaContext); - break; - case FINANCIALTRANSACTION: - importFinancialTransactionsCSV(nextLine, - financialTransactions, topiaContext); - break; - case ENTRY: - importEntriesCSV(nextLine, entries, topiaContext); - break; - case IDENTITY: - importIdentity(nextLine, topiaContext); - break; + case ACCOUNT: + result.append(importAccountsChartsCSV(nextLine, accounts, + topiaContext)); + break; + case ENTRYBOOK: + result.append(importEntryBooksChartCSV(nextLine, + topiaContext)); + break; + case FINANCIALSTATEMENT: + result.append(importFinancialsStatementChartCSV(nextLine, + financialStatements, topiaContext)); + break; + case VATSTATEMENT: + result.append(importVatStatementChartCSV(nextLine, + vatStatements, topiaContext)); + break; + case FISCALPERIOD: + result.append(importFiscalPeriodCSV(nextLine, + fiscalPeriods, topiaContext)); + break; + case CLOSEDPERIODICENTRYBOOK: + importClosedPeriodicEntryBookCSV(nextLine, + closedPeriodicEntryBooks, topiaContext); + break; + case FINANCIALTRANSACTION: + importFinancialTransactionsCSV(nextLine, + financialTransactions, topiaContext); + break; + case ENTRY: + importEntriesCSV(nextLine, entries, topiaContext); + break; + case IDENTITY: + importIdentity(nextLine, topiaContext); + break; } } } @@ -529,28 +502,26 @@ result.append(createAccounts(accounts, topiaContext)); // create financialStatements result.append(createFinancialStatements(financialStatements, - topiaContext)); + topiaContext)); // create vatStatements result.append(createVatStatements(vatStatements, - topiaContext)); + topiaContext)); // create fiscalperiod Collections.sort(fiscalPeriods, new FiscalPeriodComparator()); result.append(createFiscalPeriod(fiscalPeriods, topiaContext)); // update closedperiodicentrybooks result.append(updateClosedPeriodicEntryBooks(closedPeriodicEntryBooks, - topiaContext)); + topiaContext)); // create financialtransaction and entries result.append(createFinancialTransactionsAndEntries( financialTransactions, entries, topiaContext)); commitTransaction(topiaContext); - } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); - } catch (IOException eeeIO) { - log.error("Can't create new CSV Reader", eeeIO); + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); } finally { - doFinally(topiaContext, log); + doFinally(topiaContext); } return result.toString(); } @@ -560,8 +531,9 @@ * This methode let import just on type of entity */ @Override - public String importAsCSV(String datas, ImportExportEntityEnum importExportEntityEnum) throws LimaException { - StringBuffer result = new StringBuffer(); + public String importAsCSV(String datas, + ImportExportEntityEnum importExportEntityEnum) throws LimaException { + StringBuilder result = new StringBuilder(); // FinancialStatements LinkedHashMap<String, ArrayList<FinancialStatementImport>> financialStatements = null; @@ -569,136 +541,140 @@ Map<String, AccountImport> accounts = null; // VatStatement LinkedHashMap<String, ArrayList<VatStatementImport>> vatStatements = null; - + switch (importExportEntityEnum) { - case ACCOUNT: - accounts = new TreeMap<String, AccountImport>(); - break; - case FINANCIALSTATEMENT: - financialStatements = new LinkedHashMap<String, ArrayList<FinancialStatementImport>>(); - break; - case VATSTATEMENT: - vatStatements = new LinkedHashMap<String, ArrayList<VatStatementImport>>(); - break; + case ACCOUNT: + accounts = new TreeMap<String, AccountImport>(); + break; + case FINANCIALSTATEMENT: + financialStatements = new LinkedHashMap<String, ArrayList<FinancialStatementImport>>(); + break; + case VATSTATEMENT: + vatStatements = new LinkedHashMap<String, ArrayList<VatStatementImport>>(); + break; } - - TopiaContext topiaContext = null; + + TopiaContext topiaContext = beginTransaction(rootContext); try { - topiaContext = beginTransaction(); - String[] nextLine = new String[1]; + String[] nextLine; CSVReader csvReader = new CSVReader(new StringReader(datas), ';'); while ((nextLine = csvReader.readNext()) != null) { if (ImportExportEntityEnum.valueOfLabel(nextLine[0]) == importExportEntityEnum) { switch (importExportEntityEnum) { - case ENTRYBOOK: - result.append(importEntryBooksChartCSV(nextLine, topiaContext)); - break; - case ACCOUNT: - result.append(importAccountsChartsCSV(nextLine, accounts, - topiaContext)); - break; - case FINANCIALSTATEMENT: - result.append(importFinancialsStatementChartCSV(nextLine, - financialStatements, topiaContext)); - break; - case VATSTATEMENT: - result.append(importVatStatementChartCSV(nextLine, - vatStatements, topiaContext)); - break; + case ENTRYBOOK: + result.append(importEntryBooksChartCSV(nextLine, topiaContext)); + break; + case ACCOUNT: + result.append(importAccountsChartsCSV(nextLine, accounts, + topiaContext)); + break; + case FINANCIALSTATEMENT: + result.append(importFinancialsStatementChartCSV(nextLine, + financialStatements, topiaContext)); + break; + case VATSTATEMENT: + result.append(importVatStatementChartCSV(nextLine, + vatStatements, topiaContext)); + break; } } } //create entity switch (importExportEntityEnum) { - case ACCOUNT: - result.append(createAccounts(accounts, topiaContext)); - break; - case FINANCIALSTATEMENT: - result.append(createFinancialStatements(financialStatements, - topiaContext)); - break; - case VATSTATEMENT: - result.append(createVatStatements(vatStatements, - topiaContext)); - break; + case ACCOUNT: + result.append(createAccounts(accounts, topiaContext)); + break; + case FINANCIALSTATEMENT: + result.append(createFinancialStatements(financialStatements, + topiaContext)); + break; + case VATSTATEMENT: + result.append(createVatStatements(vatStatements, + topiaContext)); + break; } - - } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); - } catch (IOException eeeIO) { - log.error("Can't create new CSV Reader", eeeIO); + + } catch (Exception eeeTE) { + doCatch(topiaContext, eeeTE); } finally { - doFinally(topiaContext, log); + doFinally(topiaContext); } return result.toString(); } - + @Override - public String importAsPDF(String datas, ImportExportEntityEnum importExportEntityEnum, boolean setMode) throws LimaException { + public String importAsPDF(String datas, + ImportExportEntityEnum importExportEntityEnum, + boolean setMode) throws LimaException { - StringBuffer result = new StringBuffer(); - + StringBuilder result = new StringBuilder(); + try { - String path = LimaConfig.getInstance().getReportsDir(); - + String path = LimaConfig.getInstance().getReportsDir().getAbsolutePath(); + String filePathDefault = path + File.separator - + DocumentsEnum.VAT.getFileName() + "_default.pdf"; + + DocumentsEnum.VAT.getFileName() + "_default.pdf"; String filePathStructured = path + File.separator - + DocumentsEnum.VAT.getFileName() + "_structure.pdf"; - - PDDocument doc = null; + + DocumentsEnum.VAT.getFileName() + "_structure.pdf"; + + PDDocument doc; InputStream reportsStream = new FileInputStream(datas); - //DocumentServiceImpl.class.getResourceAsStream("/reports/vat_form_fr.pdf"); + //DocumentServiceImpl.class.getResourceAsStream("/reports/vat_form_fr.pdf"); // load the document doc = PDDocument.load(reportsStream); - + //save default vat document with empty boxes if (setMode) { doc.save(filePathDefault); } - + //search for all PDFBox List<PDField> FieldList = doc.getDocumentCatalog().getAcroForm().getFields(); - + //display inside each box their name for (PDField pdField : FieldList) { - pdField.setValue(pdField.getFullyQualifiedName()); + pdField.setValue(pdField.getFullyQualifiedName()); } - + // save the structured document doc.save(filePathStructured); - + //sets the new pdf url to be used as pdf document edited for reports if (setMode) { LimaConfig.getInstance().setVatPDFUrl(datas); } doc.close(); - } - catch (IOException eee) { + } catch (IOException eee) { log.error("Can't read vat pdf", eee); result.append("Can't read vat pdf"); - } - catch (COSVisitorException eee) { + } catch (COSVisitorException eee) { log.error("Can't save vat pdf", eee); result.append("Can't save vat pdf"); } return result.toString(); } - + // ################ Import entities an put to lists ################ /** * Import and create accounts Structure : TYPE | accountNumber | label * | thirdparty | masterAccountNumber | generalLedgerNumber + * + * @param nextLine + * @param accounts + * @param topiaContext + * @return + * @throws LimaException */ public String importAccountsChartsCSV(String[] nextLine, - Map<String, AccountImport> accounts, TopiaContext topiaContext) + Map<String, AccountImport> accounts, + TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String accountNumber = nextLine[1]; String label = nextLine[2]; String thirdParty = nextLine[3]; @@ -724,7 +700,7 @@ result.append(_("lima-business.import.accountalreadyexist", accountNumber)); } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } @@ -732,11 +708,18 @@ /** * Import and create fiscal period Structure : TYPE | BeginDate | EndDate * | Locked + * + * @param nextLine + * @param fiscalPeriods + * @param topiaContext + * @return + * @throws LimaException */ public String importFiscalPeriodCSV(String[] nextLine, - List<FiscalPeriod> fiscalPeriods, TopiaContext topiaContext) + List<FiscalPeriod> fiscalPeriods, + TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); try { FiscalPeriodDAO fiscalPeriodDAO = LimaCallaoDAOHelper .getFiscalPeriodDAO(topiaContext); @@ -752,22 +735,27 @@ if (fiscalPeriodDAO.findByNaturalId(beginDate, endDate) == null) { fiscalPeriods.add(fiscalPeriod); } else { - result.append(_("lima-business.import.fiscalperiodalreadyexist", beginDate , endDate)); + result.append(_("lima-business.import.fiscalperiodalreadyexist", beginDate, endDate)); } } catch (ParseException eeePE) { - log.error("Can't parse date", eeePE); + log.error("Can't parse date", eeePE); } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } /** * Import and create entrybooks Structure : TYPE | Code | Label | Type + * + * @param nextLine + * @param topiaContext + * @return + * @throws LimaException */ public String importEntryBooksChartCSV(String[] nextLine, - TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + TopiaContext topiaContext) throws LimaException { + StringBuilder result = new StringBuilder(); try { EntryBookDAO entryBookDAO = LimaCallaoDAOHelper @@ -786,18 +774,23 @@ result.append(_("lima-business.import.financialstatementadded", entryBook.getLabel())); } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } - - + + /** * Import and create Letter : TYPE | Code + * + * @param nextLine + * @param topiaContext + * @return + * @throws LimaException */ public String importLetterCSV(String[] nextLine, - TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + TopiaContext topiaContext) throws LimaException { + StringBuilder result = new StringBuilder(); try { LetterDAO letterDAO = LimaCallaoDAOHelper.getLetterDAO(topiaContext); @@ -812,10 +805,10 @@ } else { // create it financialTransactionService.createLetter(letter); - result.append(_("lima-business.import.letteradded",code)); + result.append(_("lima-business.import.letteradded", code)); } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } @@ -823,10 +816,15 @@ /** * Import and create closedperiodicentrybook import Structure : TYPE | * BeginDate | EndDate | Locked + * + * @param nextLine + * @param closedPeriodicEntryBooks + * @param topiaContext + * @throws LimaException */ public void importClosedPeriodicEntryBookCSV(String[] nextLine, - List<ClosedPeriodicEntryBookImport> closedPeriodicEntryBooks, - TopiaContext topiaContext) throws LimaException { + List<ClosedPeriodicEntryBookImport> closedPeriodicEntryBooks, + TopiaContext topiaContext) throws LimaException { String locked = nextLine[1]; String beginDate = nextLine[2]; String endDate = nextLine[3]; @@ -849,12 +847,18 @@ * | accounts | debitAccount | creditAccount | * provisitionDeprecationAccounts | subAmount | headerAmount * | masterFinancialStatement - */ + * + * @param nextLine + * @param financialStatements + * @param topiaContext + * @return + * @throws LimaException + */ public String importFinancialsStatementChartCSV(String[] nextLine, - LinkedHashMap<String, ArrayList<FinancialStatementImport>> financialStatements, - TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + LinkedHashMap<String, ArrayList<FinancialStatementImport>> financialStatements, + TopiaContext topiaContext) throws LimaException { + StringBuilder result = new StringBuilder(); String label = nextLine[1]; String header = nextLine[2]; @@ -889,10 +893,9 @@ financialStatementImport.setWay(financialStatementWay); // put it in hashlinkedlist - if (financialStatements.containsKey(label)){ + if (financialStatements.containsKey(label)) { financialStatements.get(label).add(financialStatementImport); - } - else { + } else { List<FinancialStatementImport> list = new ArrayList<FinancialStatementImport>(); list.add(financialStatementImport); financialStatements.put(label, (ArrayList<FinancialStatementImport>) list); @@ -901,23 +904,29 @@ result.append(_("lima-business.import.financialstatementalreadyexist", label)); } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } - - + + /** * Import and create vatstatement Structure : TYPE | boxName | label * | header | accounts | masterVatStatement - */ + * + * @param nextLine + * @param vatStatements + * @param topiaContext + * @return + * @throws LimaException + */ public String importVatStatementChartCSV(String[] nextLine, - LinkedHashMap<String, ArrayList<VatStatementImport>> vatStatements, - TopiaContext topiaContext) throws LimaException { - - StringBuffer result = new StringBuffer(); + Map<String, ArrayList<VatStatementImport>> vatStatements, + TopiaContext topiaContext) throws LimaException { + StringBuilder result = new StringBuilder(); + String boxName = nextLine[1]; String label = nextLine[2]; String header = nextLine[3]; @@ -940,7 +949,7 @@ vatStatementImport.setMasterVatStatement(masterVatStatement); // put it in hashlinkedlist - if (vatStatements.containsKey(label)){ + if (vatStatements.containsKey(label)) { vatStatements.get(label).add(vatStatementImport); } else { List<VatStatementImport> list = new ArrayList<VatStatementImport>(); @@ -951,20 +960,25 @@ result.append(_("lima-business.import.vatstatementalreadyexist", label)); } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } - + /** * Import and create financialtransactions Structure : TYPE | NumTransac | * TransactionDate | AmountDebit | AmountCredit | FinancialPeriod BeginDate * | FinancialPeriod EndDate | EntryBook Code + * + * @param nextLine + * @param financialTransactions + * @param topiaContext + * @throws LimaException */ public void importFinancialTransactionsCSV(String[] nextLine, - Map<Integer, FinancialTransactionImport> financialTransactions, - TopiaContext topiaContext) throws LimaException { + Map<Integer, FinancialTransactionImport> financialTransactions, + TopiaContext topiaContext) throws LimaException { int num = new Integer(nextLine[1]); FinancialTransactionImport financialTransactionImport = new FinancialTransactionImportImpl(); financialTransactionImport.setDate(nextLine[2]); @@ -982,10 +996,15 @@ * Amount | Debit | Lettering | Detail | Voucher | Position * | FinancialTransaction Date | FinancialTransaction EntryBookCode | * FinancialTransaction AmountDebit | FinancialTransaction AmountCredit + * + * @param nextLine + * @param entries + * @param topiaContext + * @throws LimaException */ public void importEntriesCSV(String[] nextLine, - Map<Integer, List<EntryImport>> entries, TopiaContext topiaContext) - throws LimaException { + Map<Integer, List<EntryImport>> entries, + TopiaContext topiaContext) throws LimaException { int num = new Integer(nextLine[1]); EntryImport entryImport = new EntryImportImpl(); @@ -1010,9 +1029,9 @@ // ################ CREATE ENTITY IN DB FOR IMPORT ################ - public String createFinancialStatements(LinkedHashMap<String, ArrayList<FinancialStatementImport>> financialStatements, - TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + public String createFinancialStatements(Map<String, ArrayList<FinancialStatementImport>> financialStatements, + TopiaContext topiaContext) throws LimaException { + StringBuilder result = new StringBuilder(); try { FinancialStatementDAO financialStatementDAO = LimaCallaoDAOHelper @@ -1020,84 +1039,84 @@ while (financialStatements.size() > 0) { for (Iterator<ArrayList<FinancialStatementImport>> itr = financialStatements - .values().iterator(); itr.hasNext();) { + .values().iterator(); itr.hasNext(); ) { List<FinancialStatementImport> financialStatementImports = - itr.next(); - - for (Iterator<FinancialStatementImport> itr2 = financialStatementImports.iterator(); itr2.hasNext();) { + itr.next(); + + for (Iterator<FinancialStatementImport> itr2 = financialStatementImports.iterator(); itr2.hasNext(); ) { FinancialStatementImport financialStatementImport = - itr2.next(); + itr2.next(); String masterFinancialStatementLabel = financialStatementImport .getMasterFinancialStatement(); FinancialStatement masterFinancialStatement = financialStatementDAO .findByLabel(masterFinancialStatementLabel); if (masterFinancialStatementLabel.equals("") - || masterFinancialStatement != null) { + || masterFinancialStatement != null) { // create it FinancialStatement financialStatement = new FinancialStatementImpl(); financialStatement.setLabel(financialStatementImport - .getLabel()); + .getLabel()); financialStatement.setHeader(Boolean - .parseBoolean(financialStatementImport - .getHeader())); + .parseBoolean(financialStatementImport + .getHeader())); financialStatement.setAccounts(financialStatementImport - .getAccounts()); + .getAccounts()); financialStatement .setDebitAccounts(financialStatementImport - .getDebitAccounts()); + .getDebitAccounts()); financialStatement .setCreditAccounts(financialStatementImport - .getCreditAccounts()); + .getCreditAccounts()); financialStatement .setProvisionDeprecationAccounts(financialStatementImport - .getProvisionDeprecationAccounts()); + .getProvisionDeprecationAccounts()); financialStatement.setSubAmount(Boolean - .parseBoolean(financialStatementImport - .getSubAmount())); + .parseBoolean(financialStatementImport + .getSubAmount())); financialStatement.setHeaderAmount(Boolean - .parseBoolean(financialStatementImport - .getHeaderAmount())); + .parseBoolean(financialStatementImport + .getHeaderAmount())); String financialStatementWay = financialStatementImport.getWay(); - if (!financialStatementWay.equals("")){ + if (!financialStatementWay.equals("")) { FinancialStatementWayEnum financialStatementWayEnum = - FinancialStatementWayEnum.valueOf(financialStatementWay); + FinancialStatementWayEnum.valueOf(financialStatementWay); financialStatement.setWay(financialStatementWayEnum); } - + financialStatementService .createFinancialStatementWithTransaction( masterFinancialStatement, financialStatement, topiaContext); result.append(_("lima-business.import.financialstatementadded", - financialStatementImport.getLabel())); - + financialStatementImport.getLabel())); + itr2.remove(); } else if (!financialStatements .containsKey(masterFinancialStatementLabel)) { result.append(_("lima-business.import.financialstatementalnomaster", - financialStatementImport.getLabel(), - masterFinancialStatementLabel)); - itr2.remove(); + financialStatementImport.getLabel(), + masterFinancialStatementLabel)); + itr2.remove(); } } - if (financialStatementImports.isEmpty()){ + if (financialStatementImports.isEmpty()) { itr.remove(); } } } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } - - public String createVatStatements(LinkedHashMap<String, ArrayList<VatStatementImport>> vatStatements, - TopiaContext topiaContext) throws LimaException { - - StringBuffer result = new StringBuffer(); + + public String createVatStatements(Map<String, ArrayList<VatStatementImport>> vatStatements, + TopiaContext topiaContext) throws LimaException { + + StringBuilder result = new StringBuilder(); try { VatStatementDAO vatStatementDAO = LimaCallaoDAOHelper @@ -1105,31 +1124,31 @@ while (vatStatements.size() > 0) { for (Iterator<ArrayList<VatStatementImport>> itr = vatStatements - .values().iterator(); itr.hasNext();) { + .values().iterator(); itr.hasNext(); ) { List<VatStatementImport> vatStatementImports = - itr.next(); - - for (Iterator<VatStatementImport> itr2 = vatStatementImports.iterator(); itr2.hasNext();) { + itr.next(); + + for (Iterator<VatStatementImport> itr2 = vatStatementImports.iterator(); itr2.hasNext(); ) { VatStatementImport vatStatementImport = - itr2.next(); + itr2.next(); String masterVatStatementLabel = vatStatementImport .getMasterVatStatement(); VatStatement masterVatStatement = vatStatementDAO .findByLabel(masterVatStatementLabel); if (masterVatStatementLabel.equals("") - || masterVatStatement != null) { + || masterVatStatement != null) { // create it VatStatement vatStatement = new VatStatementImpl(); vatStatement.setBoxName(vatStatementImport - .getBoxName()); + .getBoxName()); vatStatement.setLabel(vatStatementImport - .getLabel()); + .getLabel()); vatStatement.setAccounts(vatStatementImport - .getAccounts()); + .getAccounts()); vatStatement.setHeader(Boolean - .parseBoolean(vatStatementImport - .getHeader())); + .parseBoolean(vatStatementImport + .getHeader())); vatStatement.setAmount(BigDecimal.ZERO); vatStatementService .createVatStatementWithTransaction( @@ -1137,39 +1156,39 @@ vatStatement, topiaContext); result.append(_("lima-business.import.vatstatementadded", - vatStatementImport.getLabel())); - + vatStatementImport.getLabel())); + itr2.remove(); } else if (!vatStatements .containsKey(masterVatStatementLabel)) { result.append(_("lima-business.import.vatstatementalnomaster", - vatStatementImport.getLabel(), - masterVatStatementLabel)); - itr2.remove(); + vatStatementImport.getLabel(), + masterVatStatementLabel)); + itr2.remove(); } } - if (vatStatementImports.isEmpty()){ + if (vatStatementImports.isEmpty()) { itr.remove(); } } } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } public String createFiscalPeriod(List<FiscalPeriod> fiscalPeriods, - TopiaContext topiaContext) { - StringBuffer result = new StringBuffer(); + TopiaContext topiaContext) { + StringBuilder result = new StringBuilder(); for (FiscalPeriod fiscalPeriod : fiscalPeriods) { // create fiscalPeriod try { fiscalPeriodService.createFiscalPeriodWithTransaction( fiscalPeriod, topiaContext); result.append(_("lima-business.import.fiscalperiodadded", - fiscalPeriod.getBeginDate(), - fiscalPeriod.getEndDate())); + fiscalPeriod.getBeginDate(), + fiscalPeriod.getEndDate())); } catch (LimaException eee) { result.append(_("lima-business.common.failed", eee.getMessage())); } @@ -1177,11 +1196,17 @@ return result.toString(); } - + /** * Dynamic letter creation used by CSV and EBP Import + * + * @param letterCode + * @param topiaContext + * @return + * @throws LimaException */ - public Letter createLetter(String letterCode, TopiaContext topiaContext) throws LimaException{ + public Letter createLetter(String letterCode, + TopiaContext topiaContext) throws LimaException { Letter letter = null; try { LetterDAO letterDAO = LimaCallaoDAOHelper.getLetterDAO(topiaContext); @@ -1193,14 +1218,14 @@ financialTransactionService.createLetter(letter); } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return letter; } - + public String createAccounts(Map<String, AccountImport> accounts, - TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + TopiaContext topiaContext) throws LimaException { + StringBuilder result = new StringBuilder(); try { AccountDAO accountDAO = LimaCallaoDAOHelper @@ -1208,7 +1233,7 @@ while (accounts.size() > 0) { for (Iterator<AccountImport> itr = accounts.values().iterator(); itr - .hasNext();) { + .hasNext(); ) { AccountImport accountImport = itr.next(); String masterAccountNumber = accountImport .getMasterAccount(); @@ -1219,13 +1244,13 @@ Account generalLedger = accountDAO .findByAccountNumber(generalLedgerNumber); - if ((masterAccountNumber.equals("") && generalLedgerNumber - .equals("")) - || masterAccount != null || generalLedger != null) { + if (masterAccountNumber.equals("") && generalLedgerNumber + .equals("") + || masterAccount != null || generalLedger != null) { // create it Account account = new AccountImpl(); account.setAccountNumber(accountImport - .getAccountNumber()); + .getAccountNumber()); account.setLabel(accountImport.getLabel()); account.setThirdParty(accountImport.getThirdParty()); @@ -1237,20 +1262,20 @@ masterAccount, account, topiaContext); } result.append(_("lima-business.import.accountadded", - accountImport.getAccountNumber(), - accountImport.getLabel())); + accountImport.getAccountNumber(), + accountImport.getLabel())); itr.remove(); } else if (!accounts.containsKey(masterAccountNumber) - && !accounts.containsKey(generalLedgerNumber)) { + && !accounts.containsKey(generalLedgerNumber)) { result.append(_("lima-business.import.accountnomaster", - accountImport.getAccountNumber(), - masterAccountNumber)); + accountImport.getAccountNumber(), + masterAccountNumber)); itr.remove(); } } } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } return result.toString(); } @@ -1258,7 +1283,7 @@ public String updateClosedPeriodicEntryBooks( List<ClosedPeriodicEntryBookImport> closedPeriodicEntryBooks, TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); try { FinancialPeriodDAO financialPeriodDAO = LimaCallaoDAOHelper @@ -1271,33 +1296,33 @@ // update closedPeriodicEntryBook Date beginDateFinancialPeriod = SDATEFORMAT .parse(closedPeriodicEntryBookImport - .getBeginDateFinancialPeriod()); + .getBeginDateFinancialPeriod()); Date endDateFinancialPeriod = SDATEFORMAT .parse(closedPeriodicEntryBookImport - .getEndDateFinancialPeriod()); + .getEndDateFinancialPeriod()); FinancialPeriod financialPeriod = financialPeriodDAO .findByNaturalId(beginDateFinancialPeriod, - endDateFinancialPeriod); + endDateFinancialPeriod); String codeEntryBook = closedPeriodicEntryBookImport .getCodeEntryBook(); EntryBook entryBook = entryBookDAO.findByCode(codeEntryBook); ClosedPeriodicEntryBook closedPeriodicEntryBook = closedPeriodicEntryBookDAO .findByEntryBookAndFinancialPeriod(entryBook, - financialPeriod); + financialPeriod); try { financialPeriodService .blockClosedPeriodicEntryBookWithTransaction( closedPeriodicEntryBook, topiaContext); result.append(_("lima-business.import.closedperiodicentrybookupdated", - beginDateFinancialPeriod, endDateFinancialPeriod, codeEntryBook)); + beginDateFinancialPeriod, endDateFinancialPeriod, codeEntryBook)); } catch (LimaException eee) { result.append(_("lima-business.common.failed", eee)); } } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } catch (ParseException eeePE) { - log.error("Can't parse date", eeePE); + log.error("Can't parse date", eeePE); } return result.toString(); } @@ -1306,7 +1331,7 @@ Map<Integer, FinancialTransactionImport> financialTransactions, Map<Integer, List<EntryImport>> entries, TopiaContext topiaContext) throws LimaException { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); try { EntryBookDAO entryBookDAO = LimaCallaoDAOHelper .getEntryBookDAO(topiaContext); @@ -1333,7 +1358,7 @@ financialTransactionImport.getAmountCredit())); EntryBook entryBook = entryBookDAO .findByCode(financialTransactionImport - .getCodeEntryBook()); + .getCodeEntryBook()); financialTransaction.setEntryBook(entryBook); FinancialPeriod financialPeriod = financialPeriodDAO @@ -1351,11 +1376,11 @@ entry.setDescription(entryImport.getDescription()); entry.setAmount(new BigDecimal(entryImport.getAmount())); entry.setDebit(Boolean.parseBoolean(entryImport.getDebit())); - + Letter letter = createLetter( entryImport.getLettering(), topiaContext); entry.setLetter(letter); - + entry.setDetail(entryImport.getDetail()); entry.setVoucher(entryImport.getVoucher()); entry.setPosition(entryImport.getPosition()); @@ -1364,16 +1389,16 @@ } } } catch (TopiaException eeeTE) { - doCatch(topiaContext, eeeTE, log); + doCatch(topiaContext, eeeTE); } catch (ParseException eeePE) { - log.error("Can't parse date", eeePE); + log.error("Can't parse date", eeePE); } return result.toString(); } - public String importIdentity(String[] nextLine, TopiaContext topiaContext) - throws LimaException { - StringBuffer result = new StringBuffer(); + public String importIdentity(String[] nextLine, + TopiaContext topiaContext) throws LimaException { + StringBuilder result = new StringBuilder(); Identity identity = new IdentityImpl(); nextLine[0] = ImportExportEntityEnum.IDENTITY.getLabel(); @@ -1396,24 +1421,4 @@ return result.toString(); } - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction" + topiaTransaction); - return topiaTransaction; - } - - protected void commitTransaction(TopiaContext topiaTransaction) - throws TopiaException { - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/OptionsServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/OptionsServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/OptionsServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -22,44 +22,44 @@ * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ -package org.chorem.lima.business.ejb; - -import javax.ejb.Stateless; - -import org.chorem.lima.business.LimaConfig; -import org.chorem.lima.business.ejbinterface.OptionsService; -import org.chorem.lima.business.ejbinterface.OptionsServiceLocal; - -@Stateless -public class OptionsServiceImpl extends AbstractLimaService implements OptionsService, OptionsServiceLocal { - +package org.chorem.lima.business.ejb; + +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.ejbinterface.OptionsService; +import org.chorem.lima.business.ejbinterface.OptionsServiceLocal; + +import javax.ejb.Stateless; + +@Stateless +public class OptionsServiceImpl extends AbstractLimaService implements OptionsService, OptionsServiceLocal { + protected String scale; - - protected String vatPDFUrl; - - public OptionsServiceImpl() { + + protected String vatPDFUrl; + + public OptionsServiceImpl() { scale = LimaConfig.getInstance().getScale(); - vatPDFUrl = LimaConfig.getInstance().getVatPDFUrl(); - } - - public int getScale() { - if (scale.isEmpty()) { - return 2; - } else { - return Integer.valueOf(scale); - } - } - - public void setScale(String scale) { - LimaConfig.getInstance().setScale(scale); + vatPDFUrl = LimaConfig.getInstance().getVatPDFUrl(); } - + + public int getScale() { + if (scale.isEmpty()) { + return 2; + } else { + return Integer.valueOf(scale); + } + } + + public void setScale(String scale) { + LimaConfig.getInstance().setScale(scale); + } + public String getVatPDFUrl() { return vatPDFUrl; } - + public void setVatPDFUrl(String url) { LimaConfig.getInstance().setVatPDFUrl(url); - } - -} + } + +} Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ReportServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ReportServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ReportServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,24 +25,14 @@ package org.chorem.lima.business.ejb; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.ejb.EJB; -import javax.ejb.Stateless; import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.beans.BalanceTrial; import org.chorem.lima.beans.BalanceTrialImpl; import org.chorem.lima.beans.ReportsDatas; import org.chorem.lima.beans.ReportsDatasImpl; -import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; -import org.chorem.lima.business.ejbinterface.AccountService; -import org.chorem.lima.business.ejbinterface.FinancialPeriodService; +import org.chorem.lima.business.ejbinterface.AccountServiceLocal; +import org.chorem.lima.business.ejbinterface.FinancialPeriodServiceLocal; import org.chorem.lima.business.ejbinterface.ReportService; import org.chorem.lima.business.ejbinterface.ReportServiceLocal; import org.chorem.lima.entity.Account; @@ -55,54 +45,49 @@ import org.chorem.lima.entity.FiscalPeriod; import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; +import javax.ejb.EJB; +import javax.ejb.Stateless; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + @Stateless public class ReportServiceImpl extends AbstractLimaService implements ReportService, ReportServiceLocal { - - private static final Log log = LogFactory.getLog(AccountServiceImpl.class); - + private TopiaContext rootContext; - + @EJB - protected FinancialPeriodService financialPeriodService; - + protected FinancialPeriodServiceLocal financialPeriodService; + @EJB - protected AccountService accountService; - + protected AccountServiceLocal accountService; + public ReportServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } + rootContext = acquireRootContext(); } - + @Override - public ReportsDatas generateAccountsReports(Account account, Boolean thirdPartAccountsMode, Date beginDate, Date endDate) throws LimaException { + public ReportsDatas generateAccountsReports(Account account, + Boolean thirdPartAccountsMode, + Date beginDate, + Date endDate) throws LimaException { ReportsDatas reportsDatas = null; - - TopiaContext topiaTransaction = null; + + TopiaContext topiaTransaction = beginTransaction(rootContext); try { - topiaTransaction = beginTransaction(); - - reportsDatas = - generateAccountReportsWithTransaction(account, thirdPartAccountsMode, beginDate, - endDate, topiaTransaction); + reportsDatas = + generateAccountReportsWithTransaction(account, thirdPartAccountsMode, beginDate, + endDate, topiaTransaction); + } catch (Exception ex) { + doCatch(topiaTransaction, ex); + } finally { + doFinally(topiaTransaction); } - catch (TopiaException ex) { - doCatch(topiaTransaction, ex, log); - } - finally { - doFinally(topiaTransaction, log); - } - + return reportsDatas; } @@ -111,26 +96,30 @@ * List entries for a period and an account * Calculate the amounts * 3 cases: - * - for subaccount - * - for a foldaccounts, contains many accounts - * - for a foldthirdparts accounts + * - for subaccount + * - for a foldaccounts, contains many accounts + * - for a foldthirdparts accounts */ @Override - public ReportsDatas generateAccountReportsWithTransaction (Account account, Boolean thirdPartAccountsMode, Date beginDate, Date endDate, TopiaContext topiaContext) throws LimaException{ + public ReportsDatas generateAccountReportsWithTransaction(Account account, + Boolean thirdPartAccountsMode, + Date beginDate, + Date endDate, + TopiaContext topiaContext) throws LimaException { ReportsDatas reportsDatas = new ReportsDatasImpl(); BigDecimal credit = new BigDecimal(0); BigDecimal debit = new BigDecimal(0); BigDecimal solde = new BigDecimal(0); List<Entry> entries = new ArrayList<Entry>(); - if (account != null){ + if (account != null) { //Get allsubaccounts and thirdParts accounts List<Account> accounts = (List<Account>) account.getSubAccounts(); - if (thirdPartAccountsMode){ + if (thirdPartAccountsMode) { List<Account> thirdPartAccount = (List<Account>) account.getSubLedgers(); - if (thirdPartAccount != null){ + if (thirdPartAccount != null) { ReportsDatas subReportsDatas = generateSubAccountReportsWithTransaction(account, - beginDate, endDate, topiaContext); + beginDate, endDate, topiaContext); entries.addAll(subReportsDatas.getListEntry()); debit = debit.add(subReportsDatas.getAmountDebit()); @@ -140,16 +129,16 @@ } // is already subaccount - if (accounts.size() == 0){ + if (accounts.size() == 0) { reportsDatas = generateSubAccountReportsWithTransaction(account, - beginDate, endDate, topiaContext); + beginDate, endDate, topiaContext); } // else is folder accounts contains many subs and thirds accounts else { - for (Account subAccount : accounts) { + for (Account subAccount : accounts) { ReportsDatas subReportsDatas = - generateAccountReportsWithTransaction(subAccount, true, - beginDate,endDate, topiaContext); + generateAccountReportsWithTransaction(subAccount, true, + beginDate, endDate, topiaContext); debit = debit.add(subReportsDatas.getAmountDebit()); credit = credit.add(subReportsDatas.getAmountCredit()); entries.addAll(subReportsDatas.getListEntry()); @@ -157,8 +146,8 @@ //solde = debit - credit solde = solde.add(debit); solde = solde.subtract(credit); - - if (solde.compareTo(BigDecimal.ZERO) == 1){ + + if (solde.compareTo(BigDecimal.ZERO) == 1) { reportsDatas.setSoldeDebit(true); } solde = solde.abs(); @@ -170,12 +159,24 @@ } return reportsDatas; } - + /** * Query for find entries for accountsreports and balancereports * Just exact and balanced transaction are calculated + * + * @param account + * @param beginDate + * @param endDate + * @param entryDAO + * @param queryAlias + * @return + * @throws LimaException */ - public TopiaQuery createEntryQuery(Account account, Date beginDate, Date endDate, EntryDAO entryDAO, String queryAlias) throws LimaException{ + public TopiaQuery createEntryQuery(Account account, + Date beginDate, + Date endDate, + EntryDAO entryDAO, + String queryAlias) throws LimaException { TopiaQuery query = entryDAO.createQuery(queryAlias); String transactionDateProperty = TopiaQuery.getProperty( @@ -183,389 +184,415 @@ String amountCreditProperty = TopiaQuery.getProperty( Entry.FINANCIAL_TRANSACTION, FinancialTransaction.AMOUNT_CREDIT); String amountDebitProperty = TopiaQuery.getProperty( - Entry.FINANCIAL_TRANSACTION, FinancialTransaction.AMOUNT_DEBIT); + Entry.FINANCIAL_TRANSACTION, FinancialTransaction.AMOUNT_DEBIT); String entryBookProperty = TopiaQuery.getProperty( Entry.FINANCIAL_TRANSACTION, FinancialTransaction.ENTRY_BOOK); - + query - .addWhere(amountCreditProperty+" = "+amountDebitProperty) - .addWhere(transactionDateProperty+" BETWEEN :beginDate AND :endDate") - .addNotNull(entryBookProperty) - .addParam("beginDate", beginDate) - .addParam("endDate", endDate) - .addEquals(Entry.ACCOUNT, account); - + .addWhere(amountCreditProperty + " = " + amountDebitProperty) + .addWhere(transactionDateProperty + " BETWEEN :beginDate AND :endDate") + .addNotNull(entryBookProperty) + .addParam("beginDate", beginDate) + .addParam("endDate", endDate) + .addEquals(Entry.ACCOUNT, account); + return query; } - + /** * Get list entries * Calculate all credit, debit and solde amounts for the accounts reports + * + * @param account + * @param beginDate + * @param endDate + * @param topiaContext + * @return + * @throws LimaException */ - protected ReportsDatas generateSubAccountReportsWithTransaction(Account account, Date beginDate, Date endDate, TopiaContext topiaContext) throws LimaException { + protected ReportsDatas generateSubAccountReportsWithTransaction(Account account, + Date beginDate, + Date endDate, + TopiaContext topiaContext) throws LimaException { ReportsDatas reportsDatas = new ReportsDatasImpl(); BigDecimal credit = new BigDecimal(0); BigDecimal debit = new BigDecimal(0); BigDecimal solde = new BigDecimal(0); - - List<Object[]> results = new ArrayList<Object[]>(); + + List<Object[]> results; String queryAlias = "E"; - if (beginDate != null && endDate != null){ + if (beginDate != null && endDate != null) { try { EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); TopiaQuery entriesQuery = - createEntryQuery(account, beginDate, endDate, entryDAO, queryAlias); + createEntryQuery(account, beginDate, endDate, entryDAO, queryAlias); //IMPORTANT : LOADING ENTRIES AND IS COLUMN FOR NO LAZY EXCEPTION String loadEntryBookProperty = - TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, - FinancialTransaction.ENTRY_BOOK); + TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, + FinancialTransaction.ENTRY_BOOK); entriesQuery.addLoad(Entry.ACCOUNT, Entry.FINANCIAL_TRANSACTION, Entry.LETTER) - .addLoad(loadEntryBookProperty); - reportsDatas.setListEntry(entryDAO.findAllByQuery(entriesQuery)); + .addLoad(loadEntryBookProperty); + reportsDatas.setListEntry(entryDAO.findAllByQuery(entriesQuery)); TopiaQuery amountsQuery = - createEntryQuery(account, beginDate, endDate, entryDAO, queryAlias); - amountsQuery.setSelect("E."+Entry.DEBIT, "SUM(E."+Entry.AMOUNT+")"); - amountsQuery.addGroup("E."+Entry.DEBIT); + createEntryQuery(account, beginDate, endDate, entryDAO, queryAlias); + amountsQuery.setSelect("E." + Entry.DEBIT, "SUM(E." + Entry.AMOUNT + ")"); + amountsQuery.addGroup("E." + Entry.DEBIT); results = amountsQuery.execute(topiaContext); int nbAmount = results.size(); - if(nbAmount==2){ + if (nbAmount == 2) { debit = (BigDecimal) results.get(0)[1]; - credit = (BigDecimal)results.get(1)[1]; + credit = (BigDecimal) results.get(1)[1]; } - if (nbAmount==1){ - if ((Boolean)results.get(0)[0]){ + if (nbAmount == 1) { + if ((Boolean) results.get(0)[0]) { debit = (BigDecimal) results.get(0)[1]; + } else { + credit = (BigDecimal) results.get(0)[1]; } - else { - credit = (BigDecimal)results.get(0)[1]; - } } - + // set the amounts and solde //solde = debit - credit solde = solde.add(debit); solde = solde.subtract(credit); - - if (solde.compareTo(BigDecimal.ZERO) == 1){ + + if (solde.compareTo(BigDecimal.ZERO) == 1) { reportsDatas.setSoldeDebit(true); } solde = solde.abs(); - + reportsDatas.setAmountCredit(credit); reportsDatas.setAmountDebit(debit); reportsDatas.setAmountSolde(solde); //commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } } - + return reportsDatas; } - + /** * Calculate all credit, debit and solde amounts for the balance - * + * <p/> * Get all entries if true */ - public ReportsDatas generateSubAccountBalanceWithTransaction(Account account, Date beginDate, Date endDate, Boolean getEntries, TopiaContext topiaContext) throws LimaException { + public ReportsDatas generateSubAccountBalanceWithTransaction(Account account, + Date beginDate, + Date endDate, + Boolean getEntries, + TopiaContext topiaContext) throws LimaException { ReportsDatas reportsDatas = new ReportsDatasImpl(); BigDecimal credit = new BigDecimal(0); BigDecimal debit = new BigDecimal(0); BigDecimal solde = new BigDecimal(0); - - - List<Object[]> results = new ArrayList<Object[]>(); + + + List<Object[]> results; String queryAlias = "E"; - if (beginDate != null && endDate != null){ + if (beginDate != null && endDate != null) { try { - EntryDAO entryDAO= LimaCallaoDAOHelper.getEntryDAO(topiaContext); - - if (getEntries){ + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); + + if (getEntries) { TopiaQuery entriesQuery = - createEntryQuery(account, beginDate, endDate, entryDAO, queryAlias); + createEntryQuery(account, beginDate, endDate, entryDAO, queryAlias); //IMPORTANT : LOADING ENTRIES AND IS COLUMN FOR NO LAZY EXCEPTION entriesQuery.addLoad(Entry.FINANCIAL_TRANSACTION); String loadEntryBookProperty = - TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, - FinancialTransaction.ENTRY_BOOK); + TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, + FinancialTransaction.ENTRY_BOOK); entriesQuery.addLoad(loadEntryBookProperty); - reportsDatas.setListEntry(entryDAO.findAllByQuery(entriesQuery)); + reportsDatas.setListEntry(entryDAO.findAllByQuery(entriesQuery)); } TopiaQuery amountsQuery = - createEntryQuery(account, beginDate, endDate, entryDAO, queryAlias); - amountsQuery.setSelect("E."+Entry.DEBIT, "SUM(E."+Entry.AMOUNT+")"); - amountsQuery.addGroup("E."+Entry.DEBIT); + createEntryQuery(account, beginDate, endDate, entryDAO, queryAlias); + amountsQuery.setSelect("E." + Entry.DEBIT, "SUM(E." + Entry.AMOUNT + ")"); + amountsQuery.addGroup("E." + Entry.DEBIT); results = amountsQuery.execute(topiaContext); int nbAmount = results.size(); - if(nbAmount==2){ - debit = (BigDecimal)results.get(0)[1]; - credit = (BigDecimal)results.get(1)[1]; + if (nbAmount == 2) { + debit = (BigDecimal) results.get(0)[1]; + credit = (BigDecimal) results.get(1)[1]; } - if (nbAmount==1){ - if ((Boolean)results.get(0)[0]){ - debit = (BigDecimal)results.get(0)[1]; + if (nbAmount == 1) { + if ((Boolean) results.get(0)[0]) { + debit = (BigDecimal) results.get(0)[1]; + } else { + credit = (BigDecimal) results.get(0)[1]; } - else { - credit = (BigDecimal)results.get(0)[1]; - } } - + // set the amounts and solde //solde = debit - credit solde = solde.add(debit); solde = solde.subtract(credit); - - if (solde.compareTo(BigDecimal.ZERO) == 1){ + + if (solde.compareTo(BigDecimal.ZERO) == 1) { reportsDatas.setSoldeDebit(true); - + } solde = solde.abs(); - + reportsDatas.setAmountCredit(credit); reportsDatas.setAmountDebit(debit); reportsDatas.setAmountSolde(solde); //commitTransaction(topiaContext); + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } } - + return reportsDatas; } - + /** * Get all entry from an entrybook and a begin-end dates order by financial transaction date - * + * <p/> * Calculate the amounts and the solde - * + * <p/> * Just balanced transaction are calculated - * */ @Override - public ReportsDatas generateEntryBooksReports(EntryBook entryBook, Date beginDate, Date endDate) throws LimaException { + public ReportsDatas generateEntryBooksReports(EntryBook entryBook, + Date beginDate, + Date endDate) throws LimaException { ReportsDatas reportsDatas = new ReportsDatasImpl(); BigDecimal credit = new BigDecimal(0); BigDecimal debit = new BigDecimal(0); BigDecimal solde = new BigDecimal(0); - - List<Object[]> results = new ArrayList<Object[]>(); - if (entryBook != null && beginDate != null && endDate != null){ + + List<Object[]> results; + if (entryBook != null && beginDate != null && endDate != null) { // Get all entries with a topia query - TopiaContext topiaTransaction = null; + TopiaContext topiaTransaction = beginTransaction(rootContext); try { - topiaTransaction = beginTransaction(); - EntryDAO entryDAO= LimaCallaoDAOHelper.getEntryDAO(topiaTransaction); + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaTransaction); TopiaQuery entriesQuery = createEntryBookReportsQuery( entryBook, beginDate, endDate, entryDAO, "E"); //IMPORTANT : LOADING ENTRIES AND IS COLUMN FOR NO LAZY EXCEPTION entriesQuery.addLoad(Entry.ACCOUNT, Entry.FINANCIAL_TRANSACTION, Entry.LETTER); String orderDateProperty = - TopiaQuery.getProperty("E", Entry.FINANCIAL_TRANSACTION, FinancialTransaction.TRANSACTION_DATE); + TopiaQuery.getProperty("E", Entry.FINANCIAL_TRANSACTION, FinancialTransaction.TRANSACTION_DATE); String orderIdProperty = - TopiaQuery.getProperty("E", Entry.FINANCIAL_TRANSACTION, FinancialTransaction.TOPIA_ID); + TopiaQuery.getProperty("E", Entry.FINANCIAL_TRANSACTION, FinancialTransaction.TOPIA_ID); entriesQuery.addOrder(orderDateProperty) - .addOrder(orderIdProperty); - reportsDatas.setListEntry(entryDAO.findAllByQuery(entriesQuery)); - + .addOrder(orderIdProperty); + reportsDatas.setListEntry(entryDAO.findAllByQuery(entriesQuery)); + TopiaQuery amountsQuery = - createEntryBookReportsQuery(entryBook, beginDate, endDate, entryDAO, "E"); - amountsQuery.setSelect("E."+Entry.DEBIT, "SUM(E."+Entry.AMOUNT+")"); - amountsQuery.addGroup("E."+Entry.DEBIT); + createEntryBookReportsQuery(entryBook, beginDate, endDate, entryDAO, "E"); + amountsQuery.setSelect("E." + Entry.DEBIT, "SUM(E." + Entry.AMOUNT + ")"); + amountsQuery.addGroup("E." + Entry.DEBIT); results = amountsQuery.execute(topiaTransaction); int nbAmount = results.size(); - if(nbAmount==2){ - debit = (BigDecimal)results.get(0)[1]; - credit = (BigDecimal)results.get(1)[1]; + if (nbAmount == 2) { + debit = (BigDecimal) results.get(0)[1]; + credit = (BigDecimal) results.get(1)[1]; } - if (nbAmount==1){ - if ((Boolean)results.get(0)[0]){ - debit = (BigDecimal)results.get(0)[1]; + if (nbAmount == 1) { + if ((Boolean) results.get(0)[0]) { + debit = (BigDecimal) results.get(0)[1]; + } else { + credit = (BigDecimal) results.get(0)[1]; } - else { - credit = (BigDecimal)results.get(0)[1]; - } } - + // set the amounts and solde //solde = debit - credit; solde = solde.add(debit); solde = solde.subtract(credit); - if (solde.compareTo(BigDecimal.ZERO) == 1){ + if (solde.compareTo(BigDecimal.ZERO) == 1) { reportsDatas.setSoldeDebit(true); } solde = solde.abs(); - + reportsDatas.setAmountCredit(credit); reportsDatas.setAmountDebit(debit); reportsDatas.setAmountSolde(solde); //commitTransaction(topiaTransaction); + } catch (Exception ex) { + doCatch(topiaTransaction, ex); + } finally { + doFinally(topiaTransaction); } - catch (TopiaException ex) { - doCatch(topiaTransaction, ex, log); - } - finally { - doFinally(topiaTransaction, log); - } } - + return reportsDatas; } /** * Query for find entries for accountsreports and balancereports * Just balanced transaction are calculated + * + * @param entryBook + * @param beginDate + * @param endDate + * @param entryDAO + * @param queryAlias + * @return + * @throws LimaException */ - public TopiaQuery createEntryBookReportsQuery(EntryBook entryBook, Date beginDate, Date endDate, EntryDAO entryDAO, String queryAlias) throws LimaException{ + public TopiaQuery createEntryBookReportsQuery(EntryBook entryBook, + Date beginDate, + Date endDate, + EntryDAO entryDAO, + String queryAlias) throws LimaException { TopiaQuery query = entryDAO.createQuery(queryAlias); String transactionDateProperty = - TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, - FinancialTransaction.TRANSACTION_DATE); + TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, + FinancialTransaction.TRANSACTION_DATE); String amountCreditProperty = - TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, - FinancialTransaction.AMOUNT_CREDIT); + TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, + FinancialTransaction.AMOUNT_CREDIT); String amountDebitProperty = - TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, - FinancialTransaction.AMOUNT_DEBIT); + TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, + FinancialTransaction.AMOUNT_DEBIT); String entryBookProperty = - TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, - FinancialTransaction.ENTRY_BOOK); + TopiaQuery.getProperty(Entry.FINANCIAL_TRANSACTION, + FinancialTransaction.ENTRY_BOOK); query - .addWhere(amountCreditProperty+" = "+amountDebitProperty) - .addEquals(entryBookProperty, entryBook) - .addWhere(transactionDateProperty+" BETWEEN :beginDate AND :endDate") - .addParam("beginDate", beginDate) - .addParam("endDate", endDate); - + .addWhere(amountCreditProperty + " = " + amountDebitProperty) + .addEquals(entryBookProperty, entryBook) + .addWhere(transactionDateProperty + " BETWEEN :beginDate AND :endDate") + .addParam("beginDate", beginDate) + .addParam("endDate", endDate); + return query; } - - /** + + /** * Get balance trial - * + * <p/> * Calculate the amounts and the solde for all subaccounts - * + * <p/> * Can have string selectedAccounts in params for account filter - * + * <p/> * Boolean Param GetEntries is for get entries in datasreports or not : - * - GetEntries = false for generate balance - * - GetEntries = true for generate ledger + * - GetEntries = false for generate balance + * - GetEntries = true for generate ledger */ @Override - public BalanceTrial generateBalanceTrial(Date beginDate, Date endDate, String selectedAccounts, Boolean getEntries, Boolean movementedFilter) throws LimaException { + public BalanceTrial generateBalanceTrial(Date beginDate, + Date endDate, + String selectedAccounts, + Boolean getEntries, + Boolean movementedFilter) throws LimaException { BalanceTrial balanceTrial = new BalanceTrialImpl(); balanceTrial.setReportsDatas(new ArrayList<ReportsDatas>()); BigDecimal credit = new BigDecimal(0); BigDecimal debit = new BigDecimal(0); BigDecimal solde = new BigDecimal(0); - TopiaContext topiaTransaction = null; + TopiaContext topiaTransaction = beginTransaction(rootContext); try { - topiaTransaction = beginTransaction(); - + AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(topiaTransaction); + LimaCallaoDAOHelper.getAccountDAO(topiaTransaction); //for each account create a balance sheet with a ReportsDatas - List<Account> accounts =null; - + List<Account> accounts; + //Remove Spaces String result = StringUtils.deleteWhitespace(selectedAccounts); //if no filter account - if (result == null || result.equals("")){ + if (result == null || result.equals("")) { accounts = accountDAO.findAll(); } //build list account from selectedAccounts - else{ - accounts = accountDAO.stringToListAccounts( + else { + accounts = accountDAO.stringToListAccounts( result, false); } for (Account account : accounts) { ReportsDatas reportsDatas = - generateSubAccountBalanceWithTransaction(account, beginDate, - endDate, getEntries, topiaTransaction); + generateSubAccountBalanceWithTransaction(account, beginDate, + endDate, getEntries, topiaTransaction); reportsDatas.setAccount(account); BigDecimal amount = reportsDatas.getAmountSolde(); - if (amount == null){ + if (amount == null) { amount = new BigDecimal(0); } - if (movementedFilter){ + if (movementedFilter) { if (reportsDatas.getAmountCredit() != BigDecimal.ZERO - || reportsDatas.getAmountDebit() != BigDecimal.ZERO) { + || reportsDatas.getAmountDebit() != BigDecimal.ZERO) { // add balance sheet to balance trial balanceTrial.addReportsDatas(reportsDatas); } - } - else { + } else { // add balance sheet to balance trial balanceTrial.addReportsDatas(reportsDatas); } if (reportsDatas.getSoldeDebit()) { debit = debit.add(amount); - } - else { + } else { credit = credit.add(amount); } - } + } // set the amounts and solde //solde = debit - credit; solde = solde.add(debit); solde = solde.subtract(credit); - if (solde.compareTo(BigDecimal.ZERO) == 1){ + if (solde.compareTo(BigDecimal.ZERO) == 1) { balanceTrial.setSoldeDebit(true); } solde = solde.abs(); balanceTrial.setAmountCredit(credit); balanceTrial.setAmountDebit(debit); balanceTrial.setAmountSolde(solde); + } catch (Exception ex) { + doCatch(topiaTransaction, ex); + } finally { + doFinally(topiaTransaction); } - catch (TopiaException ex) { - doCatch(topiaTransaction, ex, log); - } - finally { - doFinally(topiaTransaction, log); - } - + return balanceTrial; } - - - /** + + + /** * Get Ledger - * + * <p/> * Calculate the amounts and the solde for all subaccounts * Get all entries */ @Override - public BalanceTrial generateLedger(Date beginDate, Date endDate, String selectedAccounts, Boolean movementedFilter) throws LimaException { - return generateBalanceTrial(beginDate, endDate, selectedAccounts, true, movementedFilter); + public BalanceTrial generateLedger(Date beginDate, + Date endDate, + String selectedAccounts, + Boolean movementedFilter) throws LimaException { + return generateBalanceTrial(beginDate, + endDate, + selectedAccounts, + true, + movementedFilter + ); } - + /** * Generate VAT - * - * @param FiscalPeriod + * + * @param fiscalPeriod * @throws LimaException, TopiaException */ @Override - public List<Object> generateVat(FiscalPeriod fiscalPeriod) throws LimaException, TopiaException { + public List<Object> generateVat(FiscalPeriod fiscalPeriod) throws LimaException { List<Object> list = new ArrayList<Object>(); if (fiscalPeriod != null) { - TopiaContext topiaTransaction = null; + TopiaContext topiaTransaction = beginTransaction(rootContext); try { - topiaTransaction = beginTransaction(); + //lists all accounts AccountDAO accountDAO = - LimaCallaoDAOHelper.getAccountDAO(topiaTransaction); - List<Account> accountsList = null; + LimaCallaoDAOHelper.getAccountDAO(topiaTransaction); + List<Account> accountsList; //gets all financial periods from the fiscal period List<FinancialPeriod> financialPeriod = financialPeriodService.getFinancialPeriods( fiscalPeriod.getBeginDate(), fiscalPeriod.getEndDate()); @@ -573,42 +600,20 @@ list.add(fp); accountsList = accountDAO.findAll(); for (Account account : accountsList) { - //VAT accounts start only with number 44 + //VAT accounts start only with number 44 if (account.getAccountNumber().startsWith("44")) { list.add(generateBalanceTrial(fp.getBeginDate(), - fp.getEndDate(), account.getAccountNumber(), - true, false)); + fp.getEndDate(), account.getAccountNumber(), + true, false)); } } } + } catch (Exception eee) { + doCatch(topiaTransaction, eee); + } finally { + doFinally(topiaTransaction); } - catch(LimaException eee) { - System.out.println(eee); - } } return list; } - - - protected TopiaContext beginTransaction() throws TopiaException { - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction"+topiaTransaction); - return topiaTransaction; - } - - - protected void commitTransaction(TopiaContext topiaTransaction) throws TopiaException { - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - } - } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/VatStatementServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/VatStatementServiceImpl.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/VatStatementServiceImpl.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -24,18 +24,7 @@ */ package org.chorem.lima.business.ejb; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.StringTokenizer; - -import javax.ejb.EJB; -import javax.ejb.Stateless; - import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.chorem.lima.beans.Amounts; import org.chorem.lima.beans.AmountsImpl; import org.chorem.lima.beans.ReportsDatas; @@ -43,7 +32,6 @@ import org.chorem.lima.beans.VatStatementAmountsImpl; import org.chorem.lima.beans.VatStatementDatas; import org.chorem.lima.beans.VatStatementDatasImpl; -import org.chorem.lima.business.LimaConfig; import org.chorem.lima.business.LimaException; import org.chorem.lima.business.ejbinterface.ReportServiceLocal; import org.chorem.lima.business.ejbinterface.VatStatementService; @@ -55,57 +43,53 @@ import org.chorem.lima.entity.VatStatementDAO; import org.chorem.lima.entity.VatStatementImpl; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.framework.TopiaQuery; import org.nuiton.topia.framework.TopiaQuery.Op; +import javax.ejb.EJB; +import javax.ejb.Stateless; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.StringTokenizer; + /** * Permet d'implémenter le plan de la déclaration de TVA - * @author vsalaun * + * @author vsalaun */ @Stateless public class VatStatementServiceImpl extends AbstractLimaService implements VatStatementService, VatStatementServiceLocal { - - private static final Log log = - LogFactory.getLog(VatStatementServiceImpl.class); private TopiaContext rootContext; - + @EJB private ReportServiceLocal reportServiceLocal; public VatStatementServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } + rootContext = acquireRootContext(); } - - + + @Override - public void createVatStatementWithTransaction( - VatStatement masterVatStatement, VatStatement vatStatement, - TopiaContext topiaContext) throws LimaException { - + public void createVatStatementWithTransaction(VatStatement masterVatStatement, + VatStatement vatStatement, + TopiaContext topiaContext) throws LimaException { + try { - VatStatementDAO vatStatementDAO = + VatStatementDAO vatStatementDAO = LimaCallaoDAOHelper.getVatStatementDAO(topiaContext); - + vatStatementDAO.create(vatStatement); - + VatStatement mastervatStatementUpdate = null; if (masterVatStatement != null) { mastervatStatementUpdate = vatStatementDAO.findByLabel(masterVatStatement.getLabel()); } - + // check if parent account exist; if (mastervatStatementUpdate != null) { mastervatStatementUpdate.addSubVatStatements(vatStatement); @@ -113,120 +97,113 @@ } commitTransaction(topiaContext); - + + } catch (TopiaException ex) { + doCatch(topiaContext, ex); } - catch (TopiaException ex) { - doCatch(topiaContext, ex, log); - } - + } - - + + @Override - public void createVatStatement(VatStatement masterVatStatement, VatStatement vatStatement) throws LimaException { - - TopiaContext transaction = null; + public void createVatStatement(VatStatement masterVatStatement, + VatStatement vatStatement) throws LimaException { + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - createVatStatementWithTransaction(masterVatStatement, vatStatement, transaction); + createVatStatementWithTransaction(masterVatStatement, + vatStatement, + transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (Exception ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - + } - - + + @Override public List<VatStatement> getAllVatStatements() throws LimaException { - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); List<VatStatement> vatStatements = null; try { - transaction = beginTransaction(); VatStatementDAO vatStatementDAO = - LimaCallaoDAOHelper.getVatStatementDAO(transaction); + LimaCallaoDAOHelper.getVatStatementDAO(transaction); vatStatements = vatStatementDAO.findAll(); - } catch (TopiaException ex) { - doCatch(transaction, ex, log); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - finally { - doFinally(transaction, log); - } return vatStatements; - + } - - + + @Override public List<VatStatement> getAllChildrenVatStatement( VatStatement vatStatement, List<VatStatement> result) throws LimaException { - + List<VatStatement> childVatStatements = - getChildrenVatStatement(vatStatement); - for (VatStatement childVatStatement: childVatStatements) { + getChildrenVatStatement(vatStatement); + for (VatStatement childVatStatement : childVatStatements) { result.add(childVatStatement); getAllChildrenVatStatement(childVatStatement, result); } return result; - + } - - + + @Override public List<VatStatement> getChildrenVatStatement(VatStatement masterVatStatement) throws LimaException { - + List<VatStatement> vatStatements = null; - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); VatStatementDAO vatStatementDAO = - LimaCallaoDAOHelper.getVatStatementDAO(transaction); + LimaCallaoDAOHelper.getVatStatementDAO(transaction); - TopiaQuery query = vatStatementDAO.createQuery(); + TopiaQuery query = vatStatementDAO.createQuery(); query.addEquals("masterVatStatement", masterVatStatement) - .addOrder(VatStatement.TOPIA_CREATE_DATE); - vatStatements = vatStatementDAO.findAllByQuery(query); + .addOrder(VatStatement.TOPIA_CREATE_DATE); + vatStatements = vatStatementDAO.findAllByQuery(query); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } return vatStatements; - + } - + @Override public void updateVatStatement(VatStatement vatStatement) throws LimaException { - - TopiaContext transaction = null; + + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); - // DAO VatStatementDAO vatStatementHeaderDAO = - LimaCallaoDAOHelper.getVatStatementDAO(transaction); + LimaCallaoDAOHelper.getVatStatementDAO(transaction); //update vatStatementHeaderDAO.update(vatStatement); //commit commitTransaction(transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - - public Amounts amountFromAccountList(String accountsNumberList, Date selectedBeginDate, Date selectedEndDate, TopiaContext topiaContext) throws LimaException{ + + public Amounts amountFromAccountList(String accountsNumberList, + Date selectedBeginDate, + Date selectedEndDate, + TopiaContext topiaContext) throws LimaException { Amounts amounts = new AmountsImpl(); BigDecimal debit = new BigDecimal(0); BigDecimal credit = new BigDecimal(0); @@ -243,16 +220,15 @@ BigDecimal creditTemp = new BigDecimal(0); for (Account account : accountsList) { ReportsDatas reportsDatas = reportServiceLocal. - generateAccountReportsWithTransaction(account, true, - selectedBeginDate, selectedEndDate, topiaContext); + generateAccountReportsWithTransaction(account, true, + selectedBeginDate, selectedEndDate, topiaContext); if (reportsDatas.getSoldeDebit()) { debitTemp = debitTemp.add(reportsDatas.getAmountSolde()); - } - else { + } else { creditTemp = creditTemp.add(reportsDatas.getAmountSolde()); } } - if (!substract){ + if (!substract) { debit = debitTemp; credit = creditTemp; } @@ -266,261 +242,262 @@ amounts.setCredit(credit); amounts.setDebit(debit); } catch (TopiaException e) { - doCatch(topiaContext, e, log); + doCatch(topiaContext, e); } return amounts; } - + /** * Gives the list of account numbers from a VatStatement + * * @param vatStatement + * @param topiaContext * @return accountNumbersList * @throws LimaException */ - public String findAccountNumberByVatStatement(VatStatement vatStatement, TopiaContext topiaContext) throws LimaException { - + public String findAccountNumberByVatStatement(VatStatement vatStatement, + TopiaContext topiaContext) throws LimaException { + String accountNumbersList = null; - + try { VatStatementDAO vatStatementDAO = - LimaCallaoDAOHelper.getVatStatementDAO(topiaContext); + LimaCallaoDAOHelper.getVatStatementDAO(topiaContext); TopiaQuery query = vatStatementDAO.createQuery(); - + String labelProperty = - TopiaQuery.getProperty(VatStatement.LABEL); - + TopiaQuery.getProperty(VatStatement.LABEL); + //not to be used causing query exception with ' character //query.addWhere(labelProperty + " " + Op.LIKE + " '%" + // vatStatement.getLabel() + "%'"); - + query.addWhere(labelProperty, Op.LIKE, vatStatement.getLabel()); query.setMaxResults(1); log.debug("query to find account by VAT " + query); - + List<VatStatement> vatStatementsList = vatStatementDAO.findAllByQuery(query); - + if (vatStatementsList.size() > 0) { accountNumbersList = vatStatementsList.get(0).getAccounts(); - } + } + } catch (TopiaException e) { + doCatch(topiaContext, e); } - catch (TopiaException e) { - doCatch(topiaContext, e, log); - } return accountNumbersList; } - + @Override - public VatStatementAmounts vatStatementAmounts(VatStatement vatStatement, Date selectedBeginDate, Date selectedEndDate) throws LimaException, TopiaException { - TopiaContext transaction = null; + public VatStatementAmounts vatStatementAmounts(VatStatement vatStatement, + Date selectedBeginDate, + Date selectedEndDate) throws LimaException { + TopiaContext transaction = beginTransaction(rootContext); VatStatementAmounts vatStatementAmount = new VatStatementAmountsImpl(); - transaction = beginTransaction(); try { - vatStatementAmount = vatStatementAmounts(vatStatement, selectedBeginDate, selectedEndDate, transaction); + vatStatementAmount = vatStatementAmounts(vatStatement, + selectedBeginDate, + selectedEndDate, + transaction); + } catch (Exception e) { + doCatch(transaction, e); + } finally { + doFinally(transaction); } - catch (TopiaException e) { - doCatch(transaction, e, log); - } - finally { - doFinally(transaction, log); - } return vatStatementAmount; } - + @Override - public VatStatementAmounts vatStatementAmounts(VatStatement vatStatement, Date selectedBeginDate, Date selectedEndDate, TopiaContext topiacontext) throws LimaException, TopiaException { + public VatStatementAmounts vatStatementAmounts(VatStatement vatStatement, + Date selectedBeginDate, + Date selectedEndDate, + TopiaContext topiacontext) throws LimaException { VatStatementAmounts vatStatementAmounts = new VatStatementAmountsImpl(); - + BigDecimal debitTemp = new BigDecimal(0); BigDecimal creditTemp = new BigDecimal(0); - + try { - + String accountNumbersList = findAccountNumberByVatStatement(vatStatement, topiacontext); - + AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(topiacontext); List<Account> accountsList = accountDAO.stringToListAccounts(accountNumbersList, false); - + for (Account account : accountsList) { ReportsDatas reportsDatas = reportServiceLocal. - generateAccountReportsWithTransaction(account, true, - selectedBeginDate, selectedEndDate, topiacontext); - if (reportsDatas.getSoldeDebit()){ + generateAccountReportsWithTransaction(account, true, + selectedBeginDate, selectedEndDate, topiacontext); + if (reportsDatas.getSoldeDebit()) { debitTemp = debitTemp.add(reportsDatas.getAmountSolde()); - } - else { + } else { creditTemp = creditTemp.add(reportsDatas.getAmountSolde()); } } + } catch (TopiaException e) { + doCatch(topiacontext, e); } - catch (TopiaException e) { - doCatch(topiacontext, e, log); - } //return debitTemp.subtract(creditTemp).abs(); vatStatementAmounts.setAmount(debitTemp.subtract(creditTemp).abs()); return vatStatementAmounts; - + } - + @Override public VatStatement findVatStatementByString(String label) throws LimaException { - + VatStatement vatStatement = new VatStatementImpl(); - TopiaContext transaction = null; - + TopiaContext transaction = beginTransaction(rootContext); + try { - - transaction = beginTransaction(); - + VatStatementDAO vatStatementDAO = - LimaCallaoDAOHelper.getVatStatementDAO(transaction); + LimaCallaoDAOHelper.getVatStatementDAO(transaction); TopiaQuery query = vatStatementDAO.createQuery(); - + String labelProperty = - TopiaQuery.getProperty(VatStatement.LABEL); - + TopiaQuery.getProperty(VatStatement.LABEL); + //not to be used causing query exception with ' character //query.addWhere(labelProperty + " " + Op.LIKE + " '%" + // vatStatement.getLabel() + "%'"); - + query.addWhere(labelProperty, Op.LIKE, label); query.setMaxResults(1); log.debug("query to find account by VAT " + query); - - List<VatStatement> vatStatementsList = vatStatementDAO.findAllByQuery(query); - + + List<VatStatement> vatStatementsList = + vatStatementDAO.findAllByQuery(query); + if (vatStatementsList.size() > 0) { vatStatement = vatStatementsList.get(0); } + } catch (Exception e) { + doCatch(transaction, e); + } finally { + doFinally(transaction); } - catch (TopiaException e) { - doCatch(transaction, e, log); - } - finally { - doFinally(transaction, log); - } return vatStatement; } - - /** - * remote methode to get list of financial statement - */ + + /** remote methode to get list of financial statement */ public List<VatStatementAmounts> vatStatementReport(Date beginDate, Date endDate) throws LimaException { - TopiaContext transaction = null; List<VatStatementAmounts> result = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); //create list form tree - result = vatStatementReport(null, beginDate, endDate, - new VatStatementDatasImpl(), transaction).getListResult(); + VatStatementDatas vatStatementDatas = vatStatementReport(null, beginDate, endDate, + new VatStatementDatasImpl(), + transaction); + result = vatStatementDatas.getListResult(); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } - return result; + return result; } - + /** * Créé la liste de postes contenant les calculs de comptes - * @throws TopiaException + * + * @throws TopiaException */ - public VatStatementDatas vatStatementReport(VatStatement vatStatement, Date selectedBeginDate, Date selectedEndDate,VatStatementDatas result, TopiaContext topiaContext) throws LimaException, TopiaException { + public VatStatementDatas vatStatementReport(VatStatement vatStatement, + Date selectedBeginDate, + Date selectedEndDate, + VatStatementDatas result, + TopiaContext topiaContext) throws LimaException { List<VatStatement> vatStatements = getChildrenVatStatement(vatStatement); try { BigDecimal amount = new BigDecimal(0); List<VatStatementAmounts> subResult = - new ArrayList<VatStatementAmounts>(); + new ArrayList<VatStatementAmounts>(); for (VatStatement subVatStatement : vatStatements) { VatStatementAmounts vatStatementAmounts = - vatStatementAmounts(subVatStatement, - selectedBeginDate, selectedEndDate, topiaContext); + vatStatementAmounts(subVatStatement, + selectedBeginDate, selectedEndDate, topiaContext); vatStatementAmounts.setLabel(subVatStatement.getLabel()); - if (!subVatStatement.getHeader()){ + if (!subVatStatement.getHeader()) { //on calcul amount = - amount.add(vatStatementAmounts.getAmount()); + amount.add(vatStatementAmounts.getAmount()); subResult.add(vatStatementAmounts); - } - else { + } else { VatStatementDatas vatStatementDatas = - vatStatementReport(subVatStatement, - selectedBeginDate, selectedEndDate, result, topiaContext); + vatStatementReport(subVatStatement, + selectedBeginDate, selectedEndDate, result, topiaContext); amount = amount.add(vatStatementDatas. - getVatStatementAmounts().getAmount()); + getVatStatementAmounts().getAmount()); VatStatementAmounts headerVatStatementAmounts = - vatStatementDatas.getVatStatementAmounts(); + vatStatementDatas.getVatStatementAmounts(); //Si sous-total - if (subVatStatement.getHeader()){ + if (subVatStatement.getHeader()) { VatStatementAmounts header = - new VatStatementAmountsImpl(); + new VatStatementAmountsImpl(); header.setLabel(headerVatStatementAmounts.getLabel()); header.setLevel(headerVatStatementAmounts.getLevel()); header.setHeader(true); //ajoute header subResult.add(header); //ajoute liste - if (vatStatementDatas.getListResult() != null){ + if (vatStatementDatas.getListResult() != null) { subResult.addAll(vatStatementDatas.getListResult()); } //ajoute une ligne vide subResult.add(new VatStatementAmountsImpl()); - + } } } VatStatementAmounts vatStatementAmounts = - new VatStatementAmountsImpl(); + new VatStatementAmountsImpl(); vatStatementAmounts.setAmount(amount); - if (vatStatement != null){ + if (vatStatement != null) { vatStatementAmounts.setLabel(vatStatement.getLabel()); vatStatementAmounts.setHeader(vatStatement.getHeader()); vatStatementAmounts.setLevel(vatStatement.getLevel()); } result.setVatStatementAmounts(vatStatementAmounts); result.setListResult(subResult); + } catch (LimaException eee) { + doCatch(topiaContext, eee); } - catch (LimaException eee) { - doCatch(topiaContext, eee, log); - } return result; } - + @Override public void removeVatStatement(VatStatement vatStatement) throws LimaException { - TopiaContext transaction = null; + TopiaContext transaction = beginTransaction(rootContext); try { - transaction = beginTransaction(); VatStatementDAO vatStatementDAO = - LimaCallaoDAOHelper.getVatStatementDAO(transaction); - - + LimaCallaoDAOHelper.getVatStatementDAO(transaction); + + // remove vatstatement VatStatement vatStatementToDelete = - vatStatementDAO.findByTopiaId( - vatStatement.getTopiaId()); + vatStatementDAO.findByTopiaId( + vatStatement.getTopiaId()); vatStatementDAO.delete(vatStatementToDelete); - + //get all subVatStatement List<VatStatement> vatStatements = - getAllChildrenVatStatement(vatStatement, - new ArrayList<VatStatement>()); - + getAllChildrenVatStatement(vatStatement, + new ArrayList<VatStatement>()); + //if VatStatement have subVatStatement - if (vatStatements.size() > 0){ + if (vatStatements.size() > 0) { for (VatStatement subVatStatement : vatStatements) { VatStatement subVatStatementToDelete = - vatStatementDAO.findByTopiaId( - subVatStatement.getTopiaId()); + vatStatementDAO.findByTopiaId( + subVatStatement.getTopiaId()); vatStatementDAO.delete(subVatStatementToDelete); } } @@ -528,44 +505,17 @@ //commit commitTransaction(transaction); + } catch (Exception ex) { + doCatch(transaction, ex); + } finally { + doFinally(transaction); } - catch (TopiaException ex) { - doCatch(transaction, ex, log); - } - finally { - doFinally(transaction, log); - } } - + @Override public void removeAllVatStatement() throws LimaException { for (VatStatement vatStatement : getChildrenVatStatement(null)) { removeVatStatement(vatStatement); } } - - protected TopiaContext beginTransaction() throws TopiaException { - - // basic check done, make check in database - // TODO move it into JTA - TopiaContext topiaTransaction; - topiaTransaction = rootContext.beginTransaction(); - log.trace("beginTransaction" + topiaTransaction); - return topiaTransaction; - - } - - protected void commitTransaction(TopiaContext topiaTransaction) throws TopiaException { - - try { - topiaTransaction.commitTransaction(); - } catch (TopiaException eee) { - if (log.isErrorEnabled()) { - log.error("Error during commit context", eee); - } - throw eee; - } - - } - } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/AccountService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/AccountService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/AccountService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,52 +25,58 @@ package org.chorem.lima.business.ejbinterface; -import java.util.List; -import javax.ejb.Remote; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.Account; +import javax.ejb.Remote; +import java.util.List; + /** * Account service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Remote public interface AccountService { - - List<Account> getAllAccountByProperty(String propertyName, String value) throws LimaException; - + + List<Account> getAllAccountByProperty(String propertyName, + String value) throws LimaException; + Account getAccountByNumber(String number) throws LimaException; List<Account> getAllAccounts() throws LimaException; - + List<Account> getAllSubAccounts() throws LimaException; - + /** * Create new account. If {@code masterAccount} is not null, {@code account} * is added in {@code masterAccount}'s subAccounts. - * + * * @param masterAccount master account (can be null) - * @param account account + * @param account account * @throws LimaException */ //EJB Remote - void createAccount(Account masterAccount, Account account) throws LimaException; - - void createSubLedger(Account masterAccount, Account account) throws LimaException; - + void createAccount(Account masterAccount, + Account account) throws LimaException; + + void createSubLedger(Account masterAccount, + Account account) throws LimaException; + void updateAccount(Account account) throws LimaException; - + void removeAccount(Account account) throws LimaException; + void removeAllAccount() throws LimaException; - - List<Account> getAllChildrenAccounts(Account masterAccount, List<Account> accounts) throws LimaException; + List<Account> getAllChildrenAccounts(Account masterAccount, + List<Account> accounts) throws LimaException; + //EJB Remote et local List<Account> getChildrenAccounts(Account masterAccount) throws LimaException; } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/AccountServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/AccountServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/AccountServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,25 +25,27 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Local; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.Account; import org.nuiton.topia.TopiaContext; +import javax.ejb.Local; + /** * Account service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Local -public interface AccountServiceLocal extends AccountService{ +public interface AccountServiceLocal extends AccountService { void createAccountWithTransaction(Account masterAccount, Account account, TopiaContext topiaContext) throws LimaException; + void createSubLedgerWithTransaction(Account masterAccount, Account account, TopiaContext topiaContext) throws LimaException; } \ No newline at end of file Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/DocumentService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/DocumentService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/DocumentService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,28 +25,31 @@ package org.chorem.lima.business.ejbinterface; -import java.io.IOException; -import java.util.Date; -import javax.ejb.Remote; - -import org.apache.pdfbox.exceptions.COSVisitorException; import org.chorem.lima.business.LimaException; import org.chorem.lima.business.utils.FormatsEnum; +import javax.ejb.Remote; +import java.util.Date; + /** * Interface to create pdf and html docs + * * @author john - * */ @Remote public interface DocumentService { void createFinancialStatementsDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException; + void createLedgerDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException; + void createEntryBooksDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException; + void createBalanceDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException; + void createGeneralEntryBooksDocuments(Date beginDate, Date endDate, FormatsEnum format) throws LimaException; - void createVatDocuments(Date beginDate, Date endDate, FormatsEnum format, String autocomplete) throws LimaException, IOException, COSVisitorException; + void createVatDocuments(Date beginDate, Date endDate, FormatsEnum format, String autocomplete) throws LimaException; + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/DocumentServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/DocumentServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/DocumentServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -29,11 +29,11 @@ /** * Interface to create pdf and html docs + * * @author john - * */ @Local -public interface DocumentServiceLocal { +public interface DocumentServiceLocal extends DocumentService { } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/EntryBookService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/EntryBookService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/EntryBookService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,31 +25,50 @@ package org.chorem.lima.business.ejbinterface; -import java.util.List; -import javax.ejb.Remote; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.EntryBook; +import javax.ejb.Remote; +import java.util.List; + /** * Entry book service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Remote public interface EntryBookService { + + /** @return all entrybook + * @throws LimaException*/ List<EntryBook> getAllEntryBooks() throws LimaException; - + List<EntryBook> getAllEntryByProperty(String propertyName, String value) throws LimaException; - + void createEntryBook(EntryBook entryBook) throws LimaException; + /** + * Permet de modifier un journal. + * + * @param entryBook journal + * @throws LimaException + */ void updateEntryBook(EntryBook entryBook) throws LimaException; - + + /** + * Permet d'effacer un EntryBook dans la base de données. + * <p/> + * ATTENTION : si un EntryBook est associé avec des entrées, il est alors + * impossible de supprimer celui-ci. + * + * @param entryBook + * @throws LimaException + */ void removeEntryBook(EntryBook entryBook) throws LimaException; } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/EntryBookServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/EntryBookServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/EntryBookServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,26 +25,26 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Local; - import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.EntryBook; import org.nuiton.topia.TopiaContext; +import javax.ejb.Local; + /** * Entry book service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Local public interface EntryBookServiceLocal extends EntryBookService { void createEntryBookWithTransaction(EntryBook entryBook, TopiaContext topiaContext) throws LimaException; - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ExportService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ExportService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ExportService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,60 +25,49 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Remote; import org.chorem.lima.business.LimaException; +import javax.ejb.Remote; + /** * Import export service. - * + * <p/> * Currently import and export as XML. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Remote public interface ExportService { - - + + /** * Get database export as CSV; - * + * * @return export as byte array * @throws LimaException */ String exportAsCSV() throws LimaException; - - /** - * export entrybook chart as CSV. - */ + + /** export entrybook chart as CSV. */ String exportEntryBookChartAsCSV() throws LimaException; - - /** - * export financialstatement chart as CSV. - */ + + /** export financialstatement chart as CSV. */ String exportFinancialStatementChartAsCSV() throws LimaException; - - /** - * export vatstatement chart as CSV - */ + + /** export vatstatement chart as CSV */ String exportVatStatementChartAsCSV() throws LimaException; - - /** - * export accounts chart as CSV. - */ + + /** export accounts chart as CSV. */ String exportAccountsChartAsCSV() throws LimaException; - - /** - * export entries as EBP - */ + + /** export entries as EBP */ String exportEntriesAsEBP() throws LimaException; - - /** - * export accounts as EBP - */ + + /** export accounts as EBP */ String exportAccountsAsEBP() throws LimaException; Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ExportServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ExportServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ExportServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -29,14 +29,14 @@ /** * Import export service. - * + * <p/> * Currently import and export as XML. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Local public interface ExportServiceLocal extends ExportService { Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialPeriodService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialPeriodService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialPeriodService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,41 +25,41 @@ package org.chorem.lima.business.ejbinterface; -import java.util.Date; -import java.util.List; -import javax.ejb.Remote; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.ClosedPeriodicEntryBook; import org.chorem.lima.entity.EntryBook; import org.chorem.lima.entity.FinancialPeriod; +import javax.ejb.Remote; +import java.util.Date; +import java.util.List; + /** * Financial period service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Remote public interface FinancialPeriodService { - + List<FinancialPeriod> getUnblockedFinancialPeriods() throws LimaException; - void createFinancialPeriods(List<FinancialPeriod> financialPeriods) throws LimaException; - - /** Methodes for closedperiodicentrybook */ - - ClosedPeriodicEntryBook getClosedPeriodicEntryBook(EntryBook entryBook, FinancialPeriod financialPeriod) throws LimaException; - + + ClosedPeriodicEntryBook getClosedPeriodicEntryBook(EntryBook entryBook, + FinancialPeriod financialPeriod) throws LimaException; + List<ClosedPeriodicEntryBook> getAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod() throws LimaException; - + void blockClosedPeriodicEntryBook(ClosedPeriodicEntryBook closedPeriodicEntryBook) throws LimaException; - List<FinancialPeriod> getAllFinancialPeriods() throws LimaException; - - List<FinancialPeriod> getFinancialPeriods(Date beginDate, Date endDate) throws LimaException; + List<FinancialPeriod> getAllFinancialPeriods() throws LimaException; + + List<FinancialPeriod> getFinancialPeriods(Date beginDate, + Date endDate) throws LimaException; } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialPeriodServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialPeriodServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialPeriodServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,29 +25,33 @@ package org.chorem.lima.business.ejbinterface; -import java.util.List; -import javax.ejb.Local; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.ClosedPeriodicEntryBook; import org.chorem.lima.entity.FinancialPeriod; import org.nuiton.topia.TopiaContext; +import javax.ejb.Local; +import java.util.List; + /** * Financial period service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Local public interface FinancialPeriodServiceLocal extends FinancialPeriodService { - void createFinancialPeriodsWithTransaction(List<FinancialPeriod> financialPeriods, TopiaContext topiaContext) throws LimaException; - void blockClosedPeriodicEntryBookWithTransaction(ClosedPeriodicEntryBook closedPeriodicEntryBook, TopiaContext topiaContext) throws LimaException; + void createFinancialPeriodsWithTransaction(List<FinancialPeriod> financialPeriods, + TopiaContext topiaContext) throws LimaException; - + void blockClosedPeriodicEntryBookWithTransaction(ClosedPeriodicEntryBook closedPeriodicEntryBook, + TopiaContext topiaContext) throws LimaException; + + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialStatementService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialStatementService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialStatementService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,28 +25,37 @@ package org.chorem.lima.business.ejbinterface; -import java.util.Date; -import java.util.List; -import javax.ejb.Remote; import org.chorem.lima.beans.FinancialStatementAmounts; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.FinancialStatement; +import javax.ejb.Remote; +import java.util.Date; +import java.util.List; + @Remote public interface FinancialStatementService { - - void createFinancialStatement(FinancialStatement masterFinancialStatement, FinancialStatement financialStatement) throws LimaException; + + void createFinancialStatement(FinancialStatement masterFinancialStatement, + FinancialStatement financialStatement) throws LimaException; + void updateFinancialStatement(FinancialStatement financialStatement) throws LimaException; + void removeFinancialStatement(FinancialStatement financialStatement) throws LimaException; + void removeAllFinancialStatement() throws LimaException; - + List<FinancialStatement> getAllFinancialStatements() throws LimaException; + List<FinancialStatement> getChildrenFinancialStatement(FinancialStatement financialStatement) throws LimaException; - List<FinancialStatement> getAllChildrenFinancialStatement(FinancialStatement financialStatement, List<FinancialStatement> financialStatements) throws LimaException; - List<FinancialStatementAmounts> financialStatementReport(Date selectedBeginDate, Date selectedEndDate) throws LimaException; - + List<FinancialStatement> getAllChildrenFinancialStatement(FinancialStatement financialStatement, + List<FinancialStatement> financialStatements) throws LimaException; + + List<FinancialStatementAmounts> financialStatementReport(Date selectedBeginDate, + Date selectedEndDate) throws LimaException; + String checkFinancialStatementChart() throws LimaException; } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialStatementServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialStatementServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialStatementServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,16 +25,18 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Local; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.FinancialStatement; import org.nuiton.topia.TopiaContext; +import javax.ejb.Local; + @Local public interface FinancialStatementServiceLocal extends FinancialStatementService { void createFinancialStatementWithTransaction(FinancialStatement masterFinancialStatement, - FinancialStatement financialStatement, TopiaContext topiaContext) throws LimaException; + FinancialStatement financialStatement, + TopiaContext topiaContext) throws LimaException; - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialTransactionService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialTransactionService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialTransactionService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,9 +25,6 @@ package org.chorem.lima.business.ejbinterface; -import java.util.Date; -import java.util.List; -import javax.ejb.Remote; import org.chorem.lima.beans.FinancialTransactionSearch; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.Entry; @@ -37,78 +34,60 @@ import org.chorem.lima.entity.FiscalPeriod; import org.chorem.lima.entity.Letter; +import javax.ejb.Remote; +import java.util.Date; +import java.util.List; + /** * Transaction service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Remote public interface FinancialTransactionService { - /** - * Find all transaction for an entry book and a financial period. - * - * @param entryBook entry book - * @param period financial period - * @return all transaction for entry book and period - * @throws LimaException - */ - FinancialTransaction createFinancialTransaction(FinancialTransaction financialtransaction) throws LimaException; void updateFinancialTransaction(FinancialTransaction financialtransaction) throws LimaException; - + void removeFinancialTransaction(FinancialTransaction financialtransaction) throws LimaException; - - List<FinancialTransaction> getAllFinancialTransactionsForFinancialPeriod( - FinancialPeriod period) throws LimaException; - - List<FinancialTransaction> getAllFinancialTransactionsFromDateToDate( - Date beginDate, Date endDate) throws LimaException; - - List<FinancialTransaction> getAllFinancialTransactionsForEntryBookAndFinancialPeriod( - EntryBook entryBook, FinancialPeriod period) throws LimaException; - + + List<FinancialTransaction> getAllFinancialTransactionsForFinancialPeriod(FinancialPeriod period) throws LimaException; + + List<FinancialTransaction> getAllFinancialTransactionsFromDateToDate(Date beginDate, + Date endDate) throws LimaException; + + List<FinancialTransaction> getAllFinancialTransactionsForEntryBookAndFinancialPeriod(EntryBook entryBook, + FinancialPeriod period) throws LimaException; + List<FinancialTransaction> getAllInexactFinancialTransactions(FiscalPeriod fiscalPeriod) throws LimaException; + List<FinancialTransaction> getAllFinancialTransactionsBalanced(FiscalPeriod fiscalPeriod) throws LimaException; List<Object> searchFinancialTransaction(FinancialTransactionSearch financialTransactionSearch) throws LimaException; - - - /** - * Methods for create, update and remove the entry - * @param entry - * @throws LimaException - */ - + Entry createEntry(Entry entry) throws LimaException; void updateEntry(Entry entry) throws LimaException; - - void removeEntry(Entry entry) throws LimaException; - - /** - * Methods for create, update and remove the letter - * @param entry - * @throws LimaException - */ - + + void removeEntry(Entry entry) throws LimaException; + Letter getNewLetter() throws LimaException; - + void createLetter(Letter letter) throws LimaException; - + void removeLetter(Letter letter) throws LimaException; - + List<Letter> getAllLetters() throws LimaException; - + void setEntryLetter(Entry entry, Letter letter) throws LimaException; - + void removeEntryLetter(Entry entry) throws LimaException; - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialTransactionServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialTransactionServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FinancialTransactionServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,32 +25,34 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Local; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.Entry; import org.chorem.lima.entity.FinancialTransaction; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; +import javax.ejb.Local; + /** * Transaction service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Local public interface FinancialTransactionServiceLocal extends FinancialTransactionService { - - FinancialTransaction createFinancialTransactionWithTransaction(FinancialTransaction financialtransaction, TopiaContext topiaContext) throws LimaException; - void updateFinancialTransactionWithTransaction(FinancialTransaction financialtransaction, TopiaContext topiaContext) throws LimaException; - - Entry createEntryWithTransaction(Entry entry, TopiaContext topiaContext) throws LimaException, TopiaException; - - - + FinancialTransaction createFinancialTransactionWithTransaction(FinancialTransaction financialtransaction, + TopiaContext topiaContext) throws LimaException; + + void updateFinancialTransactionWithTransaction(FinancialTransaction financialtransaction, + TopiaContext topiaContext) throws LimaException; + + Entry createEntryWithTransaction(Entry entry, TopiaContext topiaContext) throws LimaException; + + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FiscalPeriodService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FiscalPeriodService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FiscalPeriodService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,41 +25,38 @@ package org.chorem.lima.business.ejbinterface; -import java.util.List; -import javax.ejb.Remote; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.EntryBook; import org.chorem.lima.entity.FiscalPeriod; +import javax.ejb.Remote; +import java.util.List; + /** * Fiscal period service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Remote public interface FiscalPeriodService { List<FiscalPeriod> getAllFiscalPeriods() throws LimaException; - + List<FiscalPeriod> getAllBlockedFiscalPeriods() throws LimaException; - + List<FiscalPeriod> getAllUnblockedFiscalPeriods() throws LimaException; - + FiscalPeriod getLastFiscalPeriod() throws LimaException; void createFiscalPeriod(FiscalPeriod fiscalPeriod) throws LimaException; - + void blockFiscalPeriod(FiscalPeriod fiscalPeriod) throws LimaException; - - /** - * Methods for report retained earnings - * @param previousFiscalPeriod, fiscalPeriod, entryBook - * @throws LimaException - */ - - void addRetainedEarnings(FiscalPeriod fiscalPeriod, boolean newyear, EntryBook entryBook) throws LimaException; + + void addRetainedEarnings(FiscalPeriod fiscalPeriod, + boolean newyear, + EntryBook entryBook) throws LimaException; } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FiscalPeriodServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FiscalPeriodServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/FiscalPeriodServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,24 +25,26 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Local; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.FiscalPeriod; import org.nuiton.topia.TopiaContext; +import javax.ejb.Local; + /** * Fiscal period service. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Local public interface FiscalPeriodServiceLocal extends FiscalPeriodService { - void createFiscalPeriodWithTransaction(FiscalPeriod fiscalPeriod, TopiaContext topiaContext) throws LimaException; + void createFiscalPeriodWithTransaction(FiscalPeriod fiscalPeriod, + TopiaContext topiaContext) throws LimaException; - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/HttpServerService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/HttpServerService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/HttpServerService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -31,6 +31,7 @@ public interface HttpServerService { void start(); + int getHttpPort(); - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/HttpServerServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/HttpServerServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/HttpServerServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -28,6 +28,6 @@ import javax.ejb.Local; @Local -public interface HttpServerServiceLocal { +public interface HttpServerServiceLocal extends HttpServerService { } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/IdentityService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/IdentityService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/IdentityService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,15 +25,16 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Remote; - import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.Identity; +import javax.ejb.Remote; + @Remote public interface IdentityService { Identity getIdentity() throws LimaException; + void updateIdentity(Identity identity) throws LimaException; - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/IdentityServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/IdentityServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/IdentityServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,16 +25,18 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Local; - import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.Identity; import org.nuiton.topia.TopiaContext; +import javax.ejb.Local; + @Local -public interface IdentityServiceLocal { +public interface IdentityServiceLocal extends IdentityService { - void updateIdentityWithTransaction(Identity identity, TopiaContext topiaContext) throws LimaException; + void updateIdentityWithTransaction(Identity identity, + TopiaContext topiaContext) throws LimaException; + Identity getIdentityWithTransaction(TopiaContext topiaContext) throws LimaException; - + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ImportService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ImportService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ImportService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,57 +25,62 @@ package org.chorem.lima.business.ejbinterface; -import javax.ejb.Remote; import org.chorem.lima.business.LimaException; import org.chorem.lima.business.utils.ImportExportEntityEnum; +import javax.ejb.Remote; + /** * Import export service. - * + * <p/> * Currently import and export as XML. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Remote public interface ImportService { - + /** * Import data as EBP CSV export. - * - * @param data + * + * @param datas * @throws LimaException */ String importEntriesFromEbp(String datas) throws LimaException; + String importAccountsChartFromEbp(String datas) throws LimaException; - + /** * Import data as Sage Maestria export. - * + * * @param data * @throws LimaException */ void importAsSage(byte[] data) throws LimaException; - + /** * Import data as Ciel Compta export. - * + * * @param data * @throws LimaException */ void importAsCiel(byte[] data) throws LimaException; - + /** * import CSV. * Return result log - */ + */ String importAllAsCSV(String path) throws LimaException; - - String importAsCSV(String datas, ImportExportEntityEnum importExportEntityEnum) throws LimaException; - - String importAsPDF(String datas, ImportExportEntityEnum importExportEntityEnum, boolean saveMode) throws LimaException; + + String importAsCSV(String datas, + ImportExportEntityEnum importExportEntityEnum) throws LimaException; + + String importAsPDF(String datas, + ImportExportEntityEnum importExportEntityEnum, + boolean saveMode) throws LimaException; } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ImportServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ImportServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ImportServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -29,14 +29,14 @@ /** * Import export service. - * + * <p/> * Currently import and export as XML. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Local public interface ImportServiceLocal extends ImportService { Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/OptionsService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/OptionsService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/OptionsService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -1,55 +1,56 @@ -/* - * #%L - * Lima :: business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ +/* + * #%L + * Lima :: business + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2008 - 2011 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ package org.chorem.lima.business.ejbinterface; import javax.ejb.Remote; /** * Service de report des certaines configurations du swing dans business - * + * <p/> * Actuellement : * <ul> - * <li>scale</li> + * <li>scale</li> * </ul> - * + * * @author salaun - * */ @Remote public interface OptionsService { - + /** * Sets the swing scale to the business scale - * @param String: scale + * + * @param scale scale */ void setScale(String scale); - + /** * Gets the business scale - * @return String: scale + * + * @return scale */ int getScale(); Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/OptionsServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/OptionsServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/OptionsServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -22,11 +22,11 @@ * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ -package org.chorem.lima.business.ejbinterface; - -import javax.ejb.Local; - -@Local -public interface OptionsServiceLocal extends OptionsService { - -} +package org.chorem.lima.business.ejbinterface; + +import javax.ejb.Local; + +@Local +public interface OptionsServiceLocal extends OptionsService { + +} Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ReportService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ReportService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ReportService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,10 +25,6 @@ package org.chorem.lima.business.ejbinterface; -import java.util.Date; -import java.util.List; - -import javax.ejb.Remote; import org.chorem.lima.beans.BalanceTrial; import org.chorem.lima.beans.ReportsDatas; import org.chorem.lima.business.LimaException; @@ -36,23 +32,26 @@ import org.chorem.lima.entity.EntryBook; import org.chorem.lima.entity.FiscalPeriod; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; +import javax.ejb.Remote; +import java.util.Date; +import java.util.List; + /** * Service de generation des rapports. - * + * <p/> * Actuellement: * <ul> - * <li>Balance</li> - * <li>Bilan</li> - * <li>TVA</li> + * <li>Balance</li> + * <li>Bilan</li> + * <li>TVA</li> * </ul> - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Remote @@ -60,50 +59,91 @@ /** * Generation du bilan. - * + * * @param fiscalPeriod exercice * @return le bilan * @throws LimaException * BalanceSheet generateBalanceSheet(FiscalPeriod fiscalPeriod) throws LimaException; */ - + /** * Generation de la balance. - * + * + * @param beginDate + * @param endDate + * @param selectedAccounts + * @param getEntries + * @param movementedFilter * @return la balance * @throws LimaException */ - BalanceTrial generateBalanceTrial(Date beginDate, Date endDate, String selectedAccounts, Boolean getEntries, Boolean movementedFilter) throws LimaException; - + BalanceTrial generateBalanceTrial(Date beginDate, + Date endDate, + String selectedAccounts, + Boolean getEntries, + Boolean movementedFilter) throws LimaException; + /** * Generation du grand-livre - * + * + * @param beginDate + * @param endDate + * @param selectedAccounts + * @param movementedFilter * @throws LimaException + * @return */ - BalanceTrial generateLedger(Date beginDate, Date endDate, String selectedAccounts, Boolean movementedFilter) throws LimaException; + BalanceTrial generateLedger(Date beginDate, + Date endDate, + String selectedAccounts, + Boolean movementedFilter) throws LimaException; - + + /** Generation du rapports des comptes + * @param account + * @param thirdPartAccountsMode + * @param beginDate + * @param endDate + * @throws LimaException + * @return*/ + ReportsDatas generateAccountsReports(Account account, + Boolean thirdPartAccountsMode, + Date beginDate, + Date endDate) throws LimaException; + + /** - * Generation du rapports des comptes - */ - ReportsDatas generateAccountsReports(Account account, Boolean thirdPartAccountsMode, Date beginDate, Date endDate) throws LimaException; - - - /** * Calculate all credit, debit and solde amounts for the balance - * + * <p/> * Get all entries if true + * @param account + * @param beginDate + * @param endDate + * @param getEntries + * @param topiaContext + * @return + * @throws LimaException */ - ReportsDatas generateSubAccountBalanceWithTransaction(Account account, Date beginDate, Date endDate, Boolean getEntries, TopiaContext topiaContext) throws LimaException; - - /** - * Generation du rapports des journaux - */ - ReportsDatas generateEntryBooksReports(EntryBook entryBook, Date beginDate, Date endDate) throws LimaException; - - /** - * Generate VAT - */ - List<Object> generateVat(FiscalPeriod fiscalPeriod) throws LimaException, TopiaException; + ReportsDatas generateSubAccountBalanceWithTransaction(Account account, + Date beginDate, + Date endDate, + Boolean getEntries, + TopiaContext topiaContext) throws LimaException; + /** Generation du rapports des journaux + * @param entryBook + * @param beginDate + * @param endDate + * @throws LimaException + * @return*/ + ReportsDatas generateEntryBooksReports(EntryBook entryBook, + Date beginDate, + Date endDate) throws LimaException; + + /** Generate VAT + * @param fiscalPeriod + * @return + * @throws LimaException*/ + List<Object> generateVat(FiscalPeriod fiscalPeriod) throws LimaException; + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ReportServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ReportServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/ReportServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,33 +25,38 @@ package org.chorem.lima.business.ejbinterface; -import java.util.Date; -import javax.ejb.Local; import org.chorem.lima.beans.ReportsDatas; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.Account; import org.nuiton.topia.TopiaContext; +import javax.ejb.Local; +import java.util.Date; + /** * Service de generation des rapports. - * + * <p/> * Actuellement: * <ul> - * <li>Balance</li> - * <li>Bilan</li> + * <li>Balance</li> + * <li>Bilan</li> * </ul> - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Local public interface ReportServiceLocal extends ReportService { - ReportsDatas generateAccountReportsWithTransaction (Account account, Boolean thirdPartAccountsMode, Date beginDate, Date endDate, TopiaContext topiaContext) throws LimaException; - + ReportsDatas generateAccountReportsWithTransaction(Account account, + Boolean thirdPartAccountsMode, + Date beginDate, + Date endDate, + TopiaContext topiaContext) throws LimaException; + } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/VatStatementService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/VatStatementService.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/VatStatementService.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -24,43 +24,40 @@ */ package org.chorem.lima.business.ejbinterface; -import java.util.Date; -import java.util.List; - -import javax.ejb.Remote; - import org.chorem.lima.beans.VatStatementAmounts; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.VatStatement; -import org.nuiton.topia.TopiaException; +import javax.ejb.Remote; +import java.util.Date; +import java.util.List; + @Remote public interface VatStatementService { void createVatStatement(VatStatement masterVatStatement, - VatStatement vatStatement) throws LimaException; + VatStatement vatStatement) throws LimaException; List<VatStatement> getAllVatStatements() throws LimaException; - List<VatStatement> getAllChildrenVatStatement( - VatStatement vatStatement, List<VatStatement> result) - throws LimaException; + List<VatStatement> getAllChildrenVatStatement(VatStatement vatStatement, + List<VatStatement> result) throws LimaException; - List<VatStatement> getChildrenVatStatement(VatStatement masterVatStatement) - throws LimaException; + List<VatStatement> getChildrenVatStatement(VatStatement masterVatStatement) throws LimaException; void updateVatStatement(VatStatement vatStatement) throws LimaException; VatStatementAmounts vatStatementAmounts(VatStatement vatStatement, - Date selectedBeginDate, Date selectedEndDate) throws LimaException, - TopiaException; + Date selectedBeginDate, + Date selectedEndDate) throws LimaException; VatStatement findVatStatementByString(String label) throws LimaException; - - List<VatStatementAmounts> vatStatementReport(Date beginDate, Date endDate) throws LimaException; - + + List<VatStatementAmounts> vatStatementReport(Date beginDate, + Date endDate) throws LimaException; + void removeAllVatStatement() throws LimaException; - + void removeVatStatement(VatStatement vatStatement) throws LimaException; Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/VatStatementServiceLocal.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/VatStatementServiceLocal.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejbinterface/VatStatementServiceLocal.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -24,16 +24,15 @@ */ package org.chorem.lima.business.ejbinterface; -import java.util.Date; -import javax.ejb.Local; - import org.chorem.lima.beans.VatStatementAmounts; import org.chorem.lima.beans.VatStatementDatas; import org.chorem.lima.business.LimaException; import org.chorem.lima.entity.VatStatement; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; +import javax.ejb.Local; +import java.util.Date; + @Local public interface VatStatementServiceLocal extends VatStatementService { @@ -42,11 +41,14 @@ TopiaContext transaction) throws LimaException; public VatStatementAmounts vatStatementAmounts(VatStatement vatStatement, - Date selectedBeginDate, Date selectedEndDate, - TopiaContext topiacontext) throws LimaException, TopiaException; - + Date selectedBeginDate, + Date selectedEndDate, + TopiaContext topiacontext) throws LimaException; + public VatStatementDatas vatStatementReport(VatStatement vatStatement, - Date selectedBeginDate, Date selectedEndDate, VatStatementDatas result, - TopiaContext topiaContext) throws LimaException, TopiaException; + Date selectedBeginDate, + Date selectedEndDate, + VatStatementDatas result, + TopiaContext topiaContext) throws LimaException; } Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/DocumentsEnum.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/DocumentsEnum.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/DocumentsEnum.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -47,11 +47,11 @@ } public String getFileName() { - return this.fileName; + return fileName; } public String getDescription() { - return this.description; + return description; } public static DocumentsEnum valueOfLink(String label){ Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FormatsEnum.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FormatsEnum.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FormatsEnum.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -41,15 +41,15 @@ } public String getExtension() { - return this.extension; + return extension; } public String getMimeType() { - return this.mimeType; + return mimeType; } public String getDescription(){ - return this.description; + return description; } public static FormatsEnum valueOfExtension(String extension){ Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/ImportExportEntityEnum.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/ImportExportEntityEnum.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/ImportExportEntityEnum.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -27,25 +27,32 @@ public enum ImportExportEntityEnum { - ACCOUNT("ACCN"), ENTRYBOOK("ENBK"), FINANCIALSTATEMENT("FNST"), - FISCALPERIOD("FSCP"), CLOSEDPERIODICENTRYBOOK("CPEB"), - FINANCIALTRANSACTION("FTRC"), ENTRY("NTRY"), - VATSTATEMENT("VAT"), IDENTITY("IDNT"), VATPDF("VATPDF"); + ACCOUNT("ACCN"), + ENTRYBOOK("ENBK"), + FINANCIALSTATEMENT("FNST"), + FISCALPERIOD("FSCP"), + CLOSEDPERIODICENTRYBOOK("CPEB"), + FINANCIALTRANSACTION("FTRC"), + ENTRY("NTRY"), + VATSTATEMENT("VAT"), + IDENTITY("IDNT"), + VATPDF("VATPDF"); + private final String label; - - private ImportExportEntityEnum(String label) { + + ImportExportEntityEnum(String label) { this.label = label; } - + public String getLabel() { - return this.label; + return label; } - - public static ImportExportEntityEnum valueOfLabel(String label){ + + public static ImportExportEntityEnum valueOfLabel(String label) { ImportExportEntityEnum value = null; - + for (ImportExportEntityEnum importExportEntityEnum : ImportExportEntityEnum.values()) { - if (label.equals(importExportEntityEnum.label)){ + if (label.equals(importExportEntityEnum.label)) { value = importExportEntityEnum; break; } Modified: trunk/lima-business/src/main/resources/i18n/lima-business_en_GB.properties =================================================================== --- trunk/lima-business/src/main/resources/i18n/lima-business_en_GB.properties 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/resources/i18n/lima-business_en_GB.properties 2011-08-16 14:08:32 UTC (rev 3277) @@ -1,12 +1,13 @@ -= lima-Business.defaultaccountingrules.updateentryerror=Can't update entry \: financialperiod of this entrybook is closed lima-Business.defaultaccountingrules.updatefinancialtransactionnewperioderror=Can't update financialtransaction \: this financialperiod of new entrybook is closed lima-Business.defaultaccountingrules.updatefinancialtransactionperioderror=Can't update financialtransaction \: the new financialperiod of this entrybook is closed lima-Business.defaultaccountingrules.updatenewentryerror=Can't update entry \: financialperiod of this entrybook is closed lima-business.account.accountalreardyexist=An account already exists with this number \: %s +lima-business.common.close.transactionerror=Can't close transaction \: %s +lima-business.common.commit.transactionerror=Can't commit a transaction \: %s lima-business.common.failed=FAILED \: %s \n +lima-business.common.open.transactionerror=Can't open a transaction \: %s lima-business.common.queryerror=Exception during query \: %s -lima-business.common.transactionerror=Can't close transaction \: %s lima-business.defaultaccountingrules.allentrybookclosed=All EntryBook of this financialperiod are closed lima-business.defaultaccountingrules.blockerrorequillibrate=Can't block financialperiod/entrybook contain financialtransaction not equilibrate lima-business.defaultaccountingrules.dateaftererror=The date is after the fiscal period @@ -94,11 +95,13 @@ lima-business.import.vatstatementadded=SUCCESS \: The vatStatement %s is created \n lima-business.import.vatstatementalnomaster=FAILED \: The vatStatement %s has master \: %s which not exist \n lima-business.import.vatstatementalreadyexist=FAILED \: The vatStatement %s already exists \!\n -lima.config.configFileName.description= -lima.config.httpport=HTTP Port -lima.config.i18ndir=i18n directories -lima.config.reportsdir=Reports directories -lima.config.reportvatpdfurl= -lima.config.rulesnationality=Rules Nationality -lima.config.scale=Scale -lima.config.serveraddress=Server Address +lima.config.configFileName.description=Filename of Lima's configuration +lima.config.data.dir.description=Data directory of Lima +lima.config.httpport.description=HTTP Port +lima.config.i18ndir.description=i18n directories +lima.config.reports.dir.description= +lima.config.reportsdir.description=Reports directories +lima.config.reportvatpdfurl.description= +lima.config.rulesnationality.description=Rules Nationality +lima.config.scale.description=Scale +lima.config.serveraddress.description=Server Address Modified: trunk/lima-business/src/main/resources/i18n/lima-business_fr_FR.properties =================================================================== --- trunk/lima-business/src/main/resources/i18n/lima-business_fr_FR.properties 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/resources/i18n/lima-business_fr_FR.properties 2011-08-16 14:08:32 UTC (rev 3277) @@ -4,9 +4,11 @@ lima-Business.defaultaccountingrules.updatefinancialtransactionperioderror=Impossible de mettre à jour la transaction \: la période financière de ce journal est bloquée lima-Business.defaultaccountingrules.updatenewentryerror=Impossible de mettre à jour l'entrée \: la période financière de ce nouveau journal est bloquée lima-business.account.accountalreardyexist=Un compte existe déjà avec ce numéro \: %s +lima-business.common.close.transactionerror=Impossible de fermer la transaction \: %s +lima-business.common.commit.transactionerror=Impossible de commiter transaction \: %s lima-business.common.failed=Échec \: %s \n +lima-business.common.open.transactionerror=Impossible d'ouvrir la transaction \: %s lima-business.common.queryerror=Exception lors de la requête \: %s -lima-business.common.transactionerror=Impossible de fermer la transaction \: %s lima-business.defaultaccountingrules.allentrybookclosed=Tous les journaux de cette période financière sont fermés lima-business.defaultaccountingrules.blockerrorequillibrate=Impossible de bloquer la période financière / le journal, il contient des transactions non équilibrées lima-business.defaultaccountingrules.dateaftererror=La date est antérieure à la période fiscale @@ -94,11 +96,12 @@ lima-business.import.vatstatementadded=Succès \: Plan de TVA %s ajoutée \n lima-business.import.vatstatementalnomaster=u00C9chec \: Le plan %s possède le master \: %s inexsitant \n lima-business.import.vatstatementalreadyexist=u00C9chec \: Le plan %s exist déjà \!\n -lima.config.configFileName.description= -lima.config.httpport=Port HTTP -lima.config.i18ndir=Dossier des i18n -lima.config.reportsdir=Dossier des rapports -lima.config.reportvatpdfurl=Chemin du raport -lima.config.rulesnationality=Règles nationales -lima.config.scale=Précision -lima.config.serveraddress=Addresse serveur +lima.config.configFileName.description=Nom du fichier de configuration de Lima +lima.config.data.dir.description=Répertoire des données de Lima +lima.config.httpport.description=Port HTTP +lima.config.i18n.dir.description=Dossier des i18n +lima.config.reports.dir.description=Dossier des rapports +lima.config.reportvatpdfurl.description=Chemin du raport +lima.config.rulesnationality.description=Règles nationales +lima.config.scale.description=Précision +lima.config.serveraddress.description=Addresse serveur Modified: trunk/lima-business/src/main/resources/lima.properties =================================================================== --- trunk/lima-business/src/main/resources/lima.properties 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/main/resources/lima.properties 2011-08-16 14:08:32 UTC (rev 3277) @@ -22,25 +22,27 @@ # <http://www.gnu.org/licenses/gpl-3.0.html>. # #L% ### +#### tchemit-2011-08-11 : Default values are in the configuration class no need to put it here ... #LIMA Defaults values # main directory -lima.dir=${user.home}/.lima +#lima.dir=${user.home}/.lima # http port for reports -lima.httpport=5462 +#lima.httpport=5462 # server address (optional for server behind proxy) -lima.serveraddress= +#lima.serveraddress= # Local class for accounting rules -lima.rules=org.chorem.lima.business.accountingrules.FranceAccountingRules +#lima.rules=org.chorem.lima.business.accountingrules.FranceAccountingRules # directory for http server -lima.report.dir=${lima.dir}/reports +#lima.report.dir=${lima.dir}/reports # Proprietes par defaut pour une base de donnees de type H2 hibernate.hbm2ddl.auto=update #hibernate.show_sql=true +# tchemit-2011-08-11 Why db configuration is here ? hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.connection.username=sa hibernate.connection.password= hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:file:~/.lima/limadb +hibernate.connection.url=jdbc:h2:file:${lima.data.dir}/limadb #FIXME should be : hibernate.connection.url=jdbc:h2:file:${lima.dir}/limadb \ No newline at end of file Modified: trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,15 +25,8 @@ package org.chorem.lima.business; -import java.util.List; - -import org.chorem.lima.business.ejb.AccountServiceImpl; -import org.chorem.lima.business.ejbinterface.AccountService; -import org.chorem.lima.entity.Account; -import org.chorem.lima.entity.AccountImpl; -import org.junit.Assert; -import org.junit.Test; - +// tchemit-2011-08-11 This test must be redone thinks it does not respect +// See http://chorem.org/issues/428 /** * Tests pour la gestion des comptes dans le plan comptable * @@ -46,214 +39,240 @@ */ public class AccountServiceImplTest extends AbstractLimaTest { - protected AccountService instance = new AccountServiceImpl(); - - /** - * Création d'un compte dans le plan comptable - * @throws LimaException - */ - @Test - public void createAccountTest() throws LimaException { - Account myAccount = new AccountImpl(); - myAccount.setAccountNumber("4"); - myAccount.setLabel("Comptes de tiers"); - instance.createAccount(null, myAccount); - } - - /** - * Création d'un compte dans le plan comptable - * @throws LimaException - */ - @Test(expected=LimaException.class) - public void testCreateAccountWrongNumber() throws LimaException { - Account myAccount = new AccountImpl(); - myAccount.setAccountNumber("42"); - instance.createAccount(null, myAccount); - } - - /** - * Création d'un compte dans le plan comptable - * @throws LimaException - */ - @Test(expected=LimaException.class) - public void testCreateAccountDuplicated() throws LimaException { - Account myAccount = new AccountImpl(); - myAccount.setAccountNumber("1"); - instance.createAccount(null, myAccount); - instance.createAccount(null, myAccount); - } - - /** - * Permet de tester l'ajout des comptes sous format DTO. La grande différence - * entre la création classique, l'applicaion va enregistrer tous les comptes - * enfants. - * @throws LimaException - */ - @Test - public void createAccountDAOTest() throws LimaException { - // Création des comptes - Account account = new AccountImpl(); - account.setAccountNumber("5"); - account.setLabel("COMPTES FINANCIERS"); - instance.createAccount(null, account); - Account accountChild1 = new AccountImpl(); - accountChild1.setAccountNumber("50"); - accountChild1.setLabel("Valeurs mobilières de placement"); - //accountChild1.setMasterAccount(account); - instance.createAccount(account, accountChild1); - - Account accountChild2 = new AccountImpl(); - accountChild2.setAccountNumber("51"); - accountChild2.setLabel("Banques établissements financiers et assimilés"); - //accountChild2.setMasterAccount(account); - instance.createAccount(account, accountChild2); - - Account accountChildChild1 = new AccountImpl(); - accountChildChild1.setAccountNumber("511"); - accountChildChild1.setLabel("Valeurs à l'encaissement"); - //accountChildChild1.setMasterAccount(accountChild2); - instance.createAccount(accountChild2, accountChildChild1); - - Account accountChildChild2 = new AccountImpl(); - accountChildChild2.setAccountNumber("512"); - accountChildChild2.setLabel("Banques"); - //accountChildChild2.setMasterAccount(accountChild2); - instance.createAccount(accountChild2, accountChildChild2); - } - - - /** - * Recherche d'un compte dans le plan comptable à partir d'un numéro de - * compte. - * @throws LimaException - */ - @Test - public void searchAccountTest() throws LimaException { - // On recherche le compte 4 - Comptes de tiers - Account result = instance.getAccountByNumber("4"); - Assert.assertEquals("Comptes de tiers",result.getLabel()); - } - - - /** - * Permet de tester le nombre d'enfants renvoyés appartenant à un père. - * @throws LimaException - */ - @Test - public void searchListAccountTest() throws LimaException { - // On recherche le compte 5 - COMPTES FINANCIERS - Account account = instance.getAccountByNumber("5"); - List<Account> listAccount = instance.getChildrenAccounts(account); - // Il possède les comptes 50 et 51 - Assert.assertEquals(2,listAccount.size()); - } - - - /** - * Permet de tester la méthode recherchant tous les comptes au format DTO. - * @throws LimaException - */ - @Test - public void getAllAccountTest() throws LimaException { - List<Account> listAccount = instance.getAllAccounts(); - Assert.assertEquals(9,listAccount.size()); - } - - - /** - * Permet de tester si un compte est bien effacé. - * @throws LimaException - */ - @Test - public void removeAccountTest() throws LimaException { - Account masterAccount = instance.getAccountByNumber("4"); - // Création de comptes - Account account = new AccountImpl(); - account.setAccountNumber("40"); - account.setLabel("Fournisseurs"); - instance.createAccount(masterAccount, account); - - Account account2 = new AccountImpl(); - account2.setAccountNumber("41"); - account2.setLabel("Usagers"); - instance.createAccount(masterAccount, account2); - - Account account3 = new AccountImpl(); - account3.setAccountNumber("44"); - account3.setLabel("Etat"); - instance.createAccount(masterAccount, account3); - - // On souhaite supprimer le compte 41. Ce compte existe bien. Il ne possède - // pas de fils. La suppression se déroule bien. - instance.removeAccount(account2); - - // On recherche les fils du compte 4 - List<Account> listAccount = instance.getChildrenAccounts(masterAccount); - // Il ne doit en possèder que 2 (au lieu de 3) - Assert.assertEquals(2,listAccount.size()); - } - - - @Test(expected=LimaException.class) - public void removeUnexistedAccountTest() throws LimaException { - // On souhaite supprimer le compte 422, ce dernier n'existe pas. La - // suppression ne peut s'effectuer. - Account account4 = new AccountImpl(); - account4.setAccountNumber("422"); - account4.setLabel("Unsaved account"); - instance.removeAccount(account4); - } - - - /** - * Cette méthode permet de tester la mise à jour d'un compte au format DTO. - * Il suffit d'envoyer un compte DTO avec des ajouts, modifications, et - * suppression. Il est automatiquement mis à jour dans Callao. - * Cette méthode est intéressante, mais demande de la ressource importante. - * Dans ce test, nous utilitons le compte numéro 5. Ce dernier a pour enfants - * 50 et 51, dont 51 a à son tour les comptes enfants 511 et 512. - * Nous ajoutons un compte supplémentaire 53 à 5. Nous modifions une valeur - * sur le compte 5, et supprimons le compte 51 (et ses enfants). - * @throws LimaException - */ - @Test - public void updateTest() throws LimaException { - // On recherche le compte 5 - COMPTES FINANCIERS - Account account = instance.getAccountByNumber("5"); - - // {ETAPE 1} Modification du nom pour le compte 5 - account.setLabel("COMPTES FINANCIERS modifié"); - - // {ETAPE 2} Ajout du compte 53 - Account accountChild = new AccountImpl(); - accountChild.setAccountNumber("53"); - accountChild.setLabel("Caisse"); - accountChild.setMasterAccount(account); - - instance.createAccount(account, accountChild); - - account.addSubAccounts(accountChild); - - // {ETAPE 3} Supprime le compte 51 (ainsi que ses enfants 511 et 512) - Account accountRemove = instance.getAccountByNumber("51"); - - account.removeSubAccounts(accountRemove); - - // Met à jour le compte 5 DTO dans la bdd ainsi que toutes les {ETAPE *} - instance.updateAccount(account); - - // Vérification ETAPE - - // ETAPE 1 - account = instance.getAccountByNumber("5"); - Assert.assertEquals("COMPTES FINANCIERS modifié",account.getLabel()); - // ETAPE 2 - account = instance.getAccountByNumber("53"); - Assert.assertEquals("Caisse",account.getLabel()); - // ETAPE 3 - account = instance.getAccountByNumber("5"); // les comptes fils de 5 - List<Account> listAccount = instance.getChildrenAccounts(account); - // Il doit avoir 50, 51 (de la méthode searchListAccountTest) et 53 - Assert.assertEquals(3,listAccount.size()); - } +// protected AccountService instance; +// +// @BeforeClass +// public static void beforeclass() throws LimaException { +// deleteAccounts(); +// } +// +// @Before +// public void setUp() throws LimaException { +// instance = new AccountServiceImpl(); +// +// // create a account +// Account myAccount = new AccountImpl(); +// myAccount.setAccountNumber("4"); +// myAccount.setLabel("Comptes de tiers"); +// instance.createAccount(null, myAccount); +// } +// +// @After +// public void tearDown() throws LimaException { +// deleteAccounts(); +// } +// +// private static void deleteAccounts() throws LimaException { +// AccountService instance = new AccountServiceImpl(); +// instance.removeAllAccount(); +// } +// +//// /** +//// * Création d'un compte dans le plan comptable +//// * @throws LimaException +//// */ +//// @Test +//// public void createAccountTest() throws LimaException { +//// Account myAccount = new AccountImpl(); +//// myAccount.setAccountNumber("4"); +//// myAccount.setLabel("Comptes de tiers"); +//// instance.createAccount(null, myAccount); +//// } +// +// /** +// * Création d'un compte dans le plan comptable +// * @throws LimaException +// */ +// @Test(expected=LimaException.class) +// public void testCreateAccountWrongNumber() throws LimaException { +// Account myAccount = new AccountImpl(); +// myAccount.setAccountNumber("42"); +// instance.createAccount(null, myAccount); +// } +// +// /** +// * Création d'un compte dans le plan comptable +// * @throws LimaException +// */ +// @Test(expected=LimaException.class) +// public void testCreateAccountDuplicated() throws LimaException { +// Account myAccount = new AccountImpl(); +// myAccount.setAccountNumber("1"); +// instance.createAccount(null, myAccount); +// instance.createAccount(null, myAccount); +// } +// +// /** +// * Permet de tester l'ajout des comptes sous format DTO. La grande différence +// * entre la création classique, l'applicaion va enregistrer tous les comptes +// * enfants. +// * @throws LimaException +// */ +// @Test +// public void createAccountDAOTest() throws LimaException { +// // Création des comptes +// Account account = new AccountImpl(); +// account.setAccountNumber("5"); +// account.setLabel("COMPTES FINANCIERS"); +// instance.createAccount(null, account); +// Account accountChild1 = new AccountImpl(); +// accountChild1.setAccountNumber("50"); +// accountChild1.setLabel("Valeurs mobilières de placement"); +// //accountChild1.setMasterAccount(account); +// instance.createAccount(account, accountChild1); +// +// Account accountChild2 = new AccountImpl(); +// accountChild2.setAccountNumber("51"); +// accountChild2.setLabel("Banques établissements financiers et assimilés"); +// //accountChild2.setMasterAccount(account); +// instance.createAccount(account, accountChild2); +// +// Account accountChildChild1 = new AccountImpl(); +// accountChildChild1.setAccountNumber("511"); +// accountChildChild1.setLabel("Valeurs à l'encaissement"); +// //accountChildChild1.setMasterAccount(accountChild2); +// instance.createAccount(accountChild2, accountChildChild1); +// +// Account accountChildChild2 = new AccountImpl(); +// accountChildChild2.setAccountNumber("512"); +// accountChildChild2.setLabel("Banques"); +// //accountChildChild2.setMasterAccount(accountChild2); +// instance.createAccount(accountChild2, accountChildChild2); +// } +// +// +// /** +// * Recherche d'un compte dans le plan comptable à partir d'un numéro de +// * compte. +// * @throws LimaException +// */ +// @Test +// public void searchAccountTest() throws LimaException { +// // On recherche le compte 4 - Comptes de tiers +// Account result = instance.getAccountByNumber("4"); +// Assert.assertEquals("Comptes de tiers",result.getLabel()); +// } +// +// +// /** +// * Permet de tester le nombre d'enfants renvoyés appartenant à un père. +// * @throws LimaException +// */ +// @Test +// public void searchListAccountTest() throws LimaException { +// // On recherche le compte 5 - COMPTES FINANCIERS +// Account account = instance.getAccountByNumber("5"); +// List<Account> listAccount = instance.getChildrenAccounts(account); +// // Il possède les comptes 50 et 51 +// Assert.assertEquals(2,listAccount.size()); +// } +// +// +// /** +// * Permet de tester la méthode recherchant tous les comptes au format DTO. +// * @throws LimaException +// */ +// @Test +// public void getAllAccountTest() throws LimaException { +// List<Account> listAccount = instance.getAllAccounts(); +// Assert.assertEquals(9,listAccount.size()); +// } +// +// +// /** +// * Permet de tester si un compte est bien effacé. +// * @throws LimaException +// */ +// @Test +// public void removeAccountTest() throws LimaException { +// Account masterAccount = instance.getAccountByNumber("4"); +// // Création de comptes +// Account account = new AccountImpl(); +// account.setAccountNumber("40"); +// account.setLabel("Fournisseurs"); +// instance.createAccount(masterAccount, account); +// +// Account account2 = new AccountImpl(); +// account2.setAccountNumber("41"); +// account2.setLabel("Usagers"); +// instance.createAccount(masterAccount, account2); +// +// Account account3 = new AccountImpl(); +// account3.setAccountNumber("44"); +// account3.setLabel("Etat"); +// instance.createAccount(masterAccount, account3); +// +// // On souhaite supprimer le compte 41. Ce compte existe bien. Il ne possède +// // pas de fils. La suppression se déroule bien. +// instance.removeAccount(account2); +// +// // On recherche les fils du compte 4 +// List<Account> listAccount = instance.getChildrenAccounts(masterAccount); +// // Il ne doit en possèder que 2 (au lieu de 3) +// Assert.assertEquals(2,listAccount.size()); +// } +// +// +// @Test(expected=LimaException.class) +// public void removeUnexistedAccountTest() throws LimaException { +// // On souhaite supprimer le compte 422, ce dernier n'existe pas. La +// // suppression ne peut s'effectuer. +// Account account4 = new AccountImpl(); +// account4.setAccountNumber("422"); +// account4.setLabel("Unsaved account"); +// instance.removeAccount(account4); +// } +// +// +// /** +// * Cette méthode permet de tester la mise à jour d'un compte au format DTO. +// * Il suffit d'envoyer un compte DTO avec des ajouts, modifications, et +// * suppression. Il est automatiquement mis à jour dans Callao. +// * Cette méthode est intéressante, mais demande de la ressource importante. +// * Dans ce test, nous utilitons le compte numéro 5. Ce dernier a pour enfants +// * 50 et 51, dont 51 a à son tour les comptes enfants 511 et 512. +// * Nous ajoutons un compte supplémentaire 53 à 5. Nous modifions une valeur +// * sur le compte 5, et supprimons le compte 51 (et ses enfants). +// * @throws LimaException +// */ +// @Test +// public void updateTest() throws LimaException { +// // On recherche le compte 5 - COMPTES FINANCIERS +// Account account = instance.getAccountByNumber("5"); +// +// // {ETAPE 1} Modification du nom pour le compte 5 +// account.setLabel("COMPTES FINANCIERS modifié"); +// +// // {ETAPE 2} Ajout du compte 53 +// Account accountChild = new AccountImpl(); +// accountChild.setAccountNumber("53"); +// accountChild.setLabel("Caisse"); +// accountChild.setMasterAccount(account); +// +// instance.createAccount(account, accountChild); +// +// account.addSubAccounts(accountChild); +// +// // {ETAPE 3} Supprime le compte 51 (ainsi que ses enfants 511 et 512) +// Account accountRemove = instance.getAccountByNumber("51"); +// +// account.removeSubAccounts(accountRemove); +// +// // Met à jour le compte 5 DTO dans la bdd ainsi que toutes les {ETAPE *} +// instance.updateAccount(account); +// +// // Vérification ETAPE +// +// // ETAPE 1 +// account = instance.getAccountByNumber("5"); +// Assert.assertEquals("COMPTES FINANCIERS modifié",account.getLabel()); +// // ETAPE 2 +// account = instance.getAccountByNumber("53"); +// Assert.assertEquals("Caisse",account.getLabel()); +// // ETAPE 3 +// account = instance.getAccountByNumber("5"); // les comptes fils de 5 +// List<Account> listAccount = instance.getChildrenAccounts(account); +// // Il doit avoir 50, 51 (de la méthode searchListAccountTest) et 53 +// Assert.assertEquals(3,listAccount.size()); +// } } \ No newline at end of file Modified: trunk/lima-callao/pom.xml =================================================================== --- trunk/lima-callao/pom.xml 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-callao/pom.xml 2011-08-16 14:08:32 UTC (rev 3277) @@ -8,7 +8,7 @@ <parent> <groupId>org.chorem</groupId> <artifactId>lima</artifactId> - <version>0.6-SNAPSHOT</version> + <version>0.5.1-SNAPSHOT</version> </parent> <groupId>org.chorem.lima</groupId> Modified: trunk/lima-swing/pom.xml =================================================================== --- trunk/lima-swing/pom.xml 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-swing/pom.xml 2011-08-16 14:08:32 UTC (rev 3277) @@ -9,7 +9,7 @@ <parent> <groupId>org.chorem</groupId> <artifactId>lima</artifactId> - <version>0.6-SNAPSHOT</version> + <version>0.5.1-SNAPSHOT</version> </parent> <groupId>org.chorem.lima</groupId> Modified: trunk/lima-swing/src/main/java/org/chorem/lima/LimaConfig.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/LimaConfig.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-swing/src/main/java/org/chorem/lima/LimaConfig.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,12 +25,14 @@ package org.chorem.lima; +import jaxx.runtime.JAXXUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.chorem.lima.actions.MiscAction; import org.chorem.lima.business.OptionsServiceMonitorable; import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.chorem.lima.service.LimaServiceFactory; +import org.nuiton.topia.TopiaContextFactory; import org.nuiton.util.ApplicationConfig; import org.nuiton.util.ArgumentsParserException; import org.nuiton.util.FileUtil; @@ -44,6 +46,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.util.Date; import java.util.Locale; import java.util.Properties; @@ -101,8 +104,6 @@ */ public LimaConfig() { - super(); - // set defaut option (included configuration file name : important) for (Option o : Option.values()) { setDefaultOption(o.key, o.defaultValue); @@ -143,7 +144,8 @@ log.error("Can't read configuration", ex); } } - instance.setOption("topia.persistence.classes", LimaCallaoDAOHelper.getImplementationClassesAsString()); + instance.setOption(TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES, + LimaCallaoDAOHelper.getImplementationClassesAsString()); } @Override @@ -234,7 +236,9 @@ setOption(Option.SCALE.key, scale); saveForUser(); firePropertyChange("scale", null, scale); - System.out.println("new scale" + scale); + if (log.isInfoEnabled()) { + log.info("new scale" + scale); + } optionsService.setScale(scale); } @@ -334,7 +338,12 @@ boolean result = getOptionAsBoolean(Option.OPENEJB_REMOTEMODE.key); return result; } - + + public File getDataDirectory() { + File result = getOptionAsFile(Option.DATA_DIR.key); + return result; + } + public File getResourcesDirectory() { File result = getOptionAsFile(Option.RESOURCES_DIRECTORY.key); return result; @@ -358,7 +367,7 @@ * Used in ???? */ public void removeJaxxPropertyChangeListener() { - PropertyChangeListener[] toRemove = jaxx.runtime.JAXXUtil.findJaxxPropertyChangeListener(DEFAULT_JAXX_PCS, getPropertyChangeListeners()); + PropertyChangeListener[] toRemove = JAXXUtil.findJaxxPropertyChangeListener(DEFAULT_JAXX_PCS, getPropertyChangeListeners()); if (toRemove == null || toRemove.length == 0) { return; } @@ -382,11 +391,12 @@ * information for jaxx configuration frame ({@link #type}, * {@link #_transient}, {@link #_final}...) */ - public static enum Option implements OptionDef { + public enum Option implements OptionDef { CONFIG_FILE(CONFIG_FILE_NAME, _("lima.config.configFileName.description"), "lima-config.properties", String.class, true, true), - RESOURCES_DIRECTORY("lima.resources.dir", _("lima.config.resourcesdir"), "${lima.dir}/resources-${application.version}", String.class, false, false), - I18N_DIRECTORY("lima.i18n.dir", _("lima.config.i18ndir"), "${lima.resources.dir}/i18n", String.class, false, false), + DATA_DIR("lima.data.dir", _("lima.config.data.dir.description"), "${user.home}/.lima", File.class, false, false), + RESOURCES_DIRECTORY("lima.resources.dir", _("lima.config.resources.dir.description"), "${lima.data.dir}/resources-${application.version}", String.class, false, false), + I18N_DIRECTORY("lima.i18n.dir", _("lima.config.i18n.dir.description"), "${lima.resources.dir}/i18n", String.class, false, false), LOCALE("locale", _("lima.config.locale.description"), "fr_FR", Locale.class, false, false), DECIMAL_SEPARATOR("lima.config.decimalseparator", _("lima.config.decimalseparator.description"), ",", String.class, false, false), SCALE("scale", _("lima.config.scale.description"), "2", Integer.class, false, false), @@ -394,7 +404,7 @@ CURRENCY("currency", _("lima.config.currency.description"), "none", Boolean.class, false, false), FULL_SCREEN("lima.ui.fullscreen", _("lima.config.ui.fullscreen.description"), "false", Boolean.class, false, false), LAUNCH_UI("lima.ui.launchui", _("lima.config.ui.flaunchui.description"), "true", Boolean.class, true, true), - SUPPORT_EMAIL("lima.misc.supportemail", _("lima.misc.supportemail.description"), "", String.class, false, false), + SUPPORT_EMAIL("lima.misc.supportemail", _("lima.misc.supportemail.description"), "support@codelutin.com", String.class, false, false), OPENEJB_REMOTEMODE("lima.openejb.remotemode", _("lima.openejb.remotemode.description"), "false", String.class, false, false), LIMA_HOST_ADDRESS("lima.host.address", _("lima.config.host.adress"), "localhost", String.class, false, false); @@ -405,7 +415,7 @@ public boolean _transient; public boolean _final; - private Option(String key, String description, String defaultValue, + Option(String key, String description, String defaultValue, Class<?> type, boolean _transient, boolean _final) { this.key = key; this.description = description; @@ -560,7 +570,7 @@ OutputStream stream = new FileOutputStream(file); try { - prop.store(stream, "Last saved " + new java.util.Date()); + prop.store(stream, "Last saved " + new Date()); } finally { stream.close(); } Modified: trunk/lima-swing/src/main/java/org/chorem/lima/service/LimaServiceFactory.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/service/LimaServiceFactory.java 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-swing/src/main/java/org/chorem/lima/service/LimaServiceFactory.java 2011-08-16 14:08:32 UTC (rev 3277) @@ -25,17 +25,6 @@ package org.chorem.lima.service; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.util.HashMap; -import java.util.Properties; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; - import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -45,6 +34,17 @@ import org.apache.openejb.loader.SystemInstance; import org.chorem.lima.LimaMain; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + /** * This class is a service factory based on embedded openejb container. */ @@ -55,7 +55,7 @@ /** Single instance. */ private static LimaServiceFactory instance; - protected HashMap<Class, Object> services = new HashMap<Class, Object>(); + protected Map<Class<?>, Object> services = new HashMap<Class<?>, Object>(); /** JNDI context used to look for EJB. */ protected static InitialContext ctx; @@ -119,14 +119,14 @@ public <M> M getService(Class<M> serviceMonitorableClass){ M result = (M) services.get(serviceMonitorableClass); if (result == null) { - Object ejbHome = null; + Object ejbHome; String serviceName = serviceMonitorableClass.getSimpleName().replace("Monitorable", "ImplRemote"); try { ejbHome = ctx.lookup(serviceName); } catch (NamingException eee) { - if (log.isErrorEnabled()) { - log.error("Can't lookup for service : " + serviceName, eee); - } + throw new RuntimeException( + "Can't lookup for service : " + serviceName, eee); + } InvocationHandler handler = new ServiceMonitorableHandler(ejbHome); result = (M) Proxy.newProxyInstance( serviceMonitorableClass.getClassLoader(), new Class[]{serviceMonitorableClass}, handler); Modified: trunk/lima-swing/src/main/resources/i18n/lima-swing_en_GB.properties =================================================================== --- trunk/lima-swing/src/main/resources/i18n/lima-swing_en_GB.properties 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-swing/src/main/resources/i18n/lima-swing_en_GB.properties 2011-08-16 14:08:32 UTC (rev 3277) @@ -1,5 +1,5 @@ = -lima.account.addaccounterror=Can't add account +lima.account.addaccounterror=Can't add account lima.accountsreports.listerror=Can't get entries list lima.action.commandline.help=Show help in console lima.action.fullscreen=Full screen @@ -91,10 +91,13 @@ lima.config.category.other.description=Other configuration properties lima.config.configFileName.description= lima.config.currency.description= +lima.config.data.dir.description= lima.config.decimalseparator.description= lima.config.host.adress=Host adress +lima.config.i18n.dir.description= lima.config.i18ndir=Directory used for i18n files lima.config.locale.description=Localization used by LIMA +lima.config.resources.dir.description= lima.config.resourcesdir=Directory used for Lima resources lima.config.scale.description= lima.config.ui.flaunchui.description= Modified: trunk/lima-swing/src/main/resources/i18n/lima-swing_fr_FR.properties =================================================================== --- trunk/lima-swing/src/main/resources/i18n/lima-swing_fr_FR.properties 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-swing/src/main/resources/i18n/lima-swing_fr_FR.properties 2011-08-16 14:08:32 UTC (rev 3277) @@ -91,10 +91,13 @@ lima.config.category.other.description=Autre propriétés de configuration lima.config.configFileName.description= lima.config.currency.description= +lima.config.data.dir.description= lima.config.decimalseparator.description= lima.config.host.adress=Adresse du serveur distant +lima.config.i18n.dir.description= lima.config.i18ndir=Répertoire utilisée pour stocker les fichiers i18n lima.config.locale.description=Locale utilisée par l'application +lima.config.resources.dir.description= lima.config.resourcesdir=Répertoire utilisée pour stocker les ressources lima.config.scale.description= lima.config.ui.flaunchui.description= Modified: trunk/lima-swing/src/main/resources/lima-config.properties =================================================================== --- trunk/lima-swing/src/main/resources/lima-config.properties 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/lima-swing/src/main/resources/lima-config.properties 2011-08-16 14:08:32 UTC (rev 3277) @@ -31,25 +31,25 @@ application.organisation.name=${project.organization.name} application.organisation.url=${project.organization.url} -lima.misc.supportemail=support@codelutin.com +#lima.misc.supportemail=support@codelutin.com ######################## # LIMA Defaults values ######################## #LIMA Defaults values # main directory -lima.dir=${user.home}/.lima +#lima.dir=\${user.home}/.lima ######################## # Open EJB Configuration ######################## # Embedded mode -lima.openejb.remotemode=false +#lima.openejb.remotemode=false java.naming.factory.initial=org.openejb.client.LocalInitialContextFactory #Lima Accounting Host -lima.host.address=localhost +#lima.host.address=localhost # Remote mode #lima.openejb.remotemode=true Modified: trunk/pom.xml =================================================================== --- trunk/pom.xml 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/pom.xml 2011-08-16 14:08:32 UTC (rev 3277) @@ -15,7 +15,7 @@ <groupId>org.chorem</groupId> <artifactId>lima</artifactId> - <version>0.6-SNAPSHOT</version> + <version>0.5.1-SNAPSHOT</version> <modules> <module>lima-callao</module> Modified: trunk/src/site/site_fr.xml =================================================================== --- trunk/src/site/site_fr.xml 2011-08-11 15:27:18 UTC (rev 3276) +++ trunk/src/site/site_fr.xml 2011-08-16 14:08:32 UTC (rev 3277) @@ -42,7 +42,7 @@ <menu name="Le projet" inherit="top"> <item name="Présentation" href="presentation.html"/> <item name="Fonctionnalités" href="features.html"/> - <item name="Lancer Lima en ligne" href="lima-main/jnlp/launch.jnlp" /> + <item name="Lancer Lima en ligne" href="lima-swing/jnlp/launch.jnlp" /> <item name="Téléchargements" href="http://www.chorem.org/projects/lima/files" /> <item name="Contacts" href="contact.html" /> <item name="Dépôt SVN" href="http://svn.chorem.org/svn/lima/"/>
participants (1)
-
tchemit@users.chorem.org