r3798 - in trunk: . lima-business lima-business/src/main/java/org/chorem/lima lima-business/src/main/java/org/chorem/lima/business lima-business/src/main/java/org/chorem/lima/business/accountingrules lima-business/src/main/java/org/chorem/lima/business/ejb lima-business/src/main/java/org/chorem/lima/business/migration lima-business/src/main/java/org/chorem/lima/business/utils lima-business/src/main/java/org/chorem/lima/service lima-business/src/test/java/org/chorem/lima/business lima-business
Author: dcosse Date: 2014-05-16 10:39:35 +0200 (Fri, 16 May 2014) New Revision: 3798 Url: http://forge.chorem.org/projects/lima/repository/revisions/3798 Log: refs #934 d?\195?\169but de migration vers Topia3 Added: trunk/lima-business/src/main/java/org/chorem/lima/LimaServer.java trunk/lima-business/src/main/java/org/chorem/lima/LimaXAResource.java trunk/lima-business/src/main/java/org/chorem/lima/business/ trunk/lima-business/src/main/java/org/chorem/lima/business/AccountingRules.java trunk/lima-business/src/main/java/org/chorem/lima/business/LimaBusinessException.java trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java trunk/lima-business/src/main/java/org/chorem/lima/business/LimaDaoHelper.java trunk/lima-business/src/main/java/org/chorem/lima/business/LimaInterceptor.java trunk/lima-business/src/main/java/org/chorem/lima/business/ServiceListener.java trunk/lima-business/src/main/java/org/chorem/lima/business/ServiceMonitorable.java trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/ trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/DefaultAccountingRules.java trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/FranceAccountingRules.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ 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/ClosedPeriodicEntryBookServiceImpl.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/EntryServiceImpl.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/migration/ trunk/lima-business/src/main/java/org/chorem/lima/business/migration/DatabaseMigrationClass.java trunk/lima-business/src/main/java/org/chorem/lima/business/migration/MigrationV0V0_5.java trunk/lima-business/src/main/java/org/chorem/lima/business/migration/MigrationV0_6.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/AccountComparator.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/AccountEBPComparator.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/EntryComparator.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/EntryEBPComparator.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FinancialPeriodComparator.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FinancialTransactionComparator.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FiscalPeriodComparator.java trunk/lima-business/src/main/java/org/chorem/lima/business/utils/LetteringComparator.java trunk/lima-business/src/main/java/org/chorem/lima/service/ trunk/lima-business/src/main/java/org/chorem/lima/service/LimaServiceFactory.java trunk/lima-business/src/main/java/org/chorem/lima/service/ServiceMonitorableHandler.java trunk/lima-business/src/main/java/org/chorem/lima/service/package-info.java trunk/lima-business/src/test/java/org/chorem/lima/business/AbstractLimaTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/EntryBookServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialPeriodServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialTransactionServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/FiscalPeriodServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/ImportServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/LetteringComparatorTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/LimaMiscTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/ReportServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/AccountServiceRuleFrTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/EntryBookServiceRuleFrTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FinancialPeriodServiceRuleFrTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FinancialTransactionServiceRuleFrTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FiscalPeriodServiceRuleFrTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ImportServiceRuleFrTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ReportServiceRuleFrTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/TestAccountingRules.java trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ClearService.java trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ClearServiceImpl.java trunk/lima-business/src/test/java/org/chorem/lima/business/utils/ trunk/lima-business/src/test/java/org/chorem/lima/entity/AccountDAOTest.java trunk/lima-business/src/test/java/org/chorem/lima/entity/FinancialTransactionDAOTest.java trunk/lima-callao/src/main/java/org/chorem/lima/DefaultServiceContext.java trunk/lima-callao/src/main/java/org/chorem/lima/ServiceContext.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractAccountTopiaDao.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractClosedPeriodicEntryBookTopiaDao.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractEntryTopiaDao.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialPeriodTopiaDao.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialStatementTopiaDao.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialTransactionTopiaDao.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFiscalPeriodTopiaDao.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractVatStatementTopiaDao.java trunk/lima-callao/src/main/xmi/accounting-model.properties trunk/lima-callao/src/main/xmi/accounting-model.zargo Removed: trunk/lima-business/src/main/java/org/chorem/lima/LimaServer.java trunk/lima-business/src/main/java/org/chorem/lima/LimaXAResource.java trunk/lima-business/src/main/java/org/chorem/lima/business/ trunk/lima-business/src/main/java/org/chorem/lima/service/ trunk/lima-business/src/test/java/org/chorem/lima/business/AbstractLimaTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/EntryBookServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialPeriodServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialTransactionServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/FiscalPeriodServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/ImportServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/LetteringComparatorTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/LimaMiscTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/ReportServiceImplTest.java trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ trunk/lima-business/src/test/java/org/chorem/lima/business/utils/ trunk/lima-business/src/test/java/org/chorem/lima/entity/AccountDAOTest.java trunk/lima-business/src/test/java/org/chorem/lima/entity/FinancialTransactionDAOTest.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/AccountDAOImpl.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/ClosedPeriodicEntryBookDAOImpl.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/EntryDAOImpl.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialPeriodDAOImpl.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialStatementDAOImpl.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialTransactionDAOImpl.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/FiscalPeriodDAOImpl.java trunk/lima-callao/src/main/java/org/chorem/lima/entity/VatStatementDAOImpl.java Modified: trunk/lima-business-api/src/main/java/org/chorem/lima/business/api/ReportService.java trunk/lima-business/pom.xml trunk/lima-callao/pom.xml trunk/lima-callao/src/main/java/org/chorem/lima/entity/GeneratorHQuery.java trunk/lima-neogia/src/main/java/org/chorem/lima/service/neogia/NeogiaEntryService.java trunk/lima-swing/src/main/resources/log4j.properties trunk/pom.xml Modified: trunk/lima-business/pom.xml =================================================================== --- trunk/lima-business/pom.xml 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/pom.xml 2014-05-16 08:39:35 UTC (rev 3798) @@ -24,11 +24,6 @@ <dependencies> <dependency> - <groupId>org.apache.openejb</groupId> - <artifactId>javaee-api</artifactId> - <scope>provided</scope> - </dependency> - <dependency> <groupId>${project.groupId}</groupId> <artifactId>lima-callao</artifactId> <version>${project.version}</version> @@ -104,6 +99,11 @@ </dependency> <dependency> <groupId>org.apache.openejb</groupId> + <artifactId>javaee-api</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.apache.openejb</groupId> <artifactId>openejb-core</artifactId> </dependency> <dependency> Deleted: trunk/lima-business/src/main/java/org/chorem/lima/LimaServer.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/LimaServer.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/main/java/org/chorem/lima/LimaServer.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,76 +0,0 @@ -/* - * #%L - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2011 Codelutin, Chatellier Eric - * %% - * 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; - -import org.apache.openejb.core.LocalInitialContextFactory; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import java.util.Properties; - -/** - * Lima server class. - * <p/> - * Starts openejb server. - * - * @author chatellier - * @version $Revision$ - * <p/> - * Last update : $Date$ - * By : $Author$ - */ -public class LimaServer { - - /** - * Lima server. - * - * @param args - * @throws NamingException - */ - public static void main(String... args) throws NamingException { - Properties properties = new Properties(); - properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName()); - properties.setProperty("openejb.embedded.remotable", "true"); - // Uncomment these properties to change the defaults - //properties.setProperty("ejbd.port", "4202"); - properties.setProperty("ejbd.bind", "0.0.0.0"); - //properties.setProperty("ejbd.threads", "200"); - //properties.setProperty("ejbd.disabled", "false"); - //properties.setProperty("ejbd.only_from", "127.0.0.1,192.168.1.1"); - - new InitialContext(properties); - - // block main otherwize, main will end - synchronized (properties) { - try { - properties.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - System.out.println("Server shutdown"); - } -} Added: trunk/lima-business/src/main/java/org/chorem/lima/LimaServer.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/LimaServer.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/LimaServer.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,76 @@ +/* + * #%L + * $Id: LimaServer.java 3350 2012-04-04 09:03:41Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2011 Codelutin, Chatellier Eric + * %% + * 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; + +import org.apache.openejb.core.LocalInitialContextFactory; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import java.util.Properties; + +/** + * Lima server class. + * <p/> + * Starts openejb server. + * + * @author chatellier + * @version $Revision: 3350 $ + * <p/> + * Last update : $Date: 2012-04-04 11:03:41 +0200 (mer. 04 avril 2012) $ + * By : $Author: echatellier $ + */ +public class LimaServer { + + /** + * Lima server. + * + * @param args + * @throws NamingException + */ + public static void main(String... args) throws NamingException { + Properties properties = new Properties(); + properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName()); + properties.setProperty("openejb.embedded.remotable", "true"); + // Uncomment these properties to change the defaults + //properties.setProperty("ejbd.port", "4202"); + properties.setProperty("ejbd.bind", "0.0.0.0"); + //properties.setProperty("ejbd.threads", "200"); + //properties.setProperty("ejbd.disabled", "false"); + //properties.setProperty("ejbd.only_from", "127.0.0.1,192.168.1.1"); + + new InitialContext(properties); + + // block main otherwize, main will end + synchronized (properties) { + try { + properties.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + System.out.println("Server shutdown"); + } +} Deleted: trunk/lima-business/src/main/java/org/chorem/lima/LimaXAResource.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/LimaXAResource.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/main/java/org/chorem/lima/LimaXAResource.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,151 +0,0 @@ -/* - * #%L - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 Codelutin, Chatellier Eric - * %% - * 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; - -import javax.transaction.xa.XAException; -import javax.transaction.xa.XAResource; -import javax.transaction.xa.Xid; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; - -/** - * Topia XA ressource containing TopiaContext to commit or rollback. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class LimaXAResource implements XAResource { - - private static Log log = LogFactory.getLog(LimaXAResource.class); - - protected TopiaContext context; - - protected int timeout; - - public LimaXAResource(TopiaContext context) { - this.context = context; - } - - /* - * @see javax.transaction.xa.XAResource#commit(javax.transaction.xa.Xid, boolean) - */ - @Override - public void commit(Xid arg0, boolean arg1) throws XAException { - try { - context.commitTransaction(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error", ex); - } - throw new XAException(XAException.XA_HEURCOM); - } - } - - /* - * @see javax.transaction.xa.XAResource#end(javax.transaction.xa.Xid, int) - */ - @Override - public void end(Xid arg0, int arg1) throws XAException { - /*try { - context.closeContext(); - } catch (TopiaException ex) { - throw new XAException(XAException.XA_HEURCOM); - }*/ - } - - /* - * @see javax.transaction.xa.XAResource#forget(javax.transaction.xa.Xid) - */ - @Override - public void forget(Xid xid) throws XAException { - - } - - /* - * @see javax.transaction.xa.XAResource#getTransactionTimeout() - */ - @Override - public int getTransactionTimeout() throws XAException { - return timeout; - } - - /* - * @see javax.transaction.xa.XAResource#isSameRM(javax.transaction.xa.XAResource) - */ - @Override - public boolean isSameRM(XAResource xar) throws XAException { - return false; - } - - /* - * @see javax.transaction.xa.XAResource#prepare(javax.transaction.xa.Xid) - */ - @Override - public int prepare(Xid xid) throws XAException { - return XAResource.XA_OK; - } - - /* - * @see javax.transaction.xa.XAResource#recover(int) - */ - @Override - public Xid[] recover(int arg0) throws XAException { - return null; - } - - /* - * @see javax.transaction.xa.XAResource#rollback(javax.transaction.xa.Xid) - */ - @Override - public void rollback(Xid arg0) throws XAException { - try { - context.rollbackTransaction(); - } catch (TopiaException ex) { - throw new XAException(XAException.XA_HEURCOM); - } - } - - /* - * @see javax.transaction.xa.XAResource#setTransactionTimeout(int) - */ - @Override - public boolean setTransactionTimeout(int timeout) throws XAException { - this.timeout = timeout; - return true; - } - - /* - * @see javax.transaction.xa.XAResource#start(javax.transaction.xa.Xid, int) - */ - @Override - public void start(Xid arg0, int arg1) throws XAException { - - } -} Added: trunk/lima-business/src/main/java/org/chorem/lima/LimaXAResource.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/LimaXAResource.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/LimaXAResource.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,150 @@ +/* + * #%L + * $Id: LimaXAResource.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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; + +import javax.transaction.xa.XAException; +import javax.transaction.xa.XAResource; +import javax.transaction.xa.Xid; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.persistence.TopiaException; + +/** + * Topia XA ressource containing TopiaContext to commit or rollback. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class LimaXAResource implements XAResource { + + private static Log log = LogFactory.getLog(LimaXAResource.class); + + protected TopiaContext context; + + protected int timeout; + + public LimaXAResource(TopiaContext context) { + this.context = context; + } + + /* + * @see javax.transaction.xa.XAResource#commit(javax.transaction.xa.Xid, boolean) + */ + @Override + public void commit(Xid arg0, boolean arg1) throws XAException { + try { + context.commitTransaction(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error", ex); + } + throw new XAException(XAException.XA_HEURCOM); + } + } + + /* + * @see javax.transaction.xa.XAResource#end(javax.transaction.xa.Xid, int) + */ + @Override + public void end(Xid arg0, int arg1) throws XAException { + /*try { + context.closeContext(); + } catch (TopiaException ex) { + throw new XAException(XAException.XA_HEURCOM); + }*/ + } + + /* + * @see javax.transaction.xa.XAResource#forget(javax.transaction.xa.Xid) + */ + @Override + public void forget(Xid xid) throws XAException { + + } + + /* + * @see javax.transaction.xa.XAResource#getTransactionTimeout() + */ + @Override + public int getTransactionTimeout() throws XAException { + return timeout; + } + + /* + * @see javax.transaction.xa.XAResource#isSameRM(javax.transaction.xa.XAResource) + */ + @Override + public boolean isSameRM(XAResource xar) throws XAException { + return false; + } + + /* + * @see javax.transaction.xa.XAResource#prepare(javax.transaction.xa.Xid) + */ + @Override + public int prepare(Xid xid) throws XAException { + return XAResource.XA_OK; + } + + /* + * @see javax.transaction.xa.XAResource#recover(int) + */ + @Override + public Xid[] recover(int arg0) throws XAException { + return null; + } + + /* + * @see javax.transaction.xa.XAResource#rollback(javax.transaction.xa.Xid) + */ + @Override + public void rollback(Xid arg0) throws XAException { + try { + context.rollbackTransaction(); + } catch (TopiaException ex) { + throw new XAException(XAException.XA_HEURCOM); + } + } + + /* + * @see javax.transaction.xa.XAResource#setTransactionTimeout(int) + */ + @Override + public boolean setTransactionTimeout(int timeout) throws XAException { + this.timeout = timeout; + return true; + } + + /* + * @see javax.transaction.xa.XAResource#start(javax.transaction.xa.Xid, int) + */ + @Override + public void start(Xid arg0, int arg1) throws XAException { + + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/AccountingRules.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/AccountingRules.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/AccountingRules.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,102 @@ +/* + * #%L + * Lima business + * + * $Id: AccountingRules.java 3519 2012-07-12 10:27:43Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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; + +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FiscalPeriod; + +import java.util.List; + +/** + * Service for localized rules + * + * @author jpepin + */ +public interface AccountingRules { + + /** + * Account rule : check create account. + * + * @param account new account + * @throws LimaException if rule validation fails + */ + void createAccountRules(Account account) throws LimaException; + + void updateAccountRules(Account account) throws LimaException; + + void removeAccountRules(Account account) throws LimaException; + + /** + * Entrybook rules. + * + * @param entryBook + * @throws LimaException + */ + void removeEntryBookRules(EntryBook entryBook) throws LimaException; + + /** + * Fiscal Period rules + * + * @param fiscalPeriod + * @throws LimaException + */ + List<FinancialPeriod> createFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaException; + + void blockFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaException; + + void deleteFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaException; + + /** + * Entry rules + * + * @param entry + * @throws LimaException + */ + void updateEntryRules(Entry entry, Entry entryOld) throws LimaException; + + void updateFinancialTransactionDateRules(FinancialTransaction financialTransaction, FinancialTransaction financialTransactionOld) throws LimaException; + + /** + * Financialperiod/entrybook rules + * + * @param financialTransaction + * @throws LimaException + */ + void checkFinancialPeriodBlockedWithFinancialTransaction(FinancialTransaction financialTransaction) throws LimaException; + + /** + * Check if a financial period can be closed. + * + * @param closedPeriodicEntryBook + * @throws LimaException + */ + void blockClosedPeriodicEntryBookRules(ClosedPeriodicEntryBook closedPeriodicEntryBook) throws LimaException; +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/LimaBusinessException.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/LimaBusinessException.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/LimaBusinessException.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,61 @@ +/* + * #%L + * Lima business + * + * $Id: LimaBusinessException.java 3290 2011-09-17 12:55:34Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2010 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; + +/** + * Lima business exception throw by a business service method + * that cannot execute successfully. + * + * @author chatellier + * @version $Revision: 3290 $ + * <p/> + * Last update : $Date: 2011-09-17 14:55:34 +0200 (sam. 17 sept. 2011) $ + * By : $Author: tchemit $ + */ +public class LimaBusinessException extends LimaException { + + /** serialVersionUID. */ + private static final long serialVersionUID = -6876236663940184462L; + + /** + * Constructs a new exception with the specified detail message. + * + * @param message message + */ + public LimaBusinessException(String message) { + super(message); + } + + /** + * Constructs a new exception with the specified detail message and cause. + * + * @param message message + * @param cause cause + */ + public LimaBusinessException(String message, Throwable cause) { + super(message, cause); + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,259 @@ +/* + * #%L + * Lima business + * + * $Id: LimaConfig.java 3796 2014-05-13 14:52:18Z echatellier $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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; + +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.LimaCallaoEntityEnum; +import org.chorem.lima.entity.LimaCallaoTopiaDaoSupplier; +import org.nuiton.topia.persistence.TopiaConfigurationConstants; +import org.nuiton.topia.migration.TopiaMigrationEngine; +import org.nuiton.topia.migration.TopiaMigrationService; +import org.nuiton.config.ApplicationConfig; +import org.nuiton.config.ConfigOptionDef; +import org.nuiton.config.ArgumentsParserException; + +import java.io.File; + +import static org.nuiton.i18n.I18n.t; +import static org.nuiton.i18n.I18n.n; + +/** + * Configuration pour le business. + * <p/> + * A voir comment le lier avec celui de lima swing. + * + * @author chatellier + * @version $Revision: 3796 $ + * <p/> + * Last update : $Date: 2014-05-13 16:52:18 +0200 (mar. 13 mai 2014) $ + * By : $Author: echatellier $ + */ +public class LimaConfig extends ApplicationConfig { + + private static final Log log = LogFactory.getLog(LimaConfig.class); + + protected static LimaConfig instance; + + protected AccountingRules accountingRules; + + public LimaConfig() { + // load default options + super(Option.class, null, null, null); + + setOption(TopiaMigrationService.TOPIA_SERVICE_NAME, TopiaMigrationEngine.class.getName()); + setOption(TopiaMigrationService.MIGRATION_CALLBACK, DatabaseMigrationClass.class.getName()); + setOption(TopiaMigrationService.MIGRATION_SHOW_SQL, Boolean.TRUE.toString()); + setOption(TopiaMigrationService.MIGRATION_SHOW_PROGRESSION, Boolean.TRUE.toString()); + } + + public static LimaConfig getInstance() { + if (instance == null) { + instance = new LimaConfig(); + instance.loadConfiguration(); + } + return instance; + } + + /** + * Instancie la bonne classe de nationalite en fonction du fichier de configuration. + * + * L'instance est conservée en cache. + * + * @return l'instance de rule + */ + public AccountingRules getAccountingRules() { + + if (accountingRules == null) { + Class<?> accountingRulesClass = getOptionAsClass(Option.RULES_NATIONALTY.key); + if (accountingRulesClass == null) { + accountingRules = new DefaultAccountingRules(); + } else { + try { + accountingRules = (AccountingRules) accountingRulesClass.newInstance(); + } catch (Exception ex) { + if (log.isErrorEnabled()) { + log.error("Can't instantiate accounting rules", ex); + } + } + } + } + + return accountingRules; + } + + public void setAccountingRule(String accountingRule) { + accountingRules = null; // clear cache + setOption(Option.RULES_NATIONALTY.key, accountingRule); + } + + public File getDataDir() { + File datadir = getOptionAsFile(Option.DATA_DIR.getKey()); + return datadir; + } + + public File getReportsDir() { + File reportsDir = getOptionAsFile(Option.REPORTS_DIR.getKey()); + return reportsDir; + } + + public String getAddressServer() { + String serverAddress = getOption(Option.SERVER_ADRESS.getKey()); + return serverAddress; + } + + public int getHttpPort() { + String httpPort = getOption(Option.HTTP_PORT.getKey()); + Integer port = Integer.valueOf(httpPort); + return port; + } + + public String getScale() { + String scale = getOption(Option.SCALE.getKey()); + return scale; + } + + public void setScale(String locale) { + setOption(Option.SCALE.key, locale); + saveForUser(); + } + + public String getVatPDFUrl() { + String vatPDFUrl = getOption(Option.VAT_PDF_URL.getKey()); + return vatPDFUrl; + } + + public void setVatPDFUrl(String url) { + setOption(Option.VAT_PDF_URL.key, url); + saveForUser(); + } + + /** + * Load configuration with custom file name. + */ + protected void loadConfiguration() { + try { + instance.parse(); + } catch (ArgumentsParserException ex) { + if (log.isErrorEnabled()) { + log.error("Can't read configuration", ex); + } + } + + instance.setOption(TopiaConfigurationConstants.CONFIG_PERSISTENCE_CLASSES, + LimaCallaoEntityEnum.getImplementationClassesAsString()); + } + + /** + * Lima option definition. + * <p/> + * Contains all lima configuration key, with defaut value and + * information for jaxx configuration frame ({@code #type}, + * {@code #transientBoolean}, {@code #finalBoolean}...) + */ + public enum Option implements ConfigOptionDef { + + CONFIG_FILE(CONFIG_FILE_NAME, n("lima.config.configFileName.description"), "lima.properties", String.class, true, true), + DATA_DIR("lima.data.dir", n("lima.config.data.dir.description"), "${user.home}/.lima", File.class, false, false), + REPORTS_DIR("lima.reports.dir", n("lima.config.reports.dir.description"), "${lima.data.dir}/reports", File.class, false, false), + RULES_NATIONALTY("lima.rules", n("lima.config.rulesnationality.description"), FranceAccountingRules.class.getName(), String.class, false, false), + HTTP_PORT("lima.httpport", n("lima.config.httpport.description"), "5462", String.class, false, false), + SERVER_ADRESS("lima.serveraddress", n("lima.config.serveraddress.description"), "", String.class, false, false), + SCALE("lima.scale", n("lima.config.scale.description"), "2", String.class, false, false), + VAT_PDF_URL("lima.report.vatpdfurl", n("lima.config.reportvatpdfurl.description"), "default", String.class, false, false); + + private final String key; + + private final String description; + + private String defaultValue; + + private final Class<?> type; + + private boolean transientBoolean; + + private boolean finalBoolean; + + Option(String key, String description, String defaultValue, + Class<?> type, boolean transientBoolean, boolean finalBoolean) { + this.key = key; + this.description = description; + this.defaultValue = defaultValue; + this.type = type; + this.finalBoolean = finalBoolean; + this.transientBoolean = transientBoolean; + } + + @Override + public boolean isFinal() { + return finalBoolean; + } + + @Override + public void setFinal(boolean finalBoolean) { + this.finalBoolean = finalBoolean; + } + + @Override + public boolean isTransient() { + return transientBoolean; + } + + @Override + public void setTransient(boolean transientBoolean) { + this.transientBoolean = transientBoolean; + } + + @Override + public String getDefaultValue() { + return defaultValue; + } + + @Override + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + @Override + public String getDescription() { + return t(description); + } + + @Override + public String getKey() { + return key; + } + + @Override + public Class<?> getType() { + return type; + } + } + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/LimaDaoHelper.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/LimaDaoHelper.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/LimaDaoHelper.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,95 @@ +/* + * #%L + * $Id: LimaDaoHelper.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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; + +import org.chorem.lima.entity.AccountTopiaDao; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.EntryBookTopiaDao; +import org.chorem.lima.entity.EntryTopiaDao; +import org.chorem.lima.entity.FinancialPeriodTopiaDao; +import org.chorem.lima.entity.FinancialStatementTopiaDao; +import org.chorem.lima.entity.FinancialTransactionTopiaDao; +import org.chorem.lima.entity.FiscalPeriodTopiaDao; +import org.chorem.lima.entity.IdentityTopiaDao; +import org.chorem.lima.entity.LimaCallaoTopiaDaoSupplier; +import org.chorem.lima.entity.VatStatementTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +/** + * DOA helper based on EJB because of context using. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class LimaDaoHelper { + + protected LimaCallaoTopiaDaoSupplier limaCallaoTopiaDaoSupplier; + + public LimaDaoHelper(LimaCallaoTopiaDaoSupplier limaCallaoTopiaDaoSupplier) { + this.limaCallaoTopiaDaoSupplier = limaCallaoTopiaDaoSupplier; + } + + public AccountTopiaDao getAccountTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getAccountDao(); + } + + public EntryTopiaDao getEntryTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getEntryDao(); + } + + public FinancialPeriodTopiaDao getFinancialPeriodTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getFinancialPeriodDao(); + } + + public FinancialTransactionTopiaDao getFinancialTransactionTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getFinancialTransactionDao(); + } + + public FinancialStatementTopiaDao getFinancialStatementTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getFinancialStatementDao(); + } + + public FiscalPeriodTopiaDao getFiscalPeriodTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getFiscalPeriodDao(); + } + + public ClosedPeriodicEntryBookTopiaDao getClosedPeriodicEntryBookTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getClosedPeriodicEntryBookDao(); + } + + public EntryBookTopiaDao getEntryBookTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getEntryBookDao(); + } + + public VatStatementTopiaDao getVatStatementTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getVatStatementDao(); + } + + public IdentityTopiaDao getIdentityTopiaDao() throws TopiaException { + return limaCallaoTopiaDaoSupplier.getIdentityDao(); + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/LimaInterceptor.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/LimaInterceptor.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/LimaInterceptor.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,137 @@ +/* + * #%L + * $Id: LimaInterceptor.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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; + +import javax.annotation.Resource; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.interceptor.AroundInvoke; +import javax.interceptor.InvocationContext; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.LimaXAResource; +import org.chorem.lima.entity.AccountImpl; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.persistence.TopiaConfigurationConstants; +import org.nuiton.topia.persistence.TopiaException; +import org.nuiton.topia.framework.TopiaUtil; + +/** + * Interceptor for topia context transaction. + * + * http://stackoverflow.com/questions/8608349 + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +@Stateless +public class LimaInterceptor { + + private static final Log log = LogFactory.getLog(LimaInterceptor.class); + + public static final ThreadLocal<LimaDaoHelper> DAO_HELPER = new ThreadLocal<LimaDaoHelper>(); + + @Resource + private TransactionManager transactionManager; + + @AroundInvoke + public Object invoke(InvocationContext context) throws Exception { + + Object result; + + // only open transaction when incoming call just + // enter in service layer + // interceptor will be called before each internal + // ejb call, but opening a new transaction in not required + if (DAO_HELPER.get() == null) { + + // maybe take care of TransactionAttributeTypes ? + if (context.getTarget().getClass().getAnnotation(TransactionAttribute.class) != null || + context.getMethod().getAnnotation(TransactionAttribute.class) != null) { + if (log.isDebugEnabled()) { + log.debug("Init new topia transaction for method : " + + context.getTarget().getClass() + "#" + context.getMethod().getName()); + } + + LimaConfig config = LimaConfig.getInstance(); + TopiaContext rootContext = TopiaContextFactory.getContext(config.getFlatOptions()); + TopiaContext tx = rootContext.beginTransaction(); + + createShemaIfNeeded(tx); + + LimaDaoHelper helper = new LimaDaoHelper(tx); + DAO_HELPER.set(helper); + + Transaction tr = transactionManager.getTransaction(); + + // enlist topia xaresource, will will commited or rollback + // by container + tr.enlistResource(new LimaXAResource(tx)); + + try { + result = context.proceed(); + } finally { + DAO_HELPER.remove(); + } + } else { + result = context.proceed(); + } + + } else { + result = context.proceed(); + } + + return result; + } + + protected static boolean schemaExistChecked = false; + + /** + * Test if schema do not already exists and create it if not found. + * + * @param tx transaction + * @throws TopiaException + */ + protected void createShemaIfNeeded(TopiaContext tx) throws TopiaException { + + if (!schemaExistChecked) { + boolean exist = TopiaUtil.isSchemaExist(tx, AccountImpl.class.getName()); + if (!exist) { + + if (log.isInfoEnabled()) { + log.info("Creating to schema in database"); + } + tx.createSchema(); + } + + schemaExistChecked = true; + } + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/ServiceListener.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ServiceListener.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ServiceListener.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,32 @@ +/* + * #%L + * Lima business + * + * $Id: ServiceListener.java 3278 2011-08-16 14:09:44Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2010 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; + +public interface ServiceListener { + + void notifyMethod(String serviceName, String methodeName); + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/ServiceMonitorable.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ServiceMonitorable.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ServiceMonitorable.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,34 @@ +/* + * #%L + * Lima business + * + * $Id: ServiceMonitorable.java 3366 2012-04-13 13:46:24Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2010 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; + + + +public interface ServiceMonitorable { + void addServiceListener(ServiceListener l); + + void removeServiceListener(ServiceListener l); +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/DefaultAccountingRules.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/DefaultAccountingRules.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/DefaultAccountingRules.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,364 @@ +/* + * #%L + * Lima business + * + * $Id: DefaultAccountingRules.java 3777 2014-04-14 07:29:08Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.apache.commons.lang3.StringUtils; +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.LimaDaoHelper; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.LimaInterceptor; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryBookTopiaDao; +import org.chorem.lima.entity.EntryTopiaDao; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialPeriodTopiaDao; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionTopiaDao; +import org.chorem.lima.entity.FiscalPeriod; +import org.chorem.lima.entity.FiscalPeriodTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +; + +/** + * Defaults rules, if no localized rules classes is instantiated + * this default class contain the strict minimum rules to check the data integrity. + * + * Rule specialization should override this class. + * + * @author jpepin + */ +public class DefaultAccountingRules implements AccountingRules { + + protected static final Log log = + LogFactory.getLog(DefaultAccountingRules.class); + + /** + * Return Dao helper to use in current thread. + * Defined by {@link LimaInterceptor}. + * + * @return dao helper + */ + protected LimaDaoHelper getDaoHelper() { + return LimaInterceptor.DAO_HELPER.get(); + } + + /** + * Rules to check before create accounts. + */ + @Override + public void createAccountRules(Account account) throws LimaException { + + // Check if the numberaccount is not blank + if (StringUtils.isBlank(account.getAccountNumber())) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.invalidaccountnumber", + account.getAccountNumber())); + } + } + + @Override + public void updateAccountRules(Account account) throws LimaException { + // Check if the numberaccount is not blank + if (StringUtils.isBlank(account.getAccountNumber())) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.invalidaccountnumber", + account.getAccountNumber())); + } + } + + /** Rules to check before create fiscals periods */ + @Override + public List<FinancialPeriod> createFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaException { + //check if the enddate period is after the begindate period + if (fiscalPeriod.getEndDate().before(fiscalPeriod.getBeginDate())) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.enddateerror")); + } + return null; + } + + /** Rules to check before block fiscals periods */ + @Override + public void blockFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaException { + + } + + /** Rules to check before delete fiscals periods */ + @Override + public void deleteFiscalPeriodRules(FiscalPeriod fiscalPeriod) + throws LimaException { + } + + /** + * Rules to check if an account and all his subaccount is not used + * Recursive function + */ + @Override + public void removeAccountRules(Account account) throws LimaException { + try { + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + // Check if account have entries + int nbentries = entryTopiaDao.findAllByAccount(account).size(); + if (nbentries != 0) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.deleteaccounterror")); + } + } catch (TopiaException ex) { + throw new LimaException("Can't remvoe account", ex); + } + } + + /** Check if entrybook have financial transaction */ + @Override + public void removeEntryBookRules(EntryBook entryBook) throws LimaException { + try { + FinancialTransactionTopiaDao financialTransactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + + // Check if entrybook have entries + long nbfinancialtransaction = financialTransactionTopiaDao.getCountByEntryBook(entryBook); + if (nbfinancialtransaction != 0) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.deleteentrybookerror")); + } + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + + } + + /** + * check if financial period of a financial transaction is blocked + * check if all entrybook of his financial period are blocked + */ + @Override + public void checkFinancialPeriodBlockedWithFinancialTransaction(FinancialTransaction financialTransaction) throws LimaException { + + try { + //check financial period locked + FinancialPeriodTopiaDao financialPeriodTopiaDao = getDaoHelper().getFinancialPeriodTopiaDao(); + FinancialPeriod financialPeriod = financialPeriodTopiaDao.findByDate(financialTransaction.getTransactionDate()); + if (financialPeriod.isLocked()) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.financialperiodblocked")); + } + + //check all entrybook of his financial period are blocked + //FIXME echatellier 20120509 il doit y avoir moyen de faire plus + //simple que de recuperer 2 listes et de comparer leur nombres + List<EntryBook> entryBooks = new ArrayList<EntryBook>(); + List<EntryBook> closedEntryBooks = new ArrayList<EntryBook>(); + + EntryBookTopiaDao entryBookTopiaDao = getDaoHelper().getEntryBookTopiaDao(); + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + + entryBooks = entryBookTopiaDao.findAll(); + for (EntryBook entryBook : entryBooks) { + ClosedPeriodicEntryBook closedPeriodicEntryBook = + closedPeriodicEntryBookTopiaDao.findByEntryBookAndFinancialPeriod( + entryBook, financialPeriod); + if (closedPeriodicEntryBook.isLocked()) { + closedEntryBooks.add(entryBook); + } + } + if (entryBooks.size() == closedEntryBooks.size()) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.allentrybookclosed")); + } + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + } + + /** + * Check if all financial transactions of closedperiodicentrybook are equilibrate + * Check if all financial transactions of this closedperiodicentrybook/financialPeriod are well filled in + * Check if all financial transactions have EntryBooks + */ + @Override + public void blockClosedPeriodicEntryBookRules(ClosedPeriodicEntryBook closedPeriodicEntryBook) + throws LimaException { + + try { + FinancialTransactionTopiaDao financialTransactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + // reload object in current transaction + closedPeriodicEntryBook = closedPeriodicEntryBookTopiaDao.findByTopiaId(closedPeriodicEntryBook.getTopiaId()); + + // Check if all financial transactions of closedperiodicentrybook are equilibrate + // FIXME echatellier 20120504 unutile de recuperer une liste + // entiere juste pour tester l'existence + FinancialPeriod period = closedPeriodicEntryBook.getFinancialPeriod(); + List<FinancialTransaction> result = financialTransactionTopiaDao.getAllUnbalancedTransaction(period.getBeginDate(), + period.getEndDate(), closedPeriodicEntryBook.getEntryBook()); + if (result.size() > 0) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.blockerrorequillibrate")); + } + + // Check if all financial transactions of this closedperiodicentrybook/financialPeriod are well filled in + result = financialTransactionTopiaDao.getAllUnfilledTransaction(period.getBeginDate(), + period.getEndDate(), closedPeriodicEntryBook.getEntryBook()); + // FIXME echatellier 20120504 unutile de recuperer une liste + // entiere juste pour tester l'existence + if (result.size() > 0) { + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.missingelements")); + } + + // Check if all financial transactions have EntryBooks + result = financialTransactionTopiaDao.getAllTransactionWithoutEntryBook(period.getBeginDate(), + period.getEndDate()); + // FIXME echatellier 20120504 unutile de recuperer une liste + // entiere juste pour tester l'existence + if (result.size() > 0) { + FinancialTransaction transaction = result.get(0); + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.missingentrybook", transaction.getTransactionDate())); + } + + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + } + + /** + * Rules on update entry : + * <p/> + * Two case : + * - second, the actual entry belong to a blocked closedPeriodicEntryBook + * - third, the new choice entrybook belong to a blocked closedPeriodicEntryBook + */ + @Override + public void updateEntryRules(Entry entry, Entry entryOld) throws LimaException { + + try { + + FinancialPeriodTopiaDao financialPeriodTopiaDao = getDaoHelper().getFinancialPeriodTopiaDao(); + FinancialPeriod financialPeriod = financialPeriodTopiaDao.findByDate(entry.getFinancialTransaction().getTransactionDate()); + + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + + if (entryOld != null) { + //second case + ClosedPeriodicEntryBook closedPeriodicEntryBook = + closedPeriodicEntryBookTopiaDao.findByEntryBookAndFinancialPeriod( + entryOld.getFinancialTransaction().getEntryBook(), financialPeriod); + if (closedPeriodicEntryBook.isLocked()) { + throw new LimaBusinessException(t("lima-Business.defaultaccountingrules.updateentryerror")); + } + } + + //third case + ClosedPeriodicEntryBook closedPeriodicEntryBook2 = + closedPeriodicEntryBookTopiaDao.findByEntryBookAndFinancialPeriod( + entry.getFinancialTransaction().getEntryBook(), financialPeriod); + + // Check 2 & 3 cases + if (closedPeriodicEntryBook2.isLocked()) { + throw new LimaBusinessException(t("lima-Business.defaultaccountingrules.updateentryerror")); + } + + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + } + + + /** + * Check : + * 1. if date are on fiscal period + * 2. if old financialtransaction date are on periodblocked + * 3. if new financialtransaction date are on periodblocked + */ + @Override + public void updateFinancialTransactionDateRules( + FinancialTransaction financialTransaction, FinancialTransaction financialTransactionOld) throws LimaException { + + try { + + Date financialTransactionDate = financialTransaction.getTransactionDate(); + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + FiscalPeriod lastFiscalPeriod = fiscalPeriodTopiaDao.getLastFiscalPeriod(); + FiscalPeriod firstFiscalPeriod = fiscalPeriodTopiaDao.getFirstFiscalPeriod(); + Date beginDateFirstFiscalPeriod = firstFiscalPeriod.getBeginDate(); + Date endDateLastFiscalPeriod = lastFiscalPeriod.getEndDate(); + + //check if date are on fiscal period (test if date is after begindate of first f.p. and before enddate of last f.p.) + + if (log.isDebugEnabled()) { + log.debug("Date de transaction modifiée sur l'ui " + financialTransactionDate); + log.debug("Date de début du premier exercice : " + beginDateFirstFiscalPeriod); + log.debug("Date de fin du dernier exercice : " + endDateLastFiscalPeriod); + } + + //1-date not on a fiscal period + if (financialTransactionDate.before(beginDateFirstFiscalPeriod) || financialTransactionDate.after(endDateLastFiscalPeriod)){ + if (financialTransactionDate.before(beginDateFirstFiscalPeriod)) { + if (log.isDebugEnabled()) { + log.debug("Date de la transaction avant (antérieure) la date de début du premier exercice"); + } + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.datebeforeerror")); + } + + if (financialTransactionDate.after(endDateLastFiscalPeriod)) { + if (log.isDebugEnabled()) { + log.debug("Date de la transaction après (postérieure) la date de fin du dernier exercice"); + } + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.dateaftererror")); + } + }else{ //date on a fiscal period (and consequently on a financial), now test if financial is open + + FinancialPeriodTopiaDao financialPeriodTopiaDao = getDaoHelper().getFinancialPeriodTopiaDao(); + FinancialPeriod financialPeriod = financialPeriodTopiaDao.findByDate(financialTransaction.getTransactionDate()); + FinancialPeriod financialPeriodOld = financialPeriodTopiaDao.findByDate(financialTransactionOld.getTransactionDate()); + + //2. check old financial period locked + if (financialPeriodOld.isLocked()) { + if (log.isDebugEnabled()) { + log.debug("Periode (Old) financière bloquée"); + } + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.financialtransactionblocked")); + } + + //3. check new financial period locked + if (financialPeriod.isLocked()) { + if (log.isDebugEnabled()) { + log.debug("Periode (New) financière bloquée"); + } + throw new LimaBusinessException(t("lima-business.defaultaccountingrules.financialnewdateblocked")); + } + } + + } catch (TopiaException ex) { + throw new LimaException("Can't check financial transaction", ex); + } + } + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/FranceAccountingRules.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/FranceAccountingRules.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/accountingrules/FranceAccountingRules.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,280 @@ +/* + * #%L + * Lima business + * + * $Id: FranceAccountingRules.java 3777 2014-04-14 07:29:08Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaBusinessException; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialPeriodImpl; +import org.chorem.lima.entity.FinancialTransactionTopiaDao; +import org.chorem.lima.entity.FiscalPeriod; +import org.chorem.lima.entity.FiscalPeriodTopiaDao; +import org.nuiton.topia.persistence.TopiaException; +import org.chorem.lima.entity.Account; + + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * Surcharge des regles par defaut pour application à la comptabilité française. + * + * @author echatellier + */ +public class FranceAccountingRules extends DefaultAccountingRules { + + protected static final Log log = LogFactory.getLog(FranceAccountingRules.class); + + /** + * Règles de vérification de la création du PCG, appliquées à la comptabilité française. + */ + @Override + public void createAccountRules(Account account) throws LimaException { + super.createAccountRules(account); + + String accountNumber = account.getAccountNumber(); + + // ledger account must be located in 411 account + if (!StringUtils.isNumeric(accountNumber) && !accountNumber.startsWith("4")) { + log.warn(t("lima-business.franceaccountingrules.accountnumbernotnumeric", + account.getAccountNumber())); + } + + // Check root account starts with 1 to 8 + if (accountNumber.length() >= 1 && !accountNumber.substring(0, 1).matches("[1-8]")) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.accountstartnumbererror", + account.getAccountNumber())); + } + + } + + @Override + public void updateAccountRules(Account account) throws LimaException { + super.updateAccountRules(account); + + String accountNumber = account.getAccountNumber(); + + // Check if the number account is type numeric + if (!StringUtils.isNumeric(account.getAccountNumber())) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.accountnumbernotnumeric", + account.getAccountNumber())); + } + + // Check root account starts with 1 to 8 + if (accountNumber.length() >= 1 && !accountNumber.substring(0, 1).matches("[1-8]")) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.accountstartnumbererror", + account.getAccountNumber())); + } + } + + /** + * Règles de vérification d'ouverture d'un exercice, appliquées à la comptabilité française + * <p/> + * Permet de créer un exercice. + * <p/> + * Elle a une durée de un an, composées de 12 périodes mensuelles. + * Elle peut aussi être plus courte ou plus longue si l'entreprise + * se constitu ou entre en liquidation ou que l'entreprise decide + * de changer + * <p/> + * Elle correspond à l'exercice comptable. + * Pas plus de deux exercices fiscaux ne peuvent-être ouvert en même temps + */ + @Override + public List<FinancialPeriod> createFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaException { + super.createFiscalPeriodRules(fiscalPeriod); + List<FinancialPeriod> financialPeriods = new ArrayList<FinancialPeriod>(); + try { + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + + //Checks if is not the first fiscalperiod to create + if (fiscalPeriodTopiaDao.count() != 0) { + + FiscalPeriod lastFiscalPeriod = fiscalPeriodTopiaDao.getLastFiscalPeriod(); + + //check the new fiscal period adjoining the last + Date dateLastFiscalPeriod = lastFiscalPeriod.getEndDate(); + dateLastFiscalPeriod = DateUtils. + addDays(dateLastFiscalPeriod, 1); + dateLastFiscalPeriod = DateUtils.truncate(dateLastFiscalPeriod, Calendar.DATE); + Date dateFiscalPeriod = fiscalPeriod.getBeginDate(); + + if (dateLastFiscalPeriod.compareTo(dateFiscalPeriod) != 0) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.newfiscalperiodadjoiningerror")); + } + + //We can create a new fiscal period meantime the last fiscal period was not locked + //But not the ante periodfiscal + int unblockedFiscalPeriod = + fiscalPeriodTopiaDao.findAllByLocked(false).size(); + if (unblockedFiscalPeriod > 1) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.antefiscalperiodnotblocked")); + } + } + + // FinancialPeriods of 1 month are created + Date endDate = fiscalPeriod.getEndDate(); + Date loopDate = fiscalPeriod.getBeginDate(); + while (loopDate.before(endDate)) { + FinancialPeriod financialPeriod = new FinancialPeriodImpl(); + //important for fiscalperiod created from import, it can be locked, so financialperiods must be locked + financialPeriod.setLocked(fiscalPeriod.isLocked()); + financialPeriod.setBeginDate(loopDate); + loopDate = DateUtils.addMonths(loopDate, 1); + loopDate = DateUtils.truncate(loopDate, Calendar.MONTH); + loopDate = DateUtils.addMilliseconds(loopDate, -1); + if (loopDate.after(endDate)) { + financialPeriod.setEndDate(endDate); + } else { + financialPeriod.setEndDate(loopDate); + } + //create it + financialPeriods.add(financialPeriod); + + //loop incremente + loopDate = DateUtils.addMilliseconds(loopDate, 1); + } + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + return financialPeriods; + } + + /** + * Règles de vérification de fermeture d'un exercice, appliquées à la comptabilité française. + * + * On ne peut pas clore la dernière periode comptable ouverte. + */ + @Override + public void blockFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaException { + try { + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + + FiscalPeriod oldestUnBlockedFiscalPeriod = + fiscalPeriodTopiaDao.getLastUnlockedFiscalPeriod(); + + //Check if the fiscal period to block is the oldest + if (oldestUnBlockedFiscalPeriod.equals(fiscalPeriod)) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.lastFiscalPeriodCantBlocked")); + } + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + } + + /** + * Règles de vérification de supression d'un exercice, appliquées à la comptabilité française. + * + * On ne peut supprimer qu'une periode comptable ouverte vide. + */ + @Override + public void deleteFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaBusinessException { + + try { + + FinancialTransactionTopiaDao financialTransactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + + //Check if the fiscal period to delete is empty + if (financialTransactionTopiaDao.findAllByDates(fiscalPeriod.getBeginDate(), fiscalPeriod.getEndDate()).size() != 0) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.fiscalperiodnotempty")); + } + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + } + + /** + * Check if old financialperiod for a an entrybook are closed before bock the asked closedperiodicentrybook + * <p/> + * get all closedperiodicentrybook between the first financial period of fiscalperiod + * and the last financial period of the closedperiodicentrybook in param + * return the number + * <p/> + * get all blocked closedperiodicentrybook while his same period, return the number + * <p/> + * compare there + * + * FIXME echatellier 20120504 a quoi ca sert de recuperer un nombre + * et de le comparer avec un autre, c'est pas plus simple de verifier + * qu'il reste des ClosedPeriodicEntryBook non clos ? + */ + @Override + public void blockClosedPeriodicEntryBookRules(ClosedPeriodicEntryBook closedPeriodicEntryBook) throws LimaException { + super.blockClosedPeriodicEntryBookRules(closedPeriodicEntryBook); + + FinancialPeriod financialPeriod = closedPeriodicEntryBook.getFinancialPeriod(); + + try { + + // Get all closedperiod between for the period and entrybook + Date endDate = closedPeriodicEntryBook.getFinancialPeriod().getBeginDate(); + // FIXME echatellier 20120502 c'est pas un hack ca ? + // un period peut ne pas durer un mois + endDate = DateUtils.addMonths(endDate, -1); + + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + + //search fiscalperiod have financialperiod + FiscalPeriod fiscalPeriod = fiscalPeriodTopiaDao.findByFinancialPeriod(financialPeriod); + Date beginDate = fiscalPeriod.getBeginDate(); + // FIXME echatellier 20120502 quels est la rapport entre beginDate + // et endDate ? il ne provienent pas du même endroit + EntryBook entryBook = closedPeriodicEntryBook.getEntryBook(); + + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + + List<ClosedPeriodicEntryBook> closedPeriodicEntryBooks = + closedPeriodicEntryBookTopiaDao.findAllByEntryBookAndDates(entryBook, beginDate, endDate); + + // FIXME echatellier 20120504 juste un count suffit + int nbClosedPeriodicEntryBooks = closedPeriodicEntryBooks.size(); + + // Get all closed between for the period, entrybook and are blocked + closedPeriodicEntryBooks = closedPeriodicEntryBookTopiaDao.findAllByEntryBookAndDatesLocked(entryBook, beginDate, endDate); + int nbBlockedClosedPeriodicEntryBooks = + closedPeriodicEntryBooks.size(); + + //Check if the fiscal period to block is the oldest + if (nbClosedPeriodicEntryBooks != nbBlockedClosedPeriodicEntryBooks) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.antefinancialperiodnotblockedentrybook")); + } + + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AbstractLimaService.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,53 @@ +/* + * #%L + * Lima business + * + * $Id: AbstractLimaService.java 3409 2012-05-11 10:19:53Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaDaoHelper; +import org.chorem.lima.business.LimaInterceptor; + +/** + * Abstract code for all ejb services (get context, catch, finally...). + * + * @author chatellier + * @version $Revision: 3409 $ + */ +public abstract class AbstractLimaService { + + /** Logger. */ + protected static final Log log = LogFactory.getLog(AbstractLimaService.class); + + /** + * Return Dao helper to use in current thread. + * Defined by {@link LimaInterceptor}. + * + * @return dao helper + */ + protected LimaDaoHelper getDaoHelper() { + return LimaInterceptor.DAO_HELPER.get(); + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AccountServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,255 @@ +/* + * #%L + * Lima business + * + * $Id: AccountServiceImpl.java 3777 2014-04-14 07:29:08Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2010 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.ejb; + +import static org.nuiton.i18n.I18n.t; + +import java.util.Collections; +import java.util.List; + +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +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.api.AccountService; +import org.chorem.lima.business.utils.AccountComparator; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +/** + * Permet d'implémenter le Plan Comptable Général. + * Un compte ne peut être supprimé si il contient des écritures comptables. + * Un compte peut devenir père et avoir des comptes fils. Chaque compte créé doit + * renseigner si il appartient à un compte père avec le numéro de compte père. + * + * @author Rémi Chapelet + */ +@Stateless +@Remote(AccountService.class) +@TransactionAttribute +public class AccountServiceImpl extends AbstractLimaService implements AccountService { + + @Override + public long getAccountCount() throws LimaException { + long result; + + try { + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + result = AccountTopiaDao.count(); + } catch (TopiaException ex) { + throw new LimaException("Can't count", ex); + } + return result; + } + + + /** + * Permet de créer un nouveau compte dans le PCG de l'application. + * + * @param account account to create + * @throws LimaException + */ + @Override + public Account createAccount(Account account) throws LimaException { + + // check rules before create the account + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + accountingRules.createAccountRules(account); + + Account result; + + try { + // force uppercase account number + account.setAccountNumber(account.getAccountNumber().toUpperCase().trim()); + + // check if account number already exist + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + + if (AccountTopiaDao.existByNaturalId(account.getAccountNumber())) { + throw new LimaBusinessException( + t("lima-business.account.accountalreardyexist", + account.getAccountNumber())); + } + + //create it + result = AccountTopiaDao.create(account); + } catch (TopiaException ex) { + throw new LimaException("Can't create account", ex); + } + + return result; + } + + @Override + public Account getMasterAccount(String accountNumber) throws LimaException { + Account account = null; + try { + + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + + while (account == null && accountNumber.length() > 1) { + + accountNumber = accountNumber.substring(0, accountNumber.length() - 1); + account = AccountTopiaDao.findByAccountNumber(accountNumber); + } + + } catch (TopiaException ex) { + throw new LimaException("Can't get master account", ex); + } + return account; + } + + /** Permet d'obtenir un compte suivant son numero */ + @Override + public Account getAccountByNumber(String number) throws LimaException { + + Account account; + try { + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + account = AccountTopiaDao.findByAccountNumber(number); + } catch (Exception ex) { + throw new LimaException("Can't get master account", ex); + } + + return account; + } + + + /** Permet d'obtenir tous les comptes. */ + @Override + public List<Account> getAllAccounts() throws LimaException { + + List<Account> accountsList; + + try { + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + accountsList = AccountTopiaDao.findAll(); + Collections.sort(accountsList, new AccountComparator()); + + } catch (Exception ex) { + throw new LimaException("Can't get all accounts", ex); + } + + return accountsList; + } + + + /** Permet d'obtenir tout les comptes feuilles */ + @Override + public List<Account> getAllLeafAccounts() throws LimaException { + + List<Account> accountsList; + + try { + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + accountsList = AccountTopiaDao.findAllLeafAccounts(); + } catch (Exception ex) { + throw new LimaException("Can't get all leaf accounts", ex); + } + + return accountsList; + } + + /* + * @see org.chorem.lima.business.api.AccountService#getAllSubAccounts(org.chorem.lima.entity.Account) + */ + @Override + public List<Account> getAllSubAccounts(Account account) + throws LimaException { + List<Account> accountsList; + + try { + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + accountsList = AccountTopiaDao.findAllSubAccounts(account); + } catch (Exception ex) { + throw new LimaException("Can't get all sub accounts", ex); + } + + return accountsList; + } + + /** + * 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 Le compte à supprimer + * @throws LimaException + */ + @Override + public void removeAccount(Account account) throws LimaException { + + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + try { + + // Check rules for account if have entries + accountingRules.removeAccountRules(account); + + // remove account + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + Account accountToDelete = AccountTopiaDao.findByTopiaId(account.getTopiaId()); + AccountTopiaDao.delete(accountToDelete); + + } catch (TopiaException ex) { + throw new LimaException("Can't remove account", ex); + } + } + + /** + * Permet de modifier un compte sur son label. + * <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 + */ + @Override + public Account updateAccount(Account account) throws LimaException { + + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + Account result; + try { + // DAO + AccountTopiaDao AccountTopiaDao = getDaoHelper().getAccountTopiaDao(); + accountingRules.updateAccountRules(account); + result = AccountTopiaDao.update(account); + + } catch (Exception ex) { + throw new LimaException("Can't update account", ex); + } + + return result; + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ClosedPeriodicEntryBookServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ClosedPeriodicEntryBookServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ClosedPeriodicEntryBookServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,57 @@ +package org.chorem.lima.business.ejb; + +/* + * #%L + * Lima :: business + * $Id: ClosedPeriodicEntryBookServiceImpl.java 3768 2014-04-11 13:38:02Z dcosse $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2014 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% + */ + +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.ClosedPeriodicEntryBookService; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.FinancialPeriod; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +/** + * Created by davidcosse on 17/01/14. + */ +@Stateless +@Remote(ClosedPeriodicEntryBookService.class) +@TransactionAttribute +public class ClosedPeriodicEntryBookServiceImpl extends AbstractLimaService implements ClosedPeriodicEntryBookService { + @Override + public ClosedPeriodicEntryBook getByEntryBookAndFinancialPeriod(EntryBook entryBook, FinancialPeriod financialPeriod) { + ClosedPeriodicEntryBook result; + try { + ClosedPeriodicEntryBookTopiaDao accountTopiaDao = getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + result = accountTopiaDao.findByEntryBookAndFinancialPeriod(entryBook, financialPeriod); + } catch (TopiaException e) { + throw new LimaException("Can't find closed period entry book", e); + } + return result; + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/DocumentServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,994 @@ +/* + * #%L + * Lima business + * + * $Id: DocumentServiceImpl.java 3778 2014-04-15 16:09:41Z dcosse $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import com.google.common.base.Strings; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.pdfbox.examples.fdf.SetField; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.chorem.lima.beans.BalanceTrial; +import org.chorem.lima.beans.FinancialStatementAmounts; +import org.chorem.lima.beans.GeneralEntryBooksDatas; +import org.chorem.lima.beans.GeneralEntryBooksDatasImpl; +import org.chorem.lima.beans.ReportsDatas; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.DocumentService; +import org.chorem.lima.business.api.FinancialStatementService; +import org.chorem.lima.business.api.IdentityService; +import org.chorem.lima.business.api.ReportService; +import org.chorem.lima.business.api.VatStatementService; +import org.chorem.lima.business.utils.DocumentsEnum; +import org.chorem.lima.business.utils.EntryComparator; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountTopiaDao; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryTopiaDao; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialPeriodTopiaDao; +import org.chorem.lima.entity.Identity; +import org.chorem.lima.entity.VatStatement; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.EJB; +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.swing.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +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.t; + +/** + * TODO david: 17/01/14, Ce service doit être entièrement revue, !!! + */ +@Stateless +@Remote(DocumentService.class) +@TransactionAttribute +public class DocumentServiceImpl extends AbstractLimaService implements DocumentService { + + protected static final Log log = LogFactory.getLog(DocumentServiceImpl.class); + + @EJB + private IdentityService identityService; + + @EJB + private FinancialStatementService financialStatementService; + + @EJB + private ReportService reportService; + + @EJB + private VatStatementService vatStatementService; + + protected String path; + + public DocumentServiceImpl() { + path = LimaConfig.getInstance().getReportsDir().getAbsolutePath(); + + if (log.isDebugEnabled()) { + log.debug("Path : " + path); + } + + } + + @Override + public String createFinancialStatementsDocuments(Date beginDate, + Date endDate) throws LimaException { + + List<FinancialStatementAmounts> financialStatementAmounts = + financialStatementService.financialStatementReport(beginDate, endDate); + String financialReport = ""; + + try { + + financialReport = constructHtmlHeader(""); + + //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)); + int printedType = -1; + + //create pages + for (List<FinancialStatementAmounts> list : listList) { + if (!list.isEmpty()){ + String title = list.get(0).getLabel(); + int i = 0; + int n = list.size(); + printedType ++; + while (i < n) { + + financialReport += constructHeaderTitle(title, beginDate, endDate); + + String boldBegin = "<b>"; + String boldEnd = "</b>"; + financialReport += "<table border=\"1\" width=\"100%\" cellpadding=\"3\" cellspacing=\"0\">\n" + + "<tr align=\"center\">\n"; + + if (printedType == 0) { + String[] columnHeaderTable = {boldBegin+t("lima-business.document.label")+boldEnd, boldBegin+t("lima-business.document.grossamount")+boldEnd, + boldBegin+t("lima-business.document.provisiondeprecationamount")+boldEnd, boldBegin+t("lima-business.document.netamount")+boldEnd}; + financialReport += constructTableLine(columnHeaderTable); + } else if (printedType == 1) { + String[] columnHeaderTable = {boldBegin+t("lima-business.document.label")+boldEnd, boldBegin+t("lima-business.document.amount")+boldEnd}; + financialReport += constructTableLine(columnHeaderTable); + } else { + String[] columnHeaderTable = {boldBegin+t("lima-business.document.label")+boldEnd, boldBegin+t("lima-business.document.amount")+boldEnd}; + financialReport += constructTableLine(columnHeaderTable); + } + + for (FinancialStatementAmounts financialStatementAmount : list) { + + 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 (label == null) { + if (printedType == 0) { + String [] emptyColumn = {"","","",""}; + financialReport += constructTableLine(emptyColumn); + } else { + String [] emptyColumn = {"", ""}; + financialReport += constructTableLine(emptyColumn); + } + } else { + //cell1 + StringBuilder tab = new StringBuilder(); + for (int k = 0; k < level; k++) { + tab.append("\t"); + } + //Phrase phrase; + String tabLabel = ""; + if (financialStatementAmount.getHeader()) { + tabLabel = boldBegin + tab + label + boldEnd; + } else { + tabLabel = tab + label; + } + //cell2 + String grossAmountStr = ""; + if (!grossAmount.equals(BigDecimal.ZERO)) { + grossAmountStr = grossAmount.toString(); + } + + //cell 3 + String provisionDeprecationAmountStr = ""; + if (!provisionDeprecationAmount.equals(BigDecimal.ZERO)) { + provisionDeprecationAmountStr = provisionDeprecationAmount.toString(); + } + + //cell 4 + BigDecimal solde = grossAmount; + solde = solde.subtract(provisionDeprecationAmount); + String soldeStr = ""; + if (!solde.equals(BigDecimal.ZERO)) { + soldeStr = solde.toString(); + } + + if (printedType == 0) { + String [] columns = {tabLabel, grossAmountStr, provisionDeprecationAmountStr, soldeStr}; + financialReport += constructTableLine(columns); + } else /*if (printedType == 1)*/ { + String [] columns = {tabLabel, soldeStr}; + financialReport += constructTableLine(columns); + } + } + } + i = i + n; + financialReport += "</table>"; + } + } + } + financialReport += "</body>" + + "</html>"; + + } catch (Exception ex) { + log.error("Can't create document", ex); + } + return financialReport; + } + + //############## Ledger ############## + @Override + public String createLedgerDocuments(Date beginDate, + Date endDate) throws LimaException { + + List<Object> list = new ArrayList<Object>(); + String ledgerReport = constructHtmlHeader(t("lima-business.document.ledger")); + + if (beginDate != null && endDate != null) { + try { + String boldBegin = "<b>"; + String boldEnd = "</b>"; + + BalanceTrial balanceTrial = reportService.generateLedger(beginDate, endDate, null, true); + if (balanceTrial.getReportsDatas() != null) { + for (ReportsDatas reportsDatas : balanceTrial.getReportsDatas()) { + list.add(reportsDatas); + List<Entry> entries = reportsDatas.getListEntry(); + if (entries != null) { + Collections.sort(entries, new EntryComparator()); + list.addAll(entries); + } + } + } + + //create pages + int i = 0; + int n = list.size(); + + boolean even = true; + BigDecimal currentAmountDebit = new BigDecimal(0); + BigDecimal currentAmountCredit = new BigDecimal(0); + + while (i < n) { + + ledgerReport += constructHeaderTitle(t("lima-business.document.ledger"), beginDate, endDate); + + ledgerReport += "<table align=\"left\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\" style=\"font-size:13px;\" >\n"; + + String [] columnsNames = {t("lima-business.document.account"), t("lima-business.document.debit"), + t("lima-business.document.credit"), t("lima-business.document.solde")}; + ledgerReport += constructTableHeader(columnsNames); + ledgerReport += "<tbody>\n"; + + int indexEntry = -1; + + for (Object object : list) { + if (object instanceof ReportsDatas) { + if (indexEntry != -1) { + indexEntry = -1; + ledgerReport += "</tbody></table>" + + "</td>" + + "</tr>"; + } + 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(); + + String [] columnsTable = {accountS, + amountDebit.toString(), amountCredit.toString(), + amountDebit.subtract(amountCredit).toString()}; + ledgerReport += constructTableHeader(columnsTable); + + } else { + indexEntry++; + 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.isDebit()) { + amountDebit = entry.getAmount(); + } else { + amountCredit = entry.getAmount(); + } + + ledgerReport +="<tr>"; + if (indexEntry == 0) { + ledgerReport += "<td><table align=\"right\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\" style=\"font-size:13px;\" >\n"; + String [] columnsEntry = {t("lima-business.document.date"), + t("lima-business.document.entrybook"), t("lima-business.document.voucher"), + t("lima-business.document.description"), t("lima-business.document.debit"), + t("lima-business.document.credit"), t("lima-business.document.solde")}; + ledgerReport += constructTableHeader(columnsEntry); + ledgerReport += "<tbody>"; + } + + String [] columnsTable = {t("lima-business.document.dateformat",entry.getFinancialTransaction().getTransactionDate()), + entryBookCode, entry.getVoucher(), entry.getDescription(), + amountDebit.toString(), amountCredit.toString(), amountDebit.subtract(amountCredit).toString()}; + ledgerReport += constructTableLine(columnsTable, even); + even = !even; + } + } + + // close inner + ledgerReport += "</tbody></table>" + + "</td>" + + "</tr>"; + + for (Object objectList : list) { + if (objectList instanceof Entry) { + Entry entry = (Entry) objectList; + if (entry.isDebit()) { + currentAmountDebit = currentAmountDebit.add(entry.getAmount()); + } else { + currentAmountCredit = currentAmountCredit.add(entry.getAmount()); + } + } + } + + i = i + n; + } + //final amounts + String [] columnsTable = { boldBegin + t("lima-business.document.amounts") + boldEnd, + boldBegin + currentAmountDebit.toString() + boldEnd, boldBegin + currentAmountCredit.toString() + boldEnd, + boldBegin + currentAmountDebit.subtract(currentAmountCredit).toString() + boldEnd}; + ledgerReport += constructTableLine(columnsTable, even); + + + ledgerReport += "</tbody></table></body>\n</html>"; + } catch (Exception ex) { + log.error("Can't create document", ex); + } + } + return ledgerReport; + } + + @Override + public String createEntryBooksDocuments(Date beginDate, + Date endDate) throws LimaException { + String entryBookReport; + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMMM yyyy"); + try { + entryBookReport = constructHtmlHeader(t("lima-business.document.entrybooks")); + + if (beginDate != null && endDate != null) { + + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = + getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + + //Split list by financialstatement type + List<ClosedPeriodicEntryBook> closedPeriodicEntryBookList = + closedPeriodicEntryBookTopiaDao.findAllByDates(beginDate, endDate); + + String journal = ""; + for (ClosedPeriodicEntryBook closedPeriodicEntryBook : closedPeriodicEntryBookList) { + + // TODO echatellier 20120509, was not about only + // balanced transaction here, normal ? + List<Entry> entries = entryTopiaDao.findAllEntryByDateForEntryBook(closedPeriodicEntryBook.getEntryBook(), + closedPeriodicEntryBook.getFinancialPeriod().getBeginDate(), + closedPeriodicEntryBook.getFinancialPeriod().getEndDate()); + + if (entries.size() > 0) { + List<Object[]> results = entryTopiaDao.getDebitCreditOfTransaction(closedPeriodicEntryBook.getEntryBook(), + closedPeriodicEntryBook.getFinancialPeriod().getBeginDate(), + closedPeriodicEntryBook.getFinancialPeriod().getEndDate()); + BigDecimal debit = BigDecimal.ZERO; + BigDecimal credit = BigDecimal.ZERO; + int nbAmount = results.size(); + 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]; + } else { + credit = (BigDecimal) results.get(0)[1]; + } + } + + String subTitleSecPart = t("lima-business.document.date") + " : " + + simpleDateFormat.format(closedPeriodicEntryBook.getFinancialPeriod().getBeginDate()); + if (closedPeriodicEntryBook.getEntryBook() != null) { + String label = Strings.isNullOrEmpty(closedPeriodicEntryBook.getEntryBook().getLabel()) ? "-" :closedPeriodicEntryBook.getEntryBook().getLabel(); + if (!journal.equals(label)) { + entryBookReport += constructSubTitleHtml(t("lima-business.document.entrybook") + + " : " + label, + subTitleSecPart); + journal = label; + } else { + entryBookReport += constructSubTitleHtml("", subTitleSecPart); + } + } + + entryBookReport += "<table border=\"1\" width=\"100%\" cellpadding=\"3\" cellspacing=\"0\">\n" + + "<tr align=\"center\">\n"; + + String [] columnNames = {t("lima-business.document.date"), t("lima-business.document.accountnumber"), + t("lima-business.document.voucher"), t("lima-business.document.description"), + t("lima-business.document.debit"), + t("lima-business.document.credit")}; + + entryBookReport += constructTableHeader(columnNames); + + for (Entry entry : entries) { + String numaccount = null; + if (entry.getAccount() != null) { + numaccount = entry.getAccount().getAccountNumber(); + } + String [] columnData = {t("lima-business.document.dateformat", entry.getFinancialTransaction().getTransactionDate()), + (StringUtils.isBlank(numaccount)?"":numaccount), (StringUtils.isBlank(entry.getVoucher())?"":entry.getVoucher()), + (StringUtils.isBlank(entry.getDescription())?"":entry.getDescription()), + (entry.isDebit() ? entry.getAmount() : BigDecimal.ZERO).toString(), + (entry.isDebit() ? BigDecimal.ZERO : entry.getAmount()).toString()}; + + entryBookReport += constructTableHeader(columnData); + } + String [] columnDataTotal = {"", "", "", t("lima-business.document.amounts"), debit.toString(), credit.toString()}; + entryBookReport += constructTableHeader(columnDataTotal); + entryBookReport += "</table></p>\n"; + } + } + entryBookReport += "</body>\n</html>"; + } + } catch (Exception ex) { + throw new LimaException("Can't create document", ex); + } + + return entryBookReport; + } + + //############## Balance ############## + + @Override + public String createBalanceDocuments(Date beginDate, + Date endDate) throws LimaException { + + BalanceTrial balanceTrial = + reportService.generateBalanceTrial(beginDate, endDate, null, false, true); + + List<ReportsDatas> list = (List<ReportsDatas>) balanceTrial.getReportsDatas(); + + String balanceReport = constructHtmlHeader(t("lima-business.document.balance")); + + if (beginDate != null && endDate != null) { + try{ + BigDecimal currentAmountDebit = new BigDecimal(0); + BigDecimal currentAmountCredit = new BigDecimal(0); + BigDecimal currentSoldeDebit = new BigDecimal(0); + BigDecimal currentSoldeCredit = new BigDecimal(0); + + //create pages + int i = 0; + int n = list.size(); + + boolean even = true; + while (i < n) { + + balanceReport += constructHeaderTitle(t("lima-business.document.balance"), beginDate, endDate); + + balanceReport += "<table border=\"1\" width=\"100%\" cellpadding=\"3\" cellspacing=\"0\">\n"; + + String [] columnsNames = {t("lima-business.document.accountnumber"), t("lima-business.document.description"), + t("lima-business.document.movementdebit"), t("lima-business.document.movementcredit"), + t("lima-business.document.soldedebit"), t("lima-business.document.soldecredit")}; + balanceReport += constructTableHeader(columnsNames); + balanceReport += "\t\t<tbody>\n"; + + for (ReportsDatas reportsDatas : list) { + String soldeDebit = String.valueOf(reportsDatas.getSoldeDebit() ? reportsDatas.getAmountSolde() : 0); + String soldeCredit = String.valueOf(reportsDatas.getSoldeDebit() ? 0 : reportsDatas.getAmountSolde()); + + String [] columnsBalanceAmount = {reportsDatas.getAccount().getAccountNumber(), reportsDatas.getAccount().getLabel(), + reportsDatas.getAmountDebit().toString(), reportsDatas.getAmountCredit().toString(), + soldeDebit, soldeCredit}; + balanceReport += constructTableLine(columnsBalanceAmount, even); + even = !even; + + currentAmountDebit = currentAmountDebit.add(reportsDatas.getAmountDebit()); + currentAmountCredit = currentAmountCredit.add(reportsDatas.getAmountCredit()); + if (reportsDatas.getSoldeDebit()) { + currentSoldeDebit = currentSoldeDebit.add(reportsDatas.getAmountSolde()); + } else { + currentSoldeCredit = currentSoldeCredit.add(reportsDatas.getAmountSolde()); + } + } + + i = i + n; + } + //final amounts + String boldBegin = "<b>"; + String boldEnd = "</b>"; + String [] columnsBalanceAmount = {"", boldBegin + t("lima-business.document.amounts") + boldEnd, + boldBegin + currentAmountDebit.toString() + boldEnd, boldBegin + currentAmountCredit.toString() + boldEnd, + boldBegin + currentSoldeDebit.toString() + boldEnd,boldBegin + currentSoldeCredit.toString() + boldEnd}; + balanceReport += constructTableLine(columnsBalanceAmount, even); + balanceReport += "</tbody></table>\n"; + + + balanceReport += "</body>\n</html>"; + } catch (Exception ex) { + log.error("Can't create document", ex); + } + } + + return balanceReport; + } + + //############## General EntryBook ############## + + + @Override + public String createGeneralEntryBooksDocuments(Date beginDate, + Date endDate) throws LimaException { + + String entryBookReport; + try { + entryBookReport = constructHtmlHeader(t("lima-business.document.entrybook")); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMMM yyyy"); + + if (beginDate != null && endDate != null) { + String subTitle = t("lima-business.document.period1") + + simpleDateFormat.format(beginDate) + " " + + t("lima-business.document.period2") + + simpleDateFormat.format(endDate); + entryBookReport += constructSubTitleHtml(subTitle); + + FinancialPeriodTopiaDao financialPeriodTopiaDao = + getDaoHelper().getFinancialPeriodTopiaDao(); + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = + getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + + List<FinancialPeriod> financialPeriods = + financialPeriodTopiaDao.findByDates(beginDate, endDate); + + List<GeneralEntryBooksDatas> list = new ArrayList<GeneralEntryBooksDatas>(); + BigDecimal amountDebit = new BigDecimal(0); + BigDecimal amountCredit = new BigDecimal(0); + for (FinancialPeriod financialPeriod : financialPeriods) { + List<ClosedPeriodicEntryBook> closedPeriodicEntryBookList = + closedPeriodicEntryBookTopiaDao.findAllByDates( + financialPeriod.getBeginDate(), financialPeriod.getEndDate()); + + BigDecimal subAmountDebit = new BigDecimal(0); + BigDecimal subAmountCredit = new BigDecimal(0); + for (ClosedPeriodicEntryBook closedPeriodicEntryBook : closedPeriodicEntryBookList) { + + BigDecimal debit = BigDecimal.ZERO; + BigDecimal credit = BigDecimal.ZERO; + + List<Object[]> results = entryTopiaDao.getDebitCreditOfTransaction(closedPeriodicEntryBook.getEntryBook(), + closedPeriodicEntryBook.getFinancialPeriod().getBeginDate(), + closedPeriodicEntryBook.getFinancialPeriod().getEndDate()); + + int nbAmount = results.size(); + 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]; + } else { + credit = (BigDecimal) results.get(0)[1]; + } + } + GeneralEntryBooksDatas generalEntryBooksDatas = + new GeneralEntryBooksDatasImpl(); + generalEntryBooksDatas.setCode( + closedPeriodicEntryBook.getEntryBook().getCode()); + generalEntryBooksDatas.setDescription( + closedPeriodicEntryBook.getEntryBook().getLabel()); + + if (log.isDebugEnabled()) { + log.debug("Entrybook code added : " + closedPeriodicEntryBook.getEntryBook().getCode()); + log.debug("Entrybook desc. added : " + closedPeriodicEntryBook.getEntryBook().getLabel()); + } + + generalEntryBooksDatas.setPeriod(financialPeriod.getBeginDate()); + generalEntryBooksDatas.setCredit(credit); + generalEntryBooksDatas.setDebit(debit); + list.add(generalEntryBooksDatas); + subAmountCredit = subAmountCredit.add(credit); + subAmountDebit = subAmountDebit.add(debit); + } + GeneralEntryBooksDatas generalEntryBooksDatas = + new GeneralEntryBooksDatasImpl(); + generalEntryBooksDatas.setSubAmount(true); + generalEntryBooksDatas.setCredit(subAmountCredit); + generalEntryBooksDatas.setDebit(subAmountDebit); + generalEntryBooksDatas.setPeriod(financialPeriod.getBeginDate()); + list.add(generalEntryBooksDatas); + amountCredit = amountCredit.add(subAmountCredit); + amountDebit = amountDebit.add(subAmountDebit); + } + GeneralEntryBooksDatas generalEntryBooksDatas = + new GeneralEntryBooksDatasImpl(); + generalEntryBooksDatas.setAmount(true); + generalEntryBooksDatas.setCredit(amountCredit); + generalEntryBooksDatas.setDebit(amountDebit); + list.add(generalEntryBooksDatas); + + entryBookReport += "<table border=\"1\" width=\"100%\" cellpadding=\"3\" cellspacing=\"0\">\n"; + + String[] columnNames = {t("lima-business.document.entrybook"), t("lima-business.document.label"), + t("lima-business.document.date"), t("lima-business.document.debit"), + t("lima-business.document.credit")}; + + entryBookReport += constructTableHeader(columnNames); + entryBookReport += "\t\t<tbody>\n"; + String entryBookCode = ""; + boolean even = true; + + for (GeneralEntryBooksDatas generalEntryBooksDataInList : list) { + if (!generalEntryBooksDataInList.getDebit().equals(BigDecimal.ZERO) && !generalEntryBooksDataInList.getCredit().equals(BigDecimal.ZERO)) { + if (!generalEntryBooksDataInList.getAmount() && !generalEntryBooksDataInList.getSubAmount()) { + String code; + String description; + if (!entryBookCode.equals(generalEntryBooksDataInList.getCode())) { + entryBookCode = generalEntryBooksDataInList.getCode(); + code = entryBookCode; + description = Strings.isNullOrEmpty(generalEntryBooksDataInList.getDescription()) == true ? "" : generalEntryBooksDataInList.getDescription(); + } else { + code = ""; + description = ""; + } + String[] columnData = {code, description, + t("lima-business.document.monthformat", generalEntryBooksDataInList.getPeriod()), + generalEntryBooksDataInList.getDebit().toString(), + generalEntryBooksDataInList.getCredit().toString()}; + entryBookReport += constructTableLine(columnData, even); + even = !even; + } else { + String amount; + if (generalEntryBooksDataInList.getAmount()) { + amount = t("lima-business.document.amounts"); + } else { + amount = t("lima-business.document.amountsperiod", generalEntryBooksDataInList.getPeriod()); + } + String[] columnDataTotal = {"", "", (StringUtils.isBlank(amount)?"":amount), + generalEntryBooksDataInList.getDebit().toString(), + generalEntryBooksDataInList.getCredit().toString()}; + entryBookReport += constructTableLine(columnDataTotal, even); + even = !even; + entryBookCode = ""; + } + } + } + entryBookReport += "\t\t</tbody>\n" + + "\t</table>\n" + + "</body>\n</html>"; + } + } catch (Exception ex) { + throw new LimaException("Can't generate document", ex); + } + return entryBookReport; + } + + //############## VAT ############## + + @Override + public void createVatDocuments(Date beginDate, + Date endDate, + String autocomplete) throws LimaException { + + String filePath = path + File.separator + + DocumentsEnum.VAT.getFileName() + ".pdf"; + + String path = LimaConfig.getInstance().getReportsDir().getAbsolutePath(); + + String filePathDefault = path + File.separator + + 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"); + } + } else { + try { + reportsStream = new FileInputStream(filePathDefault); + } catch (FileNotFoundException eee) { + throw new LimaException("Could not find such file " + + filePathDefault, eee); + } + } + + try { + + // load the document + doc = PDDocument.load(reportsStream); + + if (autocomplete != null) { + if (log.isDebugEnabled()) { + log.debug("autocomplete: " + autocomplete); + } + if (autocomplete.equals("true")) { + + SetField fields = new SetField(); + + //search for all VAT Statements from the report + List<VatStatement> vatStatementsList = vatStatementService.getAllVatStatements(); + if (log.isDebugEnabled()) { + log.debug("vatStatementsList.size() : " + vatStatementsList.size()); + } + 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 + if (vatStatement.getBoxName() != null && !vatStatement.isHeader()) { + if (log.isDebugEnabled()) { + log.debug("Set field..."); + } + fields.setField(doc, vatStatement.getBoxName(), amount.toString()); + } + } + } + } + + // save the updated document to the new file and close + doc.save(filePath); + doc.close(); + + } catch (Exception ex) { + throw new LimaException("Can't create document", ex); + } + } + + @Override + public String createAccountDocument(Date beginDate, Date endDate, String account) throws LimaException { + + String accountReport = null; + + try { + + AccountTopiaDao accountTopiaDao = getDaoHelper().getAccountTopiaDao(); + Account accountFormat = accountTopiaDao.findByTopiaId(account); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMMM yyyy"); + + accountReport = constructHtmlHeader(t("lima.reports.accounts")); + + ReportsDatas results; + + if (beginDate != null && endDate != null && accountFormat != null) { + + String subTitleFirstpart = t("lima.ui.fiscalperiod.fiscalperiod") + " : " + simpleDateFormat.format(beginDate) + " - " + simpleDateFormat.format(endDate); + String subTitleSecPart = t("lima.ui.financialtransaction.account") + " : " + accountFormat.getAccountNumber() + " - " + accountFormat.getLabel(); + accountReport += constructSubTitleHtml(subTitleFirstpart, subTitleSecPart); + + results = reportService.generateAccountsReports(accountFormat, true, + beginDate, endDate); + List<Entry> entries = results.getListEntry(); + + String[] columnNames = {t("lima.table.number"), t("lima.table.date"), t("lima.table.entrybook"), + t("lima.table.voucher"), t("lima.table.description"), t("lima.table.letter"), + t("lima.table.debit"), t("lima.table.credit")}; + + accountReport += "\t<table border=\"1\" width=\"100%\" cellpadding=\"3\" cellspacing=\"0\">\n"; + + accountReport += constructTableHeader(columnNames); + accountReport += "\t\t<tbody>\n"; + + boolean even = true; + for(Entry entry : entries) { + + String accountNumber = entry.getAccount().getAccountNumber(); + String transactionDate = simpleDateFormat.format(entry.getFinancialTransaction().getTransactionDate()); + String code = ""; + if (entry.getFinancialTransaction().getEntryBook() != null) { + code = entry.getFinancialTransaction().getEntryBook().getCode(); + } + String voucher = entry.getVoucher(); + String description = entry.getDescription(); + String lettering = entry.getLettering(); + + + String[] columnData = {(StringUtils.isBlank(accountNumber)?"":accountNumber), (StringUtils.isBlank(transactionDate)?"":transactionDate), + (StringUtils.isBlank(code)?"":code), (StringUtils.isBlank(voucher)?"":voucher), + (StringUtils.isBlank(description)?"":description), (StringUtils.isBlank(lettering)?"":lettering), + (entry.isDebit() ? entry.getAmount() : BigDecimal.ZERO).toString(), + (entry.isDebit() ? BigDecimal.ZERO : entry.getAmount()).toString()}; + + accountReport += constructTableLine(columnData, even); + even = !even; + } + + accountReport += "\t\t</tbody>\n\t</table>\n" + + "</body>\n"; + + } else { + JOptionPane.showMessageDialog(null, t("lima.reports.account.noaccount"), t("lima.reports.account.noaccounttitle"), JOptionPane.INFORMATION_MESSAGE); + } + + accountReport += "</html>"; + + }catch (TopiaException e) { + log.error("Can't find object", e); + } + catch (Exception e) { + throw new LimaException("Can't create document", e); + } + + return accountReport; + } + + protected String constructHtmlHeader(String title) { + String head = "<!DOCTYPE html>\n" + + "<html>\n" + + "<head>\n" + + "\t<meta charset=\"UTF-8\" />\n" + + "\t<title>" + title + "</title>\n" + + "</head>\n" + + "<body>\n" + + "\t<h1>" + title + "</h1>\n"; + return head; + } + + protected String constructSubTitleHtml(String subTitle) { + return "\t<h2>" + subTitle + "</h2>\n"; + } + + protected String constructSubTitleHtml(String subTitleFirstpart, String subTitleSecPart) { + String subTitle = "\t<h2>\n" + + subTitleFirstpart + + "<br/>\n" + + subTitleSecPart + + "</h2>\n"; + + return subTitle; + } + + protected String constructTableHeader(String[] columnsNames) { + String header = "\t\t<thead>\n\t\t\t<tr>\n"; + for (String name : columnsNames) { + header += "\t\t\t\t<th>" + name + "</th>\n"; + } + header += "\t\t\t</tr>\t\t\n</thead>\n"; + return header; + } + + protected String constructTableLine(String[] cells, boolean even) { + String style = even ? "line_even" : "line_odd"; + String line = "\t\t<tr class=\"" + style + "\">\n"; + for (String cell : cells) { + line += "\t\t\t<td>" + cell + "</td>\n"; + } + line += "\t\t</tr>\n"; + return line; + } + + protected String constructTableLine(String[] cells) { + String line = "\t\t<tr>\n"; + for (String cell : cells) { + line += "\t\t\t<td>" + cell + "</td>\n"; + } + line += "\t\t</tr>\n"; + return line; + } + + protected String constructHeaderTitle(String title, Date beginDate, Date endDate) { + String headerTitle; + Identity identity = identityService.getIdentity(); + + headerTitle = "<table>" + + "<thead> " + + "<tr><th>" + title + + "</th></tr>" + + "</thead>" + + "<tr> " + + "<td>" + + "<table align=\"left\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\" style=\"font-size:13px;\" >\n" + + "<tr>\n"; + + String boldItalicBegin = "<b>" + "<i>"; + String boldItalicEnd = "</i>" + "</b>"; + + if (identity != null) { + String [] columnsNameSociety = {boldItalicBegin + t("lima-business.document.society") + boldItalicEnd, + "<i>" + (StringUtils.isNotEmpty(identity.getName()) ? identity.getName() : " - ") + "</i>", }; + headerTitle += constructTableLine(columnsNameSociety); + + String [] columnsDescription = {boldItalicBegin + t("lima-business.document.description") + boldItalicEnd, + "<i>" + (StringUtils.isNotEmpty(identity.getDescription()) ? identity.getDescription() : " - ") + "</i>", }; + headerTitle += constructTableLine(columnsDescription); + + String [] columnsAdressOne = {boldItalicBegin + t("lima-business.document.adress") + boldItalicEnd, + "<i>" + (StringUtils.isNotEmpty(identity.getAddress()) ? identity.getAddress() : " - ") + "</i>", }; + headerTitle += constructTableLine(columnsAdressOne); + + String [] columnsAdressTwo = {boldItalicBegin + t("lima-business.document.adresssuite") + boldItalicEnd, + "<i>" + (StringUtils.isNotEmpty(identity.getAddress2()) ? identity.getAddress2() : " - ") + "</i>", }; + headerTitle += constructTableLine(columnsAdressTwo); + + String [] columnsZipCode = {boldItalicBegin + t("lima-business.document.zipcode") + boldItalicEnd, + "<i>" + (StringUtils.isNotEmpty(identity.getZipCode()) ? identity.getZipCode() : " - ") + "</i>", }; + headerTitle += constructTableLine(columnsZipCode); + + String [] columnsCity = {boldItalicBegin + t("lima-business.document.city") + boldItalicEnd, + "<i>" + (StringUtils.isNotEmpty(identity.getCity()) ? identity.getCity() : " - ") + "</i>", }; + headerTitle += constructTableLine(columnsCity); + + String [] columnsBusinessNumber = {boldItalicBegin + t("lima-business.document.businessnumber") + + boldItalicEnd, "<i>" + (StringUtils.isNotEmpty(identity.getBusinessNumber()) ? identity.getBusinessNumber() : " - ") + "</i>"}; + headerTitle += constructTableLine(columnsBusinessNumber); + + String [] columnsClassifCode = {boldItalicBegin + t("lima-business.document.classificationcode") + + boldItalicEnd, "<i>" + (StringUtils.isNotEmpty(identity.getClassificationCode()) ? identity.getClassificationCode() : " - ") + "</i>"}; + headerTitle += constructTableLine(columnsClassifCode); + + String [] columnsVatNumber = {boldItalicBegin + t("lima-business.document.vatnumber") + boldItalicEnd, + "<i>" + (StringUtils.isNotEmpty(identity.getVatNumber()) ? identity.getVatNumber() : " - ") + "</i>", }; + headerTitle += constructTableLine(columnsVatNumber); + } + + String [] columnsPeriodOne = {boldItalicBegin + t("lima-business.document.period1") + boldItalicEnd, "<i>" + + t("lima-business.document.period1format", beginDate)+ "</i>"}; + headerTitle += constructTableLine(columnsPeriodOne); + + headerTitle += "<tr>\n"; + String [] columnsPeriodTwo = {boldItalicBegin + t("lima-business.document.period2") + boldItalicEnd, "<i>" + + t("lima-business.document.period2format", endDate)+ "</i>"}; + headerTitle += constructTableLine(columnsPeriodTwo); + + headerTitle += "</table>" + + "</td>" + + "</table>"; + + return headerTitle; + } + +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryBookServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,198 @@ +/* + * #%L + * Lima business + * + * $Id: EntryBookServiceImpl.java 3780 2014-05-05 16:28:39Z dcosse $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +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.api.EntryBookService; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.ClosedPeriodicEntryBookImpl; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryBookTopiaDao; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialPeriodTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * Implémente la fonction multi-EntryBook. Il est possible de créer ici le + * EntryBook des ventes, le EntryBook des achats, etc. + * + * @author Rémi Chapelet + */ +@Stateless +@Remote(EntryBookService.class) +@TransactionAttribute +public class EntryBookServiceImpl extends AbstractLimaService implements EntryBookService { + + @Override + public EntryBook createEntryBook(EntryBook entryBook) + throws LimaException { + + EntryBook result = null; + try { + + // check if entrybook with is name already exist + EntryBookTopiaDao entryBookTopiaDao = getDaoHelper().getEntryBookTopiaDao(); + result = + entryBookTopiaDao.findByCode(entryBook.getCode()); + if (result != null) { + log.error( + t("lima-business.entrybook.entrybookalreadyexist", + entryBook.getCode())); + } else { + // creation du EntryBook + result = entryBookTopiaDao.create(entryBook); + + //create ClosedPeriodicEntryBook for all unblocked financial period + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = + getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + FinancialPeriodTopiaDao financialPeriodTopiaDao = + getDaoHelper().getFinancialPeriodTopiaDao(); + // for all unblocked financialperiod + for (FinancialPeriod financialPeriod : financialPeriodTopiaDao.findAllByLocked(false)) { + + //new closed periodic entrybook + ClosedPeriodicEntryBook closedPeriodicEntryBook = + new ClosedPeriodicEntryBookImpl(); + // set entrybook + closedPeriodicEntryBook.setEntryBook(entryBook); + // set financial period + closedPeriodicEntryBook.setFinancialPeriod(financialPeriod); + // create it + closedPeriodicEntryBookTopiaDao.create(closedPeriodicEntryBook); + } + } + + } catch (TopiaException ex) { + throw new LimaException("Can't create entry book", ex); + } + return result; + } + + @Override + public List<EntryBook> getAllEntryBooks() throws LimaException { + + List<EntryBook> entryBooksList; + + try { + // check if entrybook with is name already exist + EntryBookTopiaDao entryBookTopiaDao = getDaoHelper().getEntryBookTopiaDao(); + entryBooksList = entryBookTopiaDao.findAll(); + } catch (Exception ex) { + throw new LimaException("Can't get entry books", ex); + } + + return entryBooksList; + } + + @Override + public EntryBook updateEntryBook(EntryBook entryBook) throws LimaException { + + EntryBook result; + try { + + EntryBookTopiaDao entryBookTopiaDao = getDaoHelper().getEntryBookTopiaDao(); + + // creation du EntryBook + result = entryBookTopiaDao.update(entryBook); + + } catch (Exception ex) { + throw new LimaException("Can't update entry book", ex); + } + + return result; + } + + @Override + public void removeEntryBook(EntryBook entryBook) throws LimaException { + + // check rule + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + accountingRules.removeEntryBookRules(entryBook); + + try { + + // re-attach to current transaction + EntryBookTopiaDao entryBookTopiaDao = getDaoHelper().getEntryBookTopiaDao(); + EntryBook localEntryBook = entryBookTopiaDao.findByTopiaId(entryBook.getTopiaId()); + + // delete all ClosedPeriodicEntryBook from this EntryBook + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = + getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + List<ClosedPeriodicEntryBook> closedPeriodicEntryBooks = + closedPeriodicEntryBookTopiaDao.findAllByEntryBook(localEntryBook); + for (ClosedPeriodicEntryBook closedPeriodicEntryBook : closedPeriodicEntryBooks) { + if (log.isDebugEnabled()) { + log.debug("Deleting closed " + closedPeriodicEntryBook.getTopiaId()); + } + + // fix : ObjectDeletedException: deleted object would be re-saved by cascade + closedPeriodicEntryBook.getEntryBook().removeFinancialPeriodClosedPeriodicEntryBook(closedPeriodicEntryBook); + closedPeriodicEntryBook.getFinancialPeriod().removeEntryBookClosedPeriodicEntryBook(closedPeriodicEntryBook); + + closedPeriodicEntryBookTopiaDao.delete(closedPeriodicEntryBook); + } + + // delete entry book + entryBookTopiaDao.delete(localEntryBook); + + } catch (Exception ex) { + throw new LimaException("Can't remove entry book", ex); + } + } + + /* + * @see org.chorem.lima.business.ejbinterface.EntryBookService#getEntryBookByCode(java.lang.String) + */ + @Override + public EntryBook getEntryBookByCode(String code) throws LimaException { + + EntryBook entryBook; + + try { + EntryBookTopiaDao entryBookTopiaDao = getDaoHelper().getEntryBookTopiaDao(); + + // creation du EntryBook + entryBook = entryBookTopiaDao.findByCode(code); + + } catch (Exception ex) { + throw new LimaException("Can't get entry book", ex); + } + + return entryBook; + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,56 @@ +package org.chorem.lima.business.ejb; + +/* + * #%L + * Lima :: business + * $Id: EntryServiceImpl.java 3768 2014-04-11 13:38:02Z dcosse $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2014 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% + */ + +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.EntryService; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +/** + * Created by davidcosse on 17/01/14. + */ +@Stateless +@Remote(EntryService.class) +@TransactionAttribute +public class EntryServiceImpl extends AbstractLimaService implements EntryService { + + @Override + public Entry createEntry(Entry entry) { + + try { + EntryTopiaDao entryDao = getDaoHelper().getEntryTopiaDao(); + entryDao.create(entry); + } catch (TopiaException e) { + throw new LimaException("Can't create entry", e); + } + return null; + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ExportServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,732 @@ +/* + * #%L + * Lima business + * + * $Id: ExportServiceImpl.java 3781 2014-05-06 09:22:03Z dcosse $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import au.com.bytecode.opencsv.CSVWriter; +import org.apache.commons.lang3.StringUtils; +import org.chorem.lima.FinancialStatementWayEnum; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.EntryBookService; +import org.chorem.lima.business.api.ExportService; +import org.chorem.lima.business.api.ExportServiceLocal; +import org.chorem.lima.business.utils.ImportExportEntityEnum; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountTopiaDao; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryBookTopiaDao; +import org.chorem.lima.entity.FinancialStatement; +import org.chorem.lima.entity.FinancialStatementTopiaDao; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionTopiaDao; +import org.chorem.lima.entity.FiscalPeriod; +import org.chorem.lima.entity.FiscalPeriodTopiaDao; +import org.chorem.lima.entity.Identity; +import org.chorem.lima.entity.IdentityTopiaDao; +import org.chorem.lima.entity.VatStatement; +import org.chorem.lima.entity.VatStatementTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.EJB; +import javax.ejb.Local; +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +import java.io.IOException; +import java.io.StringWriter; +import java.text.SimpleDateFormat; +import java.util.List; + +/** + * CSV import export service. + * + * @version $Revision: 3781 $ + * <p/> + * Last update : $Date: 2014-05-06 11:22:03 +0200 (mar. 06 mai 2014) $ + * By : $Author: dcosse $ + */ +@Stateless +@Remote(ExportService.class) +@Local(ExportServiceLocal.class) +@TransactionAttribute +public class ExportServiceImpl extends AbstractLimaService implements ExportService, ExportServiceLocal { + + private static final SimpleDateFormat SDATEFORMAT = + new SimpleDateFormat("dd,MM,yyyy HH:mm:ss"); + + protected final String DATE_PATTERN = "dd/MM/yyyy"; + + @EJB + private EntryBookService entryBookService; + + //############## EXPORT EBP + + /** + * Export entries to EBP + * Structure example : DatEcr,Journal,Compte,Libelle,Piece,Debit,Credit,Lettre + * 01/01/2013,AN,101,Capital,1,0,100000.00,C + */ + @Override + public String exportEntriesAsEBP() throws LimaException { + SimpleDateFormat epbDateFormat = new SimpleDateFormat(DATE_PATTERN); + StringWriter out = new StringWriter(); + CSVWriter csvWriter = null; + + try { + csvWriter = new CSVWriter(out, + CSVWriter.DEFAULT_SEPARATOR, + CSVWriter.NO_QUOTE_CHARACTER); + + //export entries + FinancialTransactionTopiaDao financialTransactionTopiaDao = + getDaoHelper().getFinancialTransactionTopiaDao(); + List<FinancialTransaction> listFinancialTransaction = + financialTransactionTopiaDao.findAll(); + + String[] nextLine = new String[8]; + + // Add the header line + if (!listFinancialTransaction.isEmpty()) { + nextLine[0] = "DatEcr"; + nextLine[1] = "Journal"; + nextLine[2] = "Compte"; + nextLine[3] = "Libelle"; + nextLine[4] = "Piece"; + nextLine[5] = "Debit"; + nextLine[6] = "Credit"; + nextLine[7] = "Lettre"; + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + + String date, debitcredit, debit, credit, entrybookCode, accountNumber; + EntryBook entryBook; + Account account; + + // For all financialTransaction + for (FinancialTransaction financialTransaction : listFinancialTransaction) { + date = epbDateFormat.format(financialTransaction.getTransactionDate()); + + entryBook = financialTransaction.getEntryBook(); + + entrybookCode = entryBook == null ? "" : entryBook.getCode(); + + for (Entry entry : financialTransaction.getEntry()) { + account = entry.getAccount(); + + if (account != null) { + accountNumber = entry.getAccount().getAccountNumber(); + } else { + accountNumber = ""; + } + + debit = "0"; + credit = "0"; + if (entry.isDebit()) { + debitcredit = "D"; + debit = entry.getAmount().toString(); + } else { + debitcredit = "C"; + credit = entry.getAmount().toString(); + } + + nextLine[0] = date; + nextLine[1] = entrybookCode; + nextLine[2] = accountNumber; + nextLine[3] = StringUtils.remove(entry.getDescription(), ","); + nextLine[4] = entry.getVoucher(); + nextLine[5] = debit; + nextLine[6] = credit; + nextLine[7] = debitcredit; + + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + } + // Write cache in string + csvWriter.flush(); + } catch (Exception ex) { + throw new LimaException("Can't export", ex); + } finally { + if (csvWriter != null) { + try { + csvWriter.close(); + out.close(); + } catch (IOException e) { + // nothing to do + } + } + } + return out.getBuffer().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 { + StringWriter out = new StringWriter(); + CSVWriter csvWriter = null; + + try { + csvWriter = new CSVWriter(out, + CSVWriter.DEFAULT_SEPARATOR, + CSVWriter.NO_QUOTE_CHARACTER); + //export accounts + //Numero,Intitule,Type,bLetManuel,bLetAuto,bLetAppro,bCentPhysique,bCentJournal,bCentGLivre,bGeleDebit,bGeleCredit,bNoEchAna,TypeRel,Categorie,CodeTVA,TypeTVA,Lettrage,Encours,Seuil,Remise,Escompte,Devise,RIB0NomBanque,RIB0AdrBanque,RIB0Agence,RIB0Guichet,RIB0Compte,RIB0CleRIB,RIB1NomBanque,RIB1AdrBanque,RIB1Agence,RIB1Guichet,RIB1Compte,RIB1CleRIB,RIB2NomBanque,RIB2AdrBanque,RIB2Agence,RIB2Guichet,RIB2Compte,RIB2CleRIB,AdresseCivilite,AdresseRaiSoc,AdresseAdresse,AdresseCodePostal,AdresseVille,AdressePays,NII,Contact0Interloc,Contact0Fonction,Contact0TelNumTel,Contact0TelNumFax,Contact0Infos,Contact1Interloc,Contact1Fonction,Contact1TelNumTel,Contact1TelNumFax,Contact1Infos,Contact2Interloc,Contact2Fonction,Contact2TelNumTel,Contact2TelNumFax,Contact2Infos,Contact3Interloc,Contact3Fonction,Contact3TelNumTel,Contact3TelNumFax,Contact3Infos,Contact4Interloc,Contact4Fonction,Contact4TelNumTel,Contact4TelNumFax,Contact4Infos,CodeRegle,NbJours,TypeJours,Limite,Grille1,Grille2,Grille3,SectGeo,SectAct,ObjCA,TailleCA,NbEmpl,Commercial,JoursMois,CptTva,CptCharge,bDecouvertAutorise,MntDecouvertAutorise,EMailTiers,WebSiteTiers,NatAchat,NatVente,NatDepense,NatRecette,NumCptBqCH,NumClearing,NumIBAN,LetPart,TypeAchatTVA,IBAN0Pays,IBAN0Controle,IBAN0Contenu,IBAN1Pays,IBAN1Controle,IBAN1Contenu,IBAN2Pays,IBAN2Controle,IBAN2Contenu,BIC0Banque,BIC0Pays,BIC0Localisation,BIC0Branche,BIC1Banque,BIC1Pays,BIC1Localisation,BIC1Branche,BIC2Banque,BIC2Pays,BIC2Localisation,BIC2Branche,LibBIC0,LibBIC1,LibBIC2 + + String[] nextLine = new String[2]; + // Add the header line + nextLine[0] = "Numero"; + nextLine[1] = "Intitule"; + csvWriter.writeNext(nextLine); + + // Récupère tous les comptes + AccountTopiaDao accountTopiaDao = getDaoHelper().getAccountTopiaDao(); + List<Account> listAccount = accountTopiaDao.findAll(); + // Pour tous les comptes + for (Account account : listAccount) { + nextLine[0] = account.getAccountNumber(); + nextLine[1] = StringUtils.remove(account.getLabel(), ","); + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + // Write cache in string + csvWriter.flush(); + csvWriter.close(); + } catch (Exception ex) { + throw new LimaException("Can't export", ex); + } finally { + if (csvWriter != null) { + try { + csvWriter.close(); + out.close(); + } catch (IOException e) { + // nothing to do + } + } + } + return out.getBuffer().toString(); + } + + @Override + public String exportEntryBooksAsEBP() throws LimaException { + StringWriter out = new StringWriter(); + CSVWriter csvWriter = null; + + try { + csvWriter = new CSVWriter(out, + CSVWriter.DEFAULT_SEPARATOR, + CSVWriter.NO_QUOTE_CHARACTER); + + //entryBooks to export + List<EntryBook> entryBooks = entryBookService.getAllEntryBooks(); + + //Code,Type,Libelle,TypePiece,NextPiece,CpteType,CpteCompte,Contact,RIBNomBanque,RIBAdrBanque,RIBAgence,RIBGuichet,RIBCompte,RIBCleRIB,Lcr,Preleve,MemoDateCreat,MemoDateModif,Devise,CompteTP,NumCptBqCH,NumClearing,bSaisieKM + String[] nextLine = new String[2]; + // Add the header line + nextLine[0] = "Code"; + nextLine[1] = "Libelle"; + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + + if (entryBooks != null && !entryBooks.isEmpty()) { + for (EntryBook entryBook:entryBooks) { + nextLine[0] = entryBook.getCode(); + nextLine[1] = StringUtils.remove(entryBook.getLabel(), ","); + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + } + + // Write cache in string + csvWriter.flush(); + + } catch (Exception ex) { + throw new LimaException("Can't export", ex); + } finally { + if (csvWriter != null) { + try { + csvWriter.close(); + out.close(); + } catch (IOException e) { + // nothing to do + } + } + } + return out.getBuffer().toString(); + } + + + //############## EXPORT CSV + + /** Export integrality of database in CSV */ + @Override + public String exportAsCSV() throws LimaException { + StringWriter out = new StringWriter(); + CSVWriter csvWriter = null; + + try { + csvWriter = new CSVWriter(out, ';'); + exportAccountsChartAsCSV(csvWriter); + exportEntryBookChartAsCSV(csvWriter); + exportFinancialStatementChartAsCSV(csvWriter); + exportFiscalPeriodAsCSV(csvWriter); + exportClosedPeriodicEntryBooksAsCSV(csvWriter); + exportFinancialTransactionsAndEntriesAsCSV(csvWriter); + exportIdentityAsCSV(csvWriter); + // Write cache in string + csvWriter.flush(); + } catch (Exception ex) { + throw new LimaException("Can't export", ex); + } finally { + if (csvWriter != null) { + try { + csvWriter.close(); + out.close(); + } catch (IOException e) { + // nothing to do + } + } + } + return out.getBuffer().toString(); + } + + + /** Remote methode call from UI. */ + @Override + public String exportFinancialStatementChartAsCSV() throws LimaException { + + StringWriter out = new StringWriter(); + CSVWriter csvWriter = null; + + try { + csvWriter = new CSVWriter(out, ';'); + exportFinancialStatementChartAsCSV(csvWriter); + // Write cache in file + csvWriter.flush(); + } catch (Exception ex) { + throw new LimaException("Can't export", ex); + } finally { + if (csvWriter != null) { + try { + csvWriter.close(); + out.close(); + } catch (IOException e) { + // nothing to do + } + } + } + return out.getBuffer().toString(); + } + + + /** + * Local methode, export financialstatements from database + * structure : TYPE | Label | Header | Accounts | DebitAccounts + * | CreditAccounts | ProvisionDeprecationAccounts | SubAmount + * | HeaderAmount | MasterFinancialStatement + * + * @param csvWriter + * @throws LimaException + */ + public void exportFinancialStatementChartAsCSV(CSVWriter csvWriter) throws LimaException { + try { + String[] nextLine = new String[12]; + // Get all Financialstatements + FinancialStatementTopiaDao financialStatementTopiaDao = + getDaoHelper().getFinancialStatementTopiaDao(); + + List<FinancialStatement> listFinancialStatements = + financialStatementTopiaDao.findAllOrderedByCreateDate(); + + // For all Financialstatements + for (FinancialStatement financialStatement : listFinancialStatements) { + nextLine[0] = ImportExportEntityEnum.FINANCIALSTATEMENT.getLabel(); + nextLine[1] = financialStatement.getLabel(); + nextLine[2] = Boolean.toString( + financialStatement.isHeader()); + nextLine[3] = financialStatement.getAccounts(); + nextLine[4] = financialStatement.getDebitAccounts(); + nextLine[5] = financialStatement.getCreditAccounts(); + nextLine[6] = financialStatement. + getProvisionDeprecationAccounts(); + nextLine[7] = Boolean.toString( + financialStatement.isSubAmount()); + nextLine[8] = Boolean.toString( + financialStatement.isHeaderAmount()); + FinancialStatement masterFinancialStatement = + financialStatement.getMasterFinancialStatement(); + String masterFinancialStatementString = masterFinancialStatement == null ? "" : StringUtils.remove(masterFinancialStatement.getLabel(), ";"); + nextLine[9] = masterFinancialStatementString; + FinancialStatementWayEnum financialStatementWayEnum = financialStatement.getWay(); + String financialStatementWay = ""; + if (financialStatementWayEnum != null) { + financialStatementWay = financialStatementWayEnum.name(); + } + nextLine[10] = financialStatementWay; + // Add line in file + csvWriter.writeNext(nextLine); + } + } catch (TopiaException ex) { + throw new LimaException("Can't export", ex); + } + } + + /** Remote method call from UI. */ + @Override + public String exportVatStatementChartAsCSV() throws LimaException { + + StringWriter out = new StringWriter(); + CSVWriter csvWriter = null; + + try { + csvWriter = new CSVWriter(out, ';'); + exportVatStatementChartAsCSV(csvWriter); + // Write cache in file + csvWriter.flush(); + } catch (Exception ex) { + throw new LimaException("Can't export", ex); + } finally { + if (csvWriter != null) { + try { + csvWriter.close(); + out.close(); + } catch (IOException e) { + // nothing to do + } + } + } + return out.getBuffer().toString(); + + } + + /** + * Local methode, export vatstatements from database + * vatstatement Structure : TYPE | boxName | label | header + * | accounts | masterVatStatement + * + * @param csvWriter + * @throws LimaException + */ + public void exportVatStatementChartAsCSV(CSVWriter csvWriter) throws LimaException { + try { + String[] nextLine = new String[6]; + // Get all Vatstatements + VatStatementTopiaDao vatStatementTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + + List<VatStatement> listVatStatements = + vatStatementTopiaDao.findAllOrderedByCreateDate(); + + // For all Vatstatements + for (VatStatement vatStatement : listVatStatements) { + nextLine[0] = ImportExportEntityEnum.VATSTATEMENT.getLabel(); + nextLine[1] = vatStatement.getBoxName(); + nextLine[2] = vatStatement.getLabel(); + nextLine[3] = Boolean.toString( + vatStatement.isHeader()); + nextLine[4] = vatStatement.getAccounts(); + VatStatement masterVatStatement = + vatStatement.getMasterVatStatement(); + String masterVatStatementString = ""; + if (masterVatStatement != null) { + masterVatStatementString = + masterVatStatement.getLabel(); + } + nextLine[5] = masterVatStatementString; + + csvWriter.writeNext(nextLine); + } + } catch (TopiaException ex) { + throw new LimaException("Can't export", ex); + } + } + + + /** Remote methode call from UI. */ + @Override + public String exportEntryBookChartAsCSV() throws LimaException { + + StringWriter out = new StringWriter(); + CSVWriter csvWriter = null; + + try { + csvWriter = new CSVWriter(out, ';'); + exportEntryBookChartAsCSV(csvWriter); + // Write cache in file + csvWriter.flush(); + } catch (Exception ex) { + throw new LimaException("Can't export", ex); + } finally { + if (csvWriter != null) { + try { + csvWriter.close(); + out.close(); + } catch (IOException e) { + // nothing to do + } + } + } + return out.getBuffer().toString(); + } + + + /** + * Local methode, export entrybooks from database + * Structure : TYPE | Code | Label | Type + * + * @param csvWriter + * @throws LimaException + */ + public void exportEntryBookChartAsCSV(CSVWriter csvWriter) throws LimaException { + try { + String[] nextLine = new String[3]; + // Get all entrybook + EntryBookTopiaDao entryBookTopiaDao = getDaoHelper().getEntryBookTopiaDao(); + List<EntryBook> listEntryBook = entryBookTopiaDao.findAll(); + // For all EntryBook + for (EntryBook entryBook : listEntryBook) { + nextLine[0] = ImportExportEntityEnum.ENTRYBOOK.getLabel(); + nextLine[1] = entryBook.getCode(); + nextLine[2] = StringUtils.remove(entryBook.getLabel(), ";"); + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + } catch (TopiaException ex) { + throw new LimaException("Can't export", ex); + } + } + + + /** Remote methode call from UI. */ + @Override + public String exportAccountsChartAsCSV() throws LimaException { + StringWriter out = new StringWriter(); + CSVWriter csvWriter = null; + + try { + csvWriter = new CSVWriter(out, ';'); + exportAccountsChartAsCSV(csvWriter); + // Write cache in file + csvWriter.flush(); + } catch (Exception ex) { + throw new LimaException("Can't export", ex); + } finally { + if (csvWriter != null) { + try { + csvWriter.close(); + out.close(); + } catch (IOException e) { + // nothing to do + } + } + } + return out.getBuffer().toString(); + } + + + /** + * Local methode, export accounts from database + * Structure : TYPE | AccountNumber | Label | ThirdParty | MasterAccount | GeneralLedger + * + * @param csvWriter + * @throws LimaException + */ + public void exportAccountsChartAsCSV(CSVWriter csvWriter) throws LimaException { + try { + String[] nextLine = new String[6]; + // Récupère tous les comptes + AccountTopiaDao accountTopiaDao = + getDaoHelper().getAccountTopiaDao(); + List<Account> listAccount = accountTopiaDao.findAll(); + // Pour tous les comptes + for (Account account : listAccount) { + nextLine[0] = ImportExportEntityEnum.ACCOUNT.getLabel(); + nextLine[1] = account.getAccountNumber(); + nextLine[2] = StringUtils.remove(account.getLabel(), ";"); + nextLine[3] = account.getThirdParty(); + + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + } catch (TopiaException ex) { + throw new LimaException("Can't export", ex); + } + } + + + /** + * Local methode, export financialtransactions from database + * Structure : TYPE | TransactionDate | AmountDebit | AmountCredit + * | FinancialPeriod BeginDate | FinancialPeriod EndDate | EntryBook Code + * + * @param csvWriter + * @throws LimaException + */ + public void exportFinancialTransactionsAndEntriesAsCSV(CSVWriter csvWriter) throws LimaException { + int numTransaction = 0; + // Get all financialtransactions + try { + FinancialTransactionTopiaDao financialTransactionTopiaDao = + getDaoHelper().getFinancialTransactionTopiaDao(); + List<FinancialTransaction> listFinancialTransaction = + financialTransactionTopiaDao.findAll(); + // For all financialTransaction + for (FinancialTransaction financialTransaction : listFinancialTransaction) { + String[] nextLine = new String[8]; + nextLine[0] = ImportExportEntityEnum.FINANCIALTRANSACTION.getLabel(); + nextLine[1] = String.valueOf(numTransaction); + nextLine[2] = SDATEFORMAT.format(financialTransaction.getTransactionDate()); + nextLine[3] = financialTransaction.getAmountDebit().toString(); + nextLine[4] = financialTransaction.getAmountCredit().toString(); + EntryBook entryBook = financialTransaction.getEntryBook(); + if (entryBook != null) { + nextLine[5] = entryBook.getCode(); + } + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + + nextLine = new String[10]; + for (Entry entry : financialTransaction.getEntry()) { + nextLine[0] = ImportExportEntityEnum.ENTRY.getLabel(); + nextLine[1] = String.valueOf(numTransaction); + nextLine[2] = entry.getDescription(); + nextLine[3] = entry.getAmount().toString(); + nextLine[4] = Boolean.toString(entry.isDebit()); + nextLine[5] = entry.getLettering(); + nextLine[6] = entry.getDetail(); + nextLine[7] = entry.getVoucher(); + nextLine[8] = entry.getPosition(); + nextLine[9] = entry.getAccount().getAccountNumber(); + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + numTransaction++; + } + } catch (TopiaException ex) { + throw new LimaException("Can't export", ex); + } + } + + + /** + * Local methode, export fiscalperiods from database + * Structure : TYPE | BeginDate | EndDate | Locked + * + * @param csvWriter + * @throws LimaException + */ + public void exportFiscalPeriodAsCSV(CSVWriter csvWriter) throws LimaException { + try { + String[] nextLine = new String[4]; + // Get all fiscalperiod + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = + getDaoHelper().getFiscalPeriodTopiaDao(); + List<FiscalPeriod> listFiscalPeriod = + fiscalPeriodTopiaDao.findAll(); + // For all Entry + for (FiscalPeriod fiscalPeriod : listFiscalPeriod) { + nextLine[0] = ImportExportEntityEnum.FISCALPERIOD.getLabel(); + nextLine[1] = SDATEFORMAT.format(fiscalPeriod.getBeginDate()); + nextLine[2] = SDATEFORMAT.format(fiscalPeriod.getEndDate()); + nextLine[3] = Boolean.toString(fiscalPeriod.isLocked()); + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + } catch (TopiaException ex) { + throw new LimaException("Can't export", ex); + } + } + + /** + * Local methode, export ClosedPeriodicEntryBooks from database + * Structure : TYPE | Locked | FinancialPeriod beginDate | FinancialPeriod endDate | EntryBook Code + * + * @param csvWriter + * @throws LimaException + */ + public void exportClosedPeriodicEntryBooksAsCSV(CSVWriter csvWriter) throws LimaException { + try { + String[] nextLine = new String[5]; + // Get all fiscalperiod + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = + getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + List<ClosedPeriodicEntryBook> listClosedPeriodicEntryBook = + closedPeriodicEntryBookTopiaDao.findAll(); + // For all Entry + for (ClosedPeriodicEntryBook closedPeriodicEntryBook : listClosedPeriodicEntryBook) { + nextLine[0] = ImportExportEntityEnum.CLOSEDPERIODICENTRYBOOK.getLabel(); + nextLine[1] = Boolean.toString( + closedPeriodicEntryBook.isLocked()); + nextLine[2] = + SDATEFORMAT.format(closedPeriodicEntryBook.getFinancialPeriod(). + getBeginDate()); + nextLine[3] = + SDATEFORMAT.format(closedPeriodicEntryBook.getFinancialPeriod(). + getEndDate()); + nextLine[4] = closedPeriodicEntryBook.getEntryBook().getCode(); + // Ajoute la ligne au fichier + csvWriter.writeNext(nextLine); + } + } catch (TopiaException ex) { + throw new LimaException("Can't export", ex); + } + } + + public void exportIdentityAsCSV(CSVWriter csvWriter) throws LimaException { + try { + String[] nextLine = new String[12]; + // Get identity + IdentityTopiaDao identityTopiaDao = getDaoHelper().getIdentityTopiaDao(); + List<Identity> identities = identityTopiaDao.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 ex) { + throw new LimaException("Can't export", ex); + } + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialPeriodServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,224 @@ +/* + * #%L + * Lima business + * + * $Id: FinancialPeriodServiceImpl.java 3740 2014-01-17 22:12:04Z dcosse $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2010 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.ejb; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; + +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +import org.chorem.lima.business.AccountingRules; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.FinancialPeriodService; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.ClosedPeriodicEntryBookImpl; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryBookTopiaDao; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialPeriodTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +/** + * Gestion des périodes intermédiaires durant l'exercice. + * Chaque timeSpan sera fixe, et devra correspondre à un mois complet. + * + * @author Rémi Chapelet + */ +@Stateless +@Remote(FinancialPeriodService.class) +@TransactionAttribute +public class FinancialPeriodServiceImpl extends AbstractLimaService implements FinancialPeriodService { + + /** + * 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 + */ + @Override + public List<FinancialPeriod> createFinancialPeriods(Collection<FinancialPeriod> financialPeriods) throws LimaException { + + List<FinancialPeriod> result = new ArrayList<FinancialPeriod>(); + + try { + + FinancialPeriodTopiaDao financialPeriodTopiaDao = + getDaoHelper().getFinancialPeriodTopiaDao(); + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = + getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + EntryBookTopiaDao entryBookTopiaDao = + getDaoHelper().getEntryBookTopiaDao(); + //create all financial period + for (FinancialPeriod financialPeriod : financialPeriods) { + + //create financial period + financialPeriod = financialPeriodTopiaDao.create(financialPeriod); + + //create ClosedPeriodicEntryBook for all entrybook + for (EntryBook entryBook : entryBookTopiaDao.findAll()) { + //new closed periodic entrybook + ClosedPeriodicEntryBook closedPeriodicEntryBook + = new ClosedPeriodicEntryBookImpl(); + // set entrybook + closedPeriodicEntryBook.setEntryBook(entryBook); + // set financial period + closedPeriodicEntryBook.setFinancialPeriod(financialPeriod); + // create it + closedPeriodicEntryBookTopiaDao.create(closedPeriodicEntryBook); + } + + result.add(financialPeriod); + } + + } catch (TopiaException ex) { + throw new LimaException("Can't create period", ex); + } + + return result; + } + + /** @return all financial period */ + @Override + public List<FinancialPeriod> getAllFinancialPeriods() throws LimaException { + + List<FinancialPeriod> result; + + try { + FinancialPeriodTopiaDao financialPeriodTopiaDao = getDaoHelper().getFinancialPeriodTopiaDao(); + result = financialPeriodTopiaDao.findAllOrderByBeginDate(); + } catch (Exception ex) { + throw new LimaException("Can't get periods", ex); + } + + return result; + } + + /** @return all unblocked financial period */ + @Override + public List<FinancialPeriod> getUnblockedFinancialPeriods() throws LimaException { + + List<FinancialPeriod> result; + + try { + FinancialPeriodTopiaDao financialPeriodTopiaDao = getDaoHelper().getFinancialPeriodTopiaDao(); + result = financialPeriodTopiaDao.findAllUnlockedOrderByBeginDate(); + } catch (Exception ex) { + throw new LimaException("Can't create period", ex); + } + + return result; + } + + /** @return all financial period from a fiscal period */ + @Override + public List<FinancialPeriod> getFinancialPeriods(Date beginDate, Date endDate) throws LimaException { + + List<FinancialPeriod> result; + + try { + FinancialPeriodTopiaDao financialPeriodTopiaDao = getDaoHelper().getFinancialPeriodTopiaDao(); + result = financialPeriodTopiaDao.findByDates(beginDate, endDate); + } catch (Exception ex) { + throw new LimaException("Can't get period", ex); + } + + return result; + } + + public FinancialPeriod getFinancialPeriodByNaturalIds(Date beginDate, Date endDate) throws LimaException { + + FinancialPeriod result; + + try { + FinancialPeriodTopiaDao financialPeriodTopiaDao = getDaoHelper().getFinancialPeriodTopiaDao(); + result = financialPeriodTopiaDao.findByNaturalId(beginDate, endDate); + } catch (Exception ex) { + throw new LimaException("Can't get period", ex); + } + + return result; + } + + @Override + public ClosedPeriodicEntryBook blockClosedPeriodicEntryBook(ClosedPeriodicEntryBook closedPeriodicEntryBook) throws LimaException { + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + ClosedPeriodicEntryBook result; + try { + // check rules before create the account + accountingRules.blockClosedPeriodicEntryBookRules(closedPeriodicEntryBook); + + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = + getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + + // reload object in current transaction + result = closedPeriodicEntryBookTopiaDao.findByTopiaId( + closedPeriodicEntryBook.getTopiaId()); + + result.setLocked(true); + result = closedPeriodicEntryBookTopiaDao.update(result); + + } catch (TopiaException ex) { + throw new LimaException("Can't block period", ex); + } + + return result; + } + + @Override + public ClosedPeriodicEntryBook getClosedPeriodicEntryBook(EntryBook entryBook, + FinancialPeriod financialPeriod) throws LimaException { + ClosedPeriodicEntryBook closedPeriodicEntryBook; + + try { + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + closedPeriodicEntryBook = closedPeriodicEntryBookTopiaDao.findByEntryBookAndFinancialPeriod(entryBook, financialPeriod); + } catch (Exception ex) { + throw new LimaException("Can't get closed periodic", ex); + } + + return closedPeriodicEntryBook; + } + + @Override + public List<ClosedPeriodicEntryBook> getAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod() throws LimaException { + + List<ClosedPeriodicEntryBook> result; + + try { + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + result = closedPeriodicEntryBookTopiaDao.findAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod(); + } catch (Exception ex) { + throw new LimaException("Can't get closed periodics", ex); + } + + return result; + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialStatementServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,525 @@ +/* + * #%L + * Lima business + * + * $Id: FinancialStatementServiceImpl.java 3777 2014-04-14 07:29:08Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import static org.nuiton.i18n.I18n.t; + +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.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +import org.apache.commons.lang3.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; +import org.chorem.lima.beans.FinancialStatementAmounts; +import org.chorem.lima.beans.FinancialStatementAmountsImpl; +import org.chorem.lima.beans.FinancialStatementDatas; +import org.chorem.lima.beans.FinancialStatementDatasImpl; +import org.chorem.lima.beans.ReportsDatas; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.FinancialStatementService; +import org.chorem.lima.business.api.ReportService; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountTopiaDao; +import org.chorem.lima.entity.FinancialStatement; +import org.chorem.lima.entity.FinancialStatementTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +@Stateless +@Remote(FinancialStatementService.class) +@TransactionAttribute +public class FinancialStatementServiceImpl extends AbstractLimaService implements FinancialStatementService { + + @EJB + private ReportService reportService; + + protected static final Log log = LogFactory.getLog(FinancialStatementServiceImpl.class); + + @Override + public void createFinancialStatement(FinancialStatement masterFinancialStatement, + FinancialStatement financialStatement) throws LimaException { + + try { + + FinancialStatementTopiaDao financialStatementTopiaDao = getDaoHelper().getFinancialStatementTopiaDao(); + + financialStatementTopiaDao.create(financialStatement); + + FinancialStatement masterfinancialStatementUpdate = null; + if (masterFinancialStatement != null) { + masterfinancialStatementUpdate = financialStatementTopiaDao.findByLabel(masterFinancialStatement.getLabel()); + } + + // check if parent account exist; + if (masterfinancialStatementUpdate != null) { + masterfinancialStatementUpdate.addSubFinancialStatements(financialStatement); + financialStatementTopiaDao.update(masterfinancialStatementUpdate); + } + + } catch (TopiaException ex) { + throw new LimaException("Can't create financial statement", ex); + } + + } + + @Override + public void removeFinancialStatement(FinancialStatement financialStatement) throws LimaException { + + try { + FinancialStatementTopiaDao financialStatementTopiaDao = getDaoHelper().getFinancialStatementTopiaDao(); + + // remove financialstatement + FinancialStatement financialStatementToDelete = + financialStatementTopiaDao.findByTopiaId( + financialStatement.getTopiaId()); + financialStatementTopiaDao.delete(financialStatementToDelete); + + //get all subFinancialStatement + List<FinancialStatement> financialStatements = + getAllChildrenFinancialStatement(financialStatement, + new ArrayList<FinancialStatement>()); + + //if FinancialStatement have subFinancialStatement + if (financialStatements.size() > 0) { + for (FinancialStatement subFinancialStatement : financialStatements) { + FinancialStatement subFinancialStatementToDelete = + financialStatementTopiaDao.findByTopiaId( + subFinancialStatement.getTopiaId()); + financialStatementTopiaDao.delete(subFinancialStatementToDelete); + } + } + + } catch (Exception ex) { + throw new LimaException("Can't remove financial statement", ex); + } + } + + @Override + public void removeAllFinancialStatement() throws LimaException { + for (FinancialStatement financialStatement : getChildrenFinancialStatement(null)) { + removeFinancialStatement(financialStatement); + } + } + + @Override + public List<FinancialStatement> getAllFinancialStatements() throws LimaException { + List<FinancialStatement> financialStatements; + + try { + FinancialStatementTopiaDao financialStatementTopiaDao = getDaoHelper().getFinancialStatementTopiaDao(); + financialStatements = financialStatementTopiaDao.findAll(); + } catch (Exception ex) { + throw new LimaException("Can't get financial statements", ex); + } + return financialStatements; + } + + @Override + public List<FinancialStatement> getAllChildrenFinancialStatement(FinancialStatement financialStatement, + List<FinancialStatement> result) throws LimaException { + List<FinancialStatement> 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; + + try { + FinancialStatementTopiaDao financialStatementTopiaDao = getDaoHelper().getFinancialStatementTopiaDao(); + financialStatements = financialStatementTopiaDao.findChildrenFinancialStatement(masterFinancialStatement); + } catch (Exception ex) { + throw new LimaException("Can't get childreen statements", ex); + } + return financialStatements; + } + + + @Override + public void updateFinancialStatement(FinancialStatement financialStatement) throws LimaException { + + try { + // TopiaDao + FinancialStatementTopiaDao financialStatementHeaderTopiaDao = getDaoHelper().getFinancialStatementTopiaDao(); + //update + financialStatementHeaderTopiaDao.update(financialStatement); + + } catch (Exception ex) { + throw new LimaException("Can't update financial statement", ex); + } + } + + + /** + * remote methode to get list of financial statement + */ + @Override + public List<FinancialStatementAmounts> financialStatementReport(Date selectedBeginDate, + Date selectedEndDate) throws LimaException { + List<FinancialStatementAmounts> result; + + try { + + //create list form tree + result = financialStatementReport(null, selectedBeginDate, + selectedEndDate, new FinancialStatementDatasImpl()).getListResult(); + + } catch (Exception ex) { + throw new LimaException("Can't generate report", ex); + } + return result; + } + + /** + * Créé la liste de postes contenant les calculs de comptes + * + * @param financialStatement + * @param selectedBeginDate + * @param selectedEndDate + * @param result + * @return + * @throws LimaException + */ + protected FinancialStatementDatas financialStatementReport(FinancialStatement financialStatement, + Date selectedBeginDate, + Date selectedEndDate, + FinancialStatementDatas result) throws LimaException { + + List<FinancialStatement> financialStatements = getChildrenFinancialStatement(financialStatement); + + BigDecimal grossAmount = new BigDecimal(0), + provisionDeprecationAmount = new BigDecimal(0); + List<FinancialStatementAmounts> subResult = new ArrayList<FinancialStatementAmounts>(); + + for (FinancialStatement subFinancialStatement : financialStatements) { + FinancialStatementAmounts financialStatementAmounts = + financialStatementAmounts(subFinancialStatement, + selectedBeginDate, selectedEndDate); + if (!subFinancialStatement.isHeader()) { + //on calcul + grossAmount = + grossAmount.add(financialStatementAmounts.getGrossAmount()); + provisionDeprecationAmount = provisionDeprecationAmount.add( + financialStatementAmounts.getProvisionDeprecationAmount()); + subResult.add(financialStatementAmounts); + } else { + FinancialStatementDatas financialStatementDatas = + financialStatementReport(subFinancialStatement, + selectedBeginDate, selectedEndDate, result); + grossAmount = grossAmount.add(financialStatementDatas. + getFinancialStatementAmounts().getGrossAmount()); + provisionDeprecationAmount = provisionDeprecationAmount. + add(financialStatementDatas.getFinancialStatementAmounts(). + getProvisionDeprecationAmount()); + + + FinancialStatementAmounts headerfinancialStatementAmounts = + financialStatementDatas.getFinancialStatementAmounts(); + //Si sous-total + if (subFinancialStatement.isSubAmount()) { + FinancialStatementAmounts header = + new FinancialStatementAmountsImpl(); + header.setLabel(headerfinancialStatementAmounts.getLabel()); + header.setLevel(headerfinancialStatementAmounts.getLevel()); + header.setHeader(true); + //ajoute header + subResult.add(header); + //ajoute liste + if (financialStatementDatas.getListResult() != null) { + subResult.addAll(financialStatementDatas.getListResult()); + } + //ajoute sstotal + FinancialStatementAmounts subAmount = + new FinancialStatementAmountsImpl(); + subAmount.setLabel( + "TOTAL " + headerfinancialStatementAmounts.getLabel()); + subAmount.setLevel( + headerfinancialStatementAmounts.getLevel()); + subAmount.setGrossAmount( + headerfinancialStatementAmounts.getGrossAmount()); + subAmount.setProvisionDeprecationAmount( + headerfinancialStatementAmounts. + getProvisionDeprecationAmount()); + subAmount.setSubAmount(true); + subResult.add(subAmount); + //ajoute une ligne vide + subResult.add(new FinancialStatementAmountsImpl()); + + }//sinon + else { + + if (subFinancialStatement.isHeaderAmount()) { + subResult.add(headerfinancialStatementAmounts); + } else { + headerfinancialStatementAmounts. + setGrossAmount(new BigDecimal(0)); + headerfinancialStatementAmounts. + setProvisionDeprecationAmount(new BigDecimal(0)); + subResult.add(headerfinancialStatementAmounts); + } + //ajoute liste + if (financialStatementDatas.getListResult() != null) { + subResult.addAll(financialStatementDatas.getListResult()); + } + } + } + } + FinancialStatementAmounts financialStatementAmounts = + new FinancialStatementAmountsImpl(); + financialStatementAmounts.setGrossAmount(grossAmount); + financialStatementAmounts.setProvisionDeprecationAmount( + provisionDeprecationAmount); + if (financialStatement != null) { + financialStatementAmounts.setLabel(financialStatement.getLabel()); + financialStatementAmounts.setHeader(financialStatement.isHeader()); + financialStatementAmounts.setLevel(financialStatement.getLevel()); + } + result.setFinancialStatementAmounts(financialStatementAmounts); + result.setListResult(subResult); + + return result; + } + + + /** + * Permet de calculer le montant de tous les comptes contenu dans un mouvement + * + * @param financialStatement + * @param selectedBeginDate + * @param selectedEndDate + * @return + * @throws LimaException + */ + protected FinancialStatementAmounts financialStatementAmounts(FinancialStatement financialStatement, + Date selectedBeginDate, + Date selectedEndDate) throws LimaException { + FinancialStatementAmounts financialStatementAmounts = + 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.getMasterFinancialStatement(); + FinancialStatementWayEnum financialStatementWayEnum = + FinancialStatementWayEnum.BOTH; + if (masterFinancialStatement != null) { + financialStatementWayEnum = masterFinancialStatement.getWay(); + } + + // DEBIT & CREDIT ACCOUNTS LIST + Amounts amounts; + String accountsString = financialStatement.getAccounts(); + if (accountsString != null && !accountsString.equals("")) { + amounts = amountFromAccountList(accountsString, + selectedBeginDate, selectedEndDate); + 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); + debitAmount = debitAmount.add(amounts.getDebit()); + } + //CREDIT ACCOUNTS LIST + String creditAccountsString = financialStatement.getCreditAccounts(); + if (creditAccountsString != null && !creditAccountsString.equals("")) { + amounts = amountFromAccountList(creditAccountsString, + selectedBeginDate, selectedEndDate); + creditAmount = creditAmount.add(amounts.getCredit()); + } + // PROVISION & DEPRECATION + String provisionDeprecationAccountsString = + financialStatement.getProvisionDeprecationAccounts(); + if (provisionDeprecationAccountsString != null && !provisionDeprecationAccountsString.equals("")) { + amounts = amountFromAccountList( + provisionDeprecationAccountsString, selectedBeginDate, + selectedEndDate); + provisionDeprecationAmount = + provisionDeprecationAmount.add(amounts.getCredit()); + provisionDeprecationAmount = + provisionDeprecationAmount.subtract(amounts.getDebit()); + } + switch (financialStatementWayEnum) { + case BOTH: + amount = amount.add(debitAmount); + amount = amount.subtract(creditAmount); + amount = amount.abs(); + break; + case CREDIT: + amount = amount.add(creditAmount); + amount = amount.subtract(debitAmount); + break; + case DEBIT: + amount = amount.add(debitAmount); + amount = amount.subtract(creditAmount); + } + + financialStatementAmounts.setGrossAmount(amount); + financialStatementAmounts.setLabel(financialStatement.getLabel()); + financialStatementAmounts.setProvisionDeprecationAmount( + provisionDeprecationAmount); + financialStatementAmounts.setLevel( + financialStatement.getLevel()); + + return financialStatementAmounts; + } + + protected Amounts amountFromAccountList(String accountsNumberList, + Date selectedBeginDate, + Date selectedEndDate) throws LimaException { + Amounts amounts = new AmountsImpl(); + BigDecimal debit = new BigDecimal(0); + BigDecimal credit = new BigDecimal(0); + Boolean substract = false; + try { + AccountTopiaDao accountTopiaDao = getDaoHelper().getAccountTopiaDao(); + //Remove Spaces + String result = StringUtils.deleteWhitespace(accountsNumberList); + StringTokenizer stQuote = new StringTokenizer(result, "-"); + while (stQuote.hasMoreTokens()) { + String s = stQuote.nextToken(); + List<Account> accountsList = accountTopiaDao.stringToListAccounts(s, false); + BigDecimal debitTemp = new BigDecimal(0); + BigDecimal creditTemp = new BigDecimal(0); + for (Account account : accountsList) { + ReportsDatas reportsDatas = reportService. + generateAccountsReports(account, true, + selectedBeginDate, selectedEndDate); + if (reportsDatas.getSoldeDebit()) { + debitTemp = debitTemp.add(reportsDatas.getAmountSolde()); + } else { + creditTemp = creditTemp.add(reportsDatas.getAmountSolde()); + } + } + if (!substract) { + debit = debitTemp; + credit = creditTemp; + } + //compte(s) précédé du signe - + else { + debit = debit.subtract(debitTemp); + credit = credit.subtract(creditTemp); + } + substract = true; + } + amounts.setCredit(credit); + amounts.setDebit(debit); + } catch (TopiaException ex) { + throw new LimaException("Can't get accounts from list", ex); + } + return amounts; + } + + @Override + public String checkFinancialStatementChart() throws LimaException { + StringBuilder result = + new StringBuilder(t("lima-business.financialstatement.check.warn")); + + try { + + AccountTopiaDao accountTopiaDao = getDaoHelper().getAccountTopiaDao(); + FinancialStatementTopiaDao financialStatementTopiaDao = getDaoHelper().getFinancialStatementTopiaDao(); + + List<Account> accountsList = accountTopiaDao.findAllLeafAccounts(); + + List<FinancialStatement> financialStatementsList = + financialStatementTopiaDao.findAll(); + + + for (FinancialStatement financialStatement : financialStatementsList) { + + accountsList.removeAll( + accountTopiaDao.stringToListAccounts( + financialStatement.getAccounts(), true)); + + accountsList.removeAll( + accountTopiaDao.stringToListAccounts( + financialStatement.getCreditAccounts(), true)); + + accountsList.removeAll( + accountTopiaDao.stringToListAccounts( + financialStatement.getDebitAccounts(), true)); + + accountsList.removeAll( + accountTopiaDao.stringToListAccounts( + financialStatement.getProvisionDeprecationAccounts(), true)); + } + + for (Account account : accountsList) { + + result.append(t("lima-business.financialstatement.check.nothing", + account.getAccountNumber(), account.getLabel())); + } + + } catch (TopiaException ex) { + throw new LimaException("Can't check financial statement", ex); + } + return result.toString(); + } + + @Override + public boolean checkFinancialStatementExist(String label) throws LimaException { + boolean result; + try { + FinancialStatementTopiaDao financialStatementTopiaDao = getDaoHelper().getFinancialStatementTopiaDao(); + result = financialStatementTopiaDao.forProperties(FinancialStatement.PROPERTY_LABEL, label).exists(); + } catch (TopiaException e) { + throw new LimaException("Can't check financial statement", e); + } + return result; + } + + @Override + public FinancialStatement getFinancialStatementByLabel(String label) throws LimaException { + FinancialStatement result; + try { + FinancialStatementTopiaDao financialStatementTopiaDao = getDaoHelper().getFinancialStatementTopiaDao(); + result = financialStatementTopiaDao.findByLabel(label); + } catch (TopiaException e) { + throw new LimaException("Can't find financial statement", e); + } + return result; + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FinancialTransactionServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,626 @@ +/* + * #%L + * Lima business + * * + * $Id: FinancialTransactionServiceImpl.java 3783 2014-05-06 16:47:18Z dcosse $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.Filter.FilterGenerator; +import org.chorem.lima.Filter.FinancialTransactionFilter; +import org.chorem.lima.beans.FinancialTransactionCondition; +import org.chorem.lima.beans.LetteringFilter; +import org.chorem.lima.business.AccountingRules; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.AccountService; +import org.chorem.lima.business.api.FinancialTransactionService; +import org.chorem.lima.business.utils.LetteringComparator; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryTopiaDao; +import org.chorem.lima.entity.EntryImpl; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionTopiaDao; +import org.chorem.lima.entity.FiscalPeriod; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.EJB; +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * 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. + * Une transaction est composée d'entrées comptables. + * Les actions sur les transactions sont soumises au statut de celle-ci, si elle + * est dans une période bloquée ou non. + * + * @author Rémi Chapelet + */ +@Stateless +@Remote(FinancialTransactionService.class) +@TransactionAttribute +public class FinancialTransactionServiceImpl extends AbstractLimaService implements FinancialTransactionService { + +// @EJB +// protected FinancialPeriodService financialPeriodService; + +// @EJB +// protected ReportService reportService; + + //@EJB + //protected EntryBookService entryBookService; + + @EJB + protected AccountService accountService; + +// @EJB +// protected OptionsService optionsService; + + protected static final Log log = LogFactory.getLog(FinancialTransactionServiceImpl.class); + + @Override + public FinancialTransaction createFinancialTransaction(FinancialTransaction financialtransaction) + throws LimaException { + FinancialTransaction fTransaction; + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + try { + //check if the financial period is blocked + accountingRules.checkFinancialPeriodBlockedWithFinancialTransaction(financialtransaction); + + FinancialTransactionTopiaDao financialtransactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + + fTransaction = financialtransactionTopiaDao.create(financialtransaction); + + } catch (TopiaException ex) { + throw new LimaException("Can't create financial transaction", ex); + } + return fTransaction; + } + + /** + * Return the list of all financial transaction from two dates. + */ + @Override + public List<FinancialTransaction> getAllFinancialTransactions( + Date beginDate, Date endDate) throws LimaException { + List<FinancialTransaction> financialTransactions; + + try { + FinancialTransactionTopiaDao transactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + financialTransactions = transactionTopiaDao.findAllByDates(beginDate, endDate); + } catch (Exception ex) { + throw new LimaException("Can't get financial transactions", ex); + } + return financialTransactions; + } + + /** Find the last three letters used + * and increment them + * */ + @Override + public String getNextLetters() throws LimaException { + String lastActualLetters; + String nextLetters; + try { + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + + List<String> letters = new ArrayList<String>(entryTopiaDao.findLetters()); + lastActualLetters = findLastLetter(letters); + + } catch (Exception ex) { + throw new LimaException("Can't get new letters", ex); + } + + nextLetters = lettersAfter(lastActualLetters); + + return nextLetters; + } + + + public static String lettersAfter(String letters) { + + String letterAfter; + + /* "" -> "A" */ + if (StringUtils.isEmpty(letters)) { + + letterAfter = "A"; + + } else { + char endChar = letters.charAt(letters.length() - 1); + + if (endChar < 'Z') { + + /* si la lettre n'est pas un 'Z' on ajout a la reste de la chaine le caratère suivant */ + letterAfter = letters.substring(0, letters.length() -1) + ((char) (endChar + 1)); + } else { + /* si non on réitére sur le reste de la chaine en ajoutant "A" a la nouvelle chaine */ + letterAfter = lettersAfter(letters.substring(0, letters.length() -1)) + 'A'; + + } + + } + return letterAfter; + + } + + @Override + public List<String> getAllLetters() throws LimaException { + List<String> letters; + try { + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + + letters = new ArrayList<String>(entryTopiaDao.findLetters()); + + } catch (Exception ex) { + throw new LimaException("Can't get all letters", ex); + } + + return letters; + } + + @Override + public Entry[] getEntriesFromEqualizing(Entry FirstEntrySelected, Entry SecondEntrySelected) throws LimaException{ + + Entry newSameAccountEntry = null; + Entry newCostOrProductEntry = null; + BigDecimal firstSelectedEntryAmount = FirstEntrySelected.getAmount(); + BigDecimal secondSelectedEntryAmount = SecondEntrySelected.getAmount(); + + if ( (firstSelectedEntryAmount.compareTo(BigDecimal.ZERO) != 0 && secondSelectedEntryAmount.compareTo(BigDecimal.ZERO) != 0) + && !firstSelectedEntryAmount.equals(secondSelectedEntryAmount)) { + + /*Calculation of result with it + * Tab : 0 : debit + * 1 : credit*/ + BigDecimal[] firstEntryDebitCredit = debitCreditCalculation(FirstEntrySelected); + BigDecimal[] secondEntryDebitCredit = debitCreditCalculation(SecondEntrySelected); + + /*Subtraction between debit and credit of first and second selected line*/ + BigDecimal firstEntryDebitSubtract = firstEntryDebitCredit[0].subtract(secondEntryDebitCredit[1]); + BigDecimal secondEntryDebitSubtract = secondEntryDebitCredit[0].subtract(firstEntryDebitCredit[1]); + + /*Create handles of new futures entries*/ + Entry sameAccountEntry; + Entry costOrProductEntry; + + /*Set result in the amount of the new entries*/ + if (firstEntryDebitSubtract.compareTo(BigDecimal.ZERO) != 0) { + sameAccountEntry = copyEntryWithoutAmount(FirstEntrySelected); + costOrProductEntry = copyEntryWithoutAmount(FirstEntrySelected); + amountsCalculation(firstEntryDebitSubtract, sameAccountEntry, costOrProductEntry); + } else { + sameAccountEntry = copyEntryWithoutAmount(SecondEntrySelected); + costOrProductEntry = copyEntryWithoutAmount(SecondEntrySelected); + amountsCalculation(secondEntryDebitSubtract, sameAccountEntry, costOrProductEntry); + } + + String accountRegularization = t("lima.ui.lettering.accountRegularization"); + + if (log.isDebugEnabled()) { + log.debug("accountRegularization : " + accountRegularization); + } + + sameAccountEntry.setDescription(accountRegularization); + costOrProductEntry.setDescription(accountRegularization); + + /*Save in the DB the new entries*/ + newSameAccountEntry = createEntry(sameAccountEntry); + newCostOrProductEntry = createEntry(costOrProductEntry); + + } + + Entry [] entries = {newSameAccountEntry, newCostOrProductEntry}; + return entries; + } + + /**Debit and credit calculation for one entry, with its amount + * @param entry Entry for calculation + * @return table of two big decimal, representing respectively debit and credit + * */ + protected BigDecimal[] debitCreditCalculation(Entry entry) { + + boolean firstEntryDebit = entry.isDebit(); + BigDecimal firstEntryAmount = entry.getAmount(); + + BigDecimal debitVal = firstEntryDebit ? firstEntryAmount : BigDecimal.ZERO; + BigDecimal creditVal = firstEntryDebit ? BigDecimal.ZERO : firstEntryAmount; + + BigDecimal[] debitCredit = {debitVal, creditVal}; + + return debitCredit; + } + + /**Copy parametrised entry, without amount*/ + protected Entry copyEntryWithoutAmount(Entry entryToCopy) { + Entry copiedEntry = new EntryImpl(); + + copiedEntry.setAccount(entryToCopy.getAccount()); + copiedEntry.setDescription(entryToCopy.getDescription()); + copiedEntry.setDetail(entryToCopy.getDetail()); + copiedEntry.setFinancialTransaction(entryToCopy.getFinancialTransaction()); + copiedEntry.setVoucher(entryToCopy.getVoucher()); + + return copiedEntry; + } + + /** + *Calculation of amount for the new entries created + * and determine for the second if account is in costs (658) + * or products (758) + * @param resultOfFirstSecondEntrySubtraction difference between the two old entries + * @param sameAccountEntry first new entry created with the same account + * @param costOrProductEntry second new entry created with account 658 or 758 + * */ + protected void amountsCalculation( BigDecimal resultOfFirstSecondEntrySubtraction, Entry sameAccountEntry, Entry costOrProductEntry) { + sameAccountEntry.setAmount(resultOfFirstSecondEntrySubtraction.abs()); + costOrProductEntry.setAmount(resultOfFirstSecondEntrySubtraction.abs()); + Account costOrProductAccount; + + /*-1 for less than 0 : credit*/ + if (resultOfFirstSecondEntrySubtraction.compareTo(BigDecimal.ZERO) == -1) { + sameAccountEntry.setDebit(true); + costOrProductEntry.setDebit(false); + costOrProductAccount = accountService.getAccountByNumber("758"); + } else { /*Greater than 0 : debit*/ + sameAccountEntry.setDebit(false); + costOrProductEntry.setDebit(true); + costOrProductAccount = accountService.getAccountByNumber("658"); + } + costOrProductEntry.setAccount(costOrProductAccount); + } + + public String findLastLetter(List<String> letters) { + + String result; + + /** filtre sur les valeurs potentiellement généré */ + Collection<String> generatedLetters = Collections2.filter(letters, new Predicate<String>() { + @Override + public boolean apply(String input) { + return input != null && + input.matches("[A-Z]+"); + } + }); + + if (generatedLetters.isEmpty()) { + result = ""; + + } else { + result = Collections.max(generatedLetters, new LetteringComparator()); + } + return result; + } + + /** + * Return the list of all financial transaction of a financial period. + */ + @Override + public List<FinancialTransaction> getAllFinancialTransactions( + FinancialPeriod period) throws LimaException { + return getAllFinancialTransactions(period, null); + } + + /** + * Return the list of all financial transaction of a fiscal period. + */ + @Override + public List<FinancialTransaction> getAllFinancialTransactions( + FiscalPeriod period) throws LimaException { + List<FinancialTransaction> financialTransactions; + + try { + FinancialTransactionTopiaDao transactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + financialTransactions = transactionTopiaDao.findAllByDates(period.getBeginDate(), period.getEndDate()); + } catch (Exception ex) { + throw new LimaException("Can't get financial transactions", ex); + } + return financialTransactions; + } + + /** + * Return the list of all financial transaction of a financial period and an entrybook. + */ + @Override + public List<FinancialTransaction> getAllFinancialTransactions(FinancialPeriod financialPeriod, EntryBook entryBook) throws LimaException { + + List<FinancialTransaction> financialTransactions; + + try { + FinancialTransactionTopiaDao transactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + + if (entryBook != null) { + financialTransactions = transactionTopiaDao.findAllByDates(financialPeriod.getBeginDate(), + financialPeriod.getEndDate(), entryBook); + } else { + financialTransactions = transactionTopiaDao.findAllByDates(financialPeriod.getBeginDate(), + financialPeriod.getEndDate()); + } + + } catch (Exception ex) { + throw new LimaException("Can't get financial transactions", ex); + } + return financialTransactions; + } + + /** + * Get unbalanced financialtransaction from selected fiscalperiod. + */ + @Override + public List<FinancialTransaction> getAllInexactFinancialTransactions(FiscalPeriod fiscalPeriod) throws LimaException { + + List<FinancialTransaction> result; + //List<FinancialTransaction> checkedResult = new ArrayList<FinancialTransaction>(); + try { + + FinancialTransactionTopiaDao financialTransactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + + result = financialTransactionTopiaDao.getAllIncorrectTransaction(fiscalPeriod.getBeginDate(), + fiscalPeriod.getEndDate(), null); + /*for (FinancialTransaction fTransaction : result) { + BigDecimal credit = fTransaction.getAmountCredit(); + BigDecimal debit = fTransaction.getAmountDebit(); + credit = credit.setScale(optionsService.getScale(), + BigDecimal.ROUND_HALF_UP); + debit = debit.setScale(optionsService.getScale(), + BigDecimal.ROUND_HALF_UP); + if (credit.equals(debit)) { + checkedResult.add(fTransaction); + } + }*/ + + } catch (Exception ex) { + throw new LimaException("Can't get financial transactions", ex); + } + return result; + } + + /** + * Get balanced financial transaction from selected fiscal period + * + * @param fiscalPeriod The fiscal period for financial transaction + * @return the balanced financial transaction + * @throws LimaException + */ + @Override + public List<FinancialTransaction> getAllFinancialTransactionsBalanced(FiscalPeriod fiscalPeriod) throws LimaException { + List<FinancialTransaction> result; + try { + FinancialTransactionTopiaDao financialTransactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + + result = financialTransactionTopiaDao.getAllBalancedTransaction(fiscalPeriod.getBeginDate(), + fiscalPeriod.getEndDate(), null); + + } catch (TopiaException ex) { + throw new LimaException("Can't get financial transactions", ex); + } + return result; + } + + @Override + public List<Entry> getAllEntrieByDatesAndAccountAndLettering(LetteringFilter filter) throws LimaException { + List<Entry> entries; + + try { + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + entries = entryTopiaDao.findAllEntryByFilter(filter); + } catch (Exception ex) { + throw new LimaException("Can't get entries", ex); + } + + if (log.isInfoEnabled()) { + log.info("Entries size : " + entries.size()); + } + + return entries; + } + + @Override + public Entry getLastEntry(FinancialTransaction financialTransaction) throws LimaException { + Entry lastEntry; + + try { + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + lastEntry = entryTopiaDao.getLastEntry(financialTransaction); + + } catch (Exception ex) { + throw new LimaException("Can't get entries", ex); + } + + return lastEntry; + } + + /** + * Method used by update entry and remove entry for update amounts. + */ + @Override + public void updateFinancialTransaction(FinancialTransaction financialTransaction) throws LimaException { + + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + try { + + //FIXME mallon 22/06/2012 : Revoir l'utilisation du rattachement à la session et celle des deux objets 'financialTransactionOld' + //et 'financialTransaction' + FinancialTransactionTopiaDao transactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + FinancialTransaction financialTransactionOld = transactionTopiaDao.findByTopiaId(financialTransaction.getTopiaId()); + + accountingRules.updateFinancialTransactionDateRules(financialTransaction, financialTransactionOld); + + financialTransactionOld.setEntryBook(financialTransaction.getEntryBook()); + financialTransactionOld.setTransactionDate(financialTransaction.getTransactionDate()); + + transactionTopiaDao.update(financialTransactionOld); + } catch (TopiaException ex) { + throw new LimaException("Can't update financial transaction", ex); + } + } + + /** + * delete financial period + * call accounting rules + */ + @Override + public void removeFinancialTransaction(FinancialTransaction financialTransaction) throws LimaException { + + // check if the financial period is blocked + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + accountingRules.checkFinancialPeriodBlockedWithFinancialTransaction(financialTransaction); + + try { + + FinancialTransactionTopiaDao transactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + FinancialTransaction financialTransactionOld = transactionTopiaDao.findByTopiaId(financialTransaction.getTopiaId()); + transactionTopiaDao.delete(financialTransactionOld); + + } catch (Exception ex) { + throw new LimaException("Can't remove financial transaction", ex); + } + } + + @Override + public Entry createEntry(Entry entry) throws LimaException { + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + Entry newEntry; + try { + //check if the financial period is blocked + accountingRules.checkFinancialPeriodBlockedWithFinancialTransaction( + entry.getFinancialTransaction()); + + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + newEntry = entryTopiaDao.create(entry); + + } catch (TopiaException ex) { + throw new LimaException("Can't create entry", ex); + } + return newEntry; + } + + /** + * update entry, calculate amount of the financial transaction. + */ + @Override + public void updateEntry(Entry entry) throws LimaException { + + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + try { + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + + Entry entryOld = entryTopiaDao.findByTopiaId(entry.getTopiaId()); + + //check rules + accountingRules.updateEntryRules(entry, entryOld); + + //get new entry amounts + BigDecimal entryAmount = entry.getAmount(); + Boolean entryAmountIsDebit = entry.isDebit(); + + //FIXME PEPIN 20100520 conflict object already instanciate + // Exist best solution ? + entryOld.setAccount(entry.getAccount()); + entryOld.setAmount(entryAmount); + entryOld.setDebit(entryAmountIsDebit); + entryOld.setDescription(entry.getDescription()); + entryOld.setVoucher(entry.getVoucher()); + entryOld.setFinancialTransaction(entry.getFinancialTransaction()); + entryOld.setPosition(entry.getPosition()); + entryOld.setLettering(entry.getLettering()); + + //update entry + entryTopiaDao.update(entryOld); + + } catch (Exception ex) { + throw new LimaException("Can't update entry", ex); + } + } + + /** + * Remove entry, update amounts for the financial transaction. + */ + @Override + public void removeEntry(Entry entry) throws LimaException { + + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + try { + //check if the financial period is blocked + accountingRules.checkFinancialPeriodBlockedWithFinancialTransaction( + entry.getFinancialTransaction()); + + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + Entry entryOld = entryTopiaDao.findByTopiaId(entry.getTopiaId()); + entryOld.getFinancialTransaction().removeEntry(entryOld); + entryTopiaDao.delete(entryOld); + + } catch (TopiaException ex) { + throw new LimaException("Can't remove entry", ex); + } + } + + @Override + public List<FinancialTransaction> searchFinancialTransaction(FinancialTransactionCondition financialTransactionCondition) throws LimaException { + List<FinancialTransaction> result; + + FilterGenerator generator = new FilterGenerator(); + financialTransactionCondition.accept(generator); + FinancialTransactionFilter filter = generator.getFilter(); + + + try { + // next on financial transaction dao + FinancialTransactionTopiaDao financialTransactionTopiaDao = getDaoHelper().getFinancialTransactionTopiaDao(); + result = financialTransactionTopiaDao.searchFinancialTransaction(filter); + + + } catch (Exception ex) { + throw new LimaException("Can't search financial transaction", ex); + } + + if (log.isDebugEnabled()) { + log.debug("Size of results list : " + result.size()); + } + + return result; + } + +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FiscalPeriodServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,531 @@ +/* + * #%L + * Lima business + * * + * $Id: FiscalPeriodServiceImpl.java 3777 2014-04-14 07:29:08Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import org.apache.commons.lang3.time.DateUtils; +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.api.AccountService; +import org.chorem.lima.business.api.EntryBookService; +import org.chorem.lima.business.api.FinancialPeriodService; +import org.chorem.lima.business.api.FinancialTransactionService; +import org.chorem.lima.business.api.FiscalPeriodService; +import org.chorem.lima.business.api.ReportService; +import org.chorem.lima.business.utils.FinancialPeriodComparator; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountImpl; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookTopiaDao; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryImpl; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionImpl; +import org.chorem.lima.entity.FiscalPeriod; +import org.chorem.lima.entity.FiscalPeriodTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.EJB; +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +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.t; + +/** + * Gestion des exercices. + * Un exercice ne peut être supprimé et débloqué après cloture. + * + * @author Rémi Chapelet + */ +@Stateless +@Remote(FiscalPeriodService.class) +@TransactionAttribute +public class FiscalPeriodServiceImpl extends AbstractLimaService implements FiscalPeriodService { + + @EJB + protected AccountService accountService; + + @EJB + protected FinancialPeriodService financialPeriodService; + + @EJB + protected EntryBookService entryBookService; + + @EJB + protected ReportService reportService; + + @EJB + protected FinancialTransactionService financialTransactionService; + + @Override + public FiscalPeriod createFiscalPeriod(FiscalPeriod fiscalPeriod) throws LimaException { + + FiscalPeriod result; + + try { + + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + + // fix begin date at midnight and end date at 23:59:59.999 + 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); + fiscalPeriod.setBeginDate(beginDate); + fiscalPeriod.setEndDate(endDate); + + //check rules before create the account + List<FinancialPeriod> financialPeriods = accountingRules.createFiscalPeriodRules(fiscalPeriod); + + // FIXME echatellier 20120510 il y a un gros problème ici + // les periods sont instanciées par la rule + // mais crée ensuite par le service et la periodes + // est créée au final avec des entités qui n'ont pas les id affectés + financialPeriods = financialPeriodService.createFinancialPeriods(financialPeriods); + + // create + result = fiscalPeriodTopiaDao.create(fiscalPeriod); + result.addAllFinancialPeriod(financialPeriods); + + // udpate + result = fiscalPeriodTopiaDao.update(result); + + } catch (TopiaException ex) { + throw new LimaException("Can't create period", ex); + } + + return result; + } + + /** + * return all fiscal period. + */ + @Override + public List<FiscalPeriod> getAllFiscalPeriods() throws LimaException { + + List<FiscalPeriod> result; + + try { + + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + result = fiscalPeriodTopiaDao.findAll(); + } catch (Exception ex) { + throw new LimaException("Can't get periods", ex); + } + + return result; + } + + /** + * return all blocked fiscal periods. + */ + @Override + public List<FiscalPeriod> getAllBlockedFiscalPeriods() throws LimaException { + + List<FiscalPeriod> result; + + try { + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + result = fiscalPeriodTopiaDao.findAllByLocked(true); + } catch (Exception ex) { + throw new LimaException("Can't create period", ex); + } + + return result; + } + + + /** return all unblocked fiscal periods */ + @Override + public List<FiscalPeriod> getAllUnblockedFiscalPeriods() throws LimaException { + + List<FiscalPeriod> result; + + try { + + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + result = fiscalPeriodTopiaDao.findAllByLocked(false); + } catch (Exception ex) { + throw new LimaException("Can't get periods", ex); + } + + return result; + } + + @Override + public FiscalPeriod getLastFiscalPeriod() throws LimaException { + FiscalPeriod result; + + try { + + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + //get the last fiscal period + result = fiscalPeriodTopiaDao.getLastFiscalPeriod(); + + } catch (Exception ex) { + throw new LimaException("Can't get period", ex); + } + + return result; + } + + /** + * to block a fiscal period + * <p/> + * check localized rules before block it + */ + @Override + public FiscalPeriod blockFiscalPeriod(FiscalPeriod fiscalPeriod) throws LimaException { + + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + FiscalPeriod result; + try { + + if (fiscalPeriod.isLocked()) { + throw new LimaBusinessException(t("lima-business.fiscalperiod.fiscalperiodalreadyblocked")); + } + //check rules + accountingRules.blockFiscalPeriodRules(fiscalPeriod); + + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + + // Get the old fiscal period instance for no object conflict + FiscalPeriod oldFiscalPeriod = + fiscalPeriodTopiaDao.findByTopiaId(fiscalPeriod.getTopiaId()); + + // lock fiscalperiod + oldFiscalPeriod.setLocked(true); + // locked all financialperiod of the fiscalperiod + for (FinancialPeriod financialPeriod : oldFiscalPeriod.getFinancialPeriod()) { + financialPeriod.setLocked(true); + } + + result = fiscalPeriodTopiaDao.update(oldFiscalPeriod); + + } catch (Exception ex) { + throw new LimaException("Can't block period", ex); + } + + return result; + } + + @Override + public boolean isRetainedEarnings(FiscalPeriod fiscalPeriod) throws LimaException{ + boolean found = false; + List<FinancialTransaction> financialTransactionsList = + financialTransactionService.getAllFinancialTransactions( + fiscalPeriod.getBeginDate(), fiscalPeriod.getEndDate()); + //check if they are at least one transaction to be report + if (!financialTransactionsList.isEmpty()) { + int i = 0; + while (i < financialTransactionsList.size() && !found) { + Collection<Entry> entryList = financialTransactionsList.get(i).getEntry(); + for (Entry entry : entryList) { + if (entry.getAccount() != null) { + if (Integer.valueOf(entry.getAccount().getAccountNumber().substring(0, 1)) < 6 + && !entry.getAmount().equals(BigDecimal.ZERO)) { + found = true; + } + } + } + i++; + } + } + return found; + } + + @Override + public FiscalPeriod updateEndDate(FiscalPeriod fiscalPeriod) throws LimaException { + + FiscalPeriod result; + + try { + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + + String topiaId = fiscalPeriod.getTopiaId(); + FiscalPeriod fiscalPeriodOld = fiscalPeriodTopiaDao.findByTopiaId(topiaId); + + Date endDate = fiscalPeriod.getEndDate(); + fiscalPeriodOld.setEndDate(endDate); + + result = fiscalPeriodTopiaDao.update(fiscalPeriodOld); + + } catch (TopiaException e) { + throw new LimaException("Can't update period", e); + } + + return result; + } + + @Override + public FiscalPeriod retainedEarningsAndBlockFiscalPeriod(FiscalPeriod fiscalPeriod, EntryBook entryBook, + boolean retainedEarnings) throws LimaException { + + if (entryBook != null && retainedEarnings) { + + // re-attach entities to current session + FiscalPeriod localFiscalPeriod; + try { + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + localFiscalPeriod = fiscalPeriodTopiaDao.findByTopiaId(fiscalPeriod.getTopiaId()); + } catch (TopiaException ex) { + throw new LimaException("Can't find fiscal period", ex); + } + + //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())) { + entryBook = entry; + found = true; + } + } + + //if entrybook isn't found + //then create it + if (!found) { + entryBook = entryBookService.createEntryBook(entryBook); + } + + //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) { + accountMaster = new AccountImpl(); + accountMaster.setAccountNumber("89"); + accountMaster.setLabel("BILAN"); + accountService.createAccount(accountMaster); + } + + //890 Bilan d'ouverture + Account beginRetainedAccount = accountService.getAccountByNumber("890"); + if (beginRetainedAccount == null) { + beginRetainedAccount = new AccountImpl(); + beginRetainedAccount.setAccountNumber("890"); + beginRetainedAccount.setLabel("Bilan d'ouverture"); + accountService.createAccount(beginRetainedAccount); + } + + //891 Bilan de cloture + Account endRetainedAccount = accountService.getAccountByNumber("891"); + if (endRetainedAccount == null) { + endRetainedAccount = new AccountImpl(); + endRetainedAccount.setAccountNumber("891"); + endRetainedAccount.setLabel("Bilan de clôture"); + endRetainedAccount = accountService.createAccount(endRetainedAccount); + } + + //look for the last financial period from the previous fiscal year + //check if the last financial period isn't blocked + Collection<FinancialPeriod> fperiod = localFiscalPeriod.getFinancialPeriod(); + Iterator<FinancialPeriod> itr = fperiod.iterator(); + FinancialPeriod lastFPeriod = null; + while (itr.hasNext()) { + lastFPeriod = itr.next(); + } + + FinancialPeriod beginfinancialPeriod = null; + + //look for the first financial period on the new fiscal year which is unlocked + found = false; + List<ClosedPeriodicEntryBook> resultsArray = + new ArrayList<ClosedPeriodicEntryBook>(); + List<ClosedPeriodicEntryBook> closedPeriodicEntryBook = + financialPeriodService.getAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod(); + Collections.sort(closedPeriodicEntryBook, new FinancialPeriodComparator()); + resultsArray.addAll(closedPeriodicEntryBook); + for (ClosedPeriodicEntryBook cPeriodicEntryBook : resultsArray) { + + //check for - unlocked financial period + // - date after the closing fiscal year + // - unlocked entrybook + // - right code and label + if (!found && !cPeriodicEntryBook.getFinancialPeriod().isLocked() + && cPeriodicEntryBook.getFinancialPeriod().getBeginDate().after(localFiscalPeriod.getEndDate()) + && !cPeriodicEntryBook.isLocked() + && cPeriodicEntryBook.getEntryBook().getCode().equals(entryBook.getCode()) + && cPeriodicEntryBook.getEntryBook().getLabel().equals(entryBook.getLabel())) { + found = true; + beginfinancialPeriod = cPeriodicEntryBook.getFinancialPeriod(); + } + } + if (!found) { + throw new LimaBusinessException(t("lima-business.fiscalperiod.newfinancialperioderror")); + } + + //holds entries of all closing transactions + FinancialTransaction endfinancialTransaction = new FinancialTransactionImpl(); + if (lastFPeriod != null) { + //Sets the endfinancialTransaction + endfinancialTransaction.setEntryBook(entryBook); + endfinancialTransaction.setTransactionDate(localFiscalPeriod.getEndDate()); + endfinancialTransaction = financialTransactionService.createFinancialTransaction(endfinancialTransaction); + } + + //holds entries of all opening transactions + FinancialTransaction beginfinancialTransaction = new FinancialTransactionImpl(); + + //Sets the endfinancialTransaction + beginfinancialTransaction.setEntryBook(entryBook); + beginfinancialTransaction.setTransactionDate(beginfinancialPeriod.getBeginDate()); + beginfinancialTransaction = financialTransactionService.createFinancialTransaction(beginfinancialTransaction); + + + //Sets date for description, e.g: Report à nouveau (DATE) + Calendar calendar = Calendar.getInstance(); + calendar.setTime(fiscalPeriod.getEndDate()); + + //Sets entries + BalanceTrial results = reportService.generateBalanceTrial(localFiscalPeriod.getBeginDate(), + localFiscalPeriod.getEndDate(), null, false, false); + + List<ReportsDatas> reportsDatasList = (List<ReportsDatas>) results.getReportsDatas(); + + 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)) { + + //close accounts by removing amounts from all class 1 to 5 accounts + Entry beginEntry = new EntryImpl(); + beginEntry.setDescription(t("lima-business.financialtransaction.retainedearnings.description") + " (" + calendar.get(Calendar.YEAR) + ")"); + beginEntry.setVoucher(t("lima-business.financialtransaction.retainedearnings.voucher")); + beginEntry.setFinancialTransaction(endfinancialTransaction); + beginEntry.setAccount(report.getAccount()); + beginEntry.setAmount(report.getAmountSolde().abs()); + beginEntry.setDebit(!report.getSoldeDebit()); + financialTransactionService.createEntry(beginEntry); + + //save amounts inside account number 891 + beginEntry = new EntryImpl(); + beginEntry.setDescription(t("lima-business.financialtransaction.retainedearnings.description") + " (" + calendar.get(Calendar.YEAR) + ")"); + beginEntry.setVoucher(t("lima-business.financialtransaction.retainedearnings.voucher")); + beginEntry.setFinancialTransaction(endfinancialTransaction); + beginEntry.setAccount(endRetainedAccount); + beginEntry.setAmount(report.getAmountSolde().abs()); + beginEntry.setDebit(report.getSoldeDebit()); + financialTransactionService.createEntry(beginEntry); + + //open new year accounts if new year exists and a date has been found for the transaction + //give back amounts from class 1 to 5 accounts + beginEntry = new EntryImpl(); + beginEntry.setDescription(t("lima-business.financialtransaction.retainedearnings.description") + " (" + calendar.get(Calendar.YEAR) + ")"); + beginEntry.setVoucher(t("lima-business.financialtransaction.retainedearnings.voucher")); + beginEntry.setFinancialTransaction(beginfinancialTransaction); + beginEntry.setAccount(report.getAccount()); + beginEntry.setAmount(report.getAmountSolde().abs()); + beginEntry.setDebit(report.getSoldeDebit()); + financialTransactionService.createEntry(beginEntry); + //close account by removing amount from account number 890 + beginEntry = new EntryImpl(); + beginEntry.setDescription(t("lima-business.financialtransaction.retainedearnings.description") + " (" + calendar.get(Calendar.YEAR) + ")"); + beginEntry.setVoucher(t("lima-business.financialtransaction.retainedearnings.voucher")); + beginEntry.setFinancialTransaction(beginfinancialTransaction); + beginEntry.setAccount(endRetainedAccount); + beginEntry.setAmount(report.getAmountSolde().abs()); + beginEntry.setDebit(!report.getSoldeDebit()); + financialTransactionService.createEntry(beginEntry); + } + } + } + + /*block the antepenultimate fiscalPeriod */ + FiscalPeriod fiscalPeriodBlocked = blockFiscalPeriod(fiscalPeriod); + return fiscalPeriodBlocked; + } + + /** + * to delete a fiscal period + * <p/> + * check localized rules before delete it + */ + @Override + public void deleteFiscalPeriod(FiscalPeriod fiscalPeriod) + throws LimaException { + + AccountingRules accountingRules = LimaConfig.getInstance().getAccountingRules(); + + try { + try { + //get entities with TopiaDao + FiscalPeriodTopiaDao fiscalPeriodTopiaDao = getDaoHelper().getFiscalPeriodTopiaDao(); + + // re-attach entities to current session + FiscalPeriod localFiscalPeriod = fiscalPeriodTopiaDao.findByTopiaId(fiscalPeriod.getTopiaId()); + + //check rules + accountingRules.deleteFiscalPeriodRules(localFiscalPeriod); + + //all "ClosedPeriodicEntryBooks" for the fiscal period + ClosedPeriodicEntryBookTopiaDao closedPeriodicEntryBookTopiaDao = getDaoHelper().getClosedPeriodicEntryBookTopiaDao(); + List<ClosedPeriodicEntryBook> closedPeriodicEntryBookTopiaDaoList = closedPeriodicEntryBookTopiaDao.findAllClosedPeriodicEntryBooksFromFiscalPeriod(localFiscalPeriod); + + //delete closedPeriodicEntryBook before fiscal period + for (ClosedPeriodicEntryBook closedPeriodicEntryBook : closedPeriodicEntryBookTopiaDaoList) { + // fix : ObjectDeletedException: deleted object would be re-saved by cascade (Need to delete association between entryBook and financial period via closedPeriodEntityBook) + closedPeriodicEntryBook.getEntryBook().removeFinancialPeriodClosedPeriodicEntryBook(closedPeriodicEntryBook); + closedPeriodicEntryBookTopiaDao.delete(closedPeriodicEntryBook); + } + + fiscalPeriodTopiaDao.delete(localFiscalPeriod); + + } catch (TopiaException ex) { + throw new LimaException("Can't find fiscal period", ex); + } + + } catch (Exception ex) { + throw new LimaException("Can't delete period", ex); + } + + } + +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/HttpServerServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,372 @@ +/* + * #%L + * Lima business + * + * $Id: HttpServerServiceImpl.java 3777 2014-04-14 07:29:08Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import static org.nuiton.i18n.I18n.t; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.net.URLDecoder; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import javax.ejb.EJB; +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.Charsets; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateUtils; +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.api.AccountService; +import org.chorem.lima.business.api.DocumentService; +import org.chorem.lima.business.api.HttpServerService; +import org.chorem.lima.business.utils.DocumentsEnum; +import org.chorem.lima.business.utils.FormatsEnum; +import org.chorem.lima.entity.Account; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.hibernate.exception.GenericJDBCException; +import org.nuiton.util.FileUtil; +import org.nuiton.util.Resource; + +@Stateless +@Remote(HttpServerService.class) +@TransactionAttribute +public class HttpServerServiceImpl extends AbstractLimaService implements HttpServerService { + + protected static final Log log = LogFactory.getLog(HttpServerServiceImpl.class); + + @EJB + private DocumentService documentService; + + @EJB + private AccountService accountService; + + 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().getAbsolutePath(); + port = LimaConfig.getInstance().getHttpPort(); + } + + /** start the server */ + @Override + public void start() { + if (server == null) { + try { + FileUtil.createDirectoryIfNecessary(new File(path)); + + server = new Server(port); + + ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); + context.setContextPath("/"); + context.addServlet(new ServletHolder(new MainServlet()),"/"); + server.setHandler(context); + server.start(); + + if (log.isInfoEnabled()) { + 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; + } + + /** + * 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 { + + if (log.isDebugEnabled()) { + log.debug("doGet"); + } + + //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"); + String account = (StringUtils.isBlank(req.getParameter("account"))?null:URLDecoder.decode(req.getParameter("account"), "UTF-8")); + + //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); + } + } + else if (model != null /*&& format != null*/ && beginDate != null && endDate != null) { + //FormatsEnum formatsEnum = FormatsEnum.valueOfExtension(format); + String accountReport = null; + String entryBooksReport = null; + String generalEntryBooksReport = null; + String balanceReport = null; + String ledgerReport = null; + String financialReport = null; + + //create docs + try { + Date beginDateFormat = DATEFORMAT.parse(beginDate); + Date endDateFormat = DATEFORMAT.parse(endDate); + + switch (DocumentsEnum.valueOfLink(model)) { + case BALANCE: + balanceReport = documentService.createBalanceDocuments( + beginDateFormat, endDateFormat); + break; + case ACCOUNT: + accountReport = documentService.createAccountDocument( + beginDateFormat, endDateFormat, account); + break; + case ENTRYBOOKS: + entryBooksReport = documentService.createEntryBooksDocuments( + beginDateFormat, endDateFormat); + if (log.isDebugEnabled()) { + log.debug("EntryBookReport :" + entryBooksReport); + } + break; + case GENERAL_ENTRYBOOK: + generalEntryBooksReport = documentService.createGeneralEntryBooksDocuments( + beginDateFormat, endDateFormat); + if (log.isDebugEnabled()) { + log.debug("GeneralEntryBooksReport :" + generalEntryBooksReport); + } + break; + case FINANCIALSTATEMENT: + financialReport = documentService.createFinancialStatementsDocuments( + beginDateFormat, endDateFormat); + break; + case LEDGER: + ledgerReport = documentService.createLedgerDocuments( + beginDateFormat, endDateFormat); + break; + case VAT: + if (log.isDebugEnabled()) { + log.debug("autocomplete : " + autocomplete); + } + documentService.createVatDocuments( + beginDateFormat, endDateFormat, + 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); + } + + if ( (accountReport != null || entryBooksReport != null || generalEntryBooksReport != null + || balanceReport != null || ledgerReport != null || financialReport != null)) { + String report; + resp.setContentType(".html"); + OutputStream out = resp.getOutputStream(); + if (accountReport != null) { + report = accountReport; + } else if (entryBooksReport != null) { + report = entryBooksReport; + } else if (generalEntryBooksReport != null) { + report = generalEntryBooksReport; + } else if (balanceReport != null) { + report = balanceReport; + } else if (ledgerReport != null) { + report = ledgerReport; + } else { + report = financialReport; + } + IOUtils.write(report, out, Charsets.UTF_8); + } else { + URL doc = new URL("file:" + path + File.separator + model + ".pdf"); + if (log.isDebugEnabled()) { + log.debug("file:" + path + File.separator + model + ".pdf"); + } + resp.setContentType(".pdf"); + OutputStream out = resp.getOutputStream(); + InputStream in = doc.openStream(); + IOUtils.copy(in, out); + } + } + // else return home html + else { + + if (log.isDebugEnabled()) { + log.debug("Home html"); + } + + resp.setContentType(FormatsEnum.HTML.getMimeType()); + StringBuilder pageContent = new StringBuilder(); + 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 { + 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" + + "<script type=\"text/javascript\">" + + " function showAccountInput(){" + + " var request = document.getElementById('model');" + + " var requestValue = request == null ? '': request.value;" + + " var isDocumentAccount = requestValue === 'lima_account'; " + + " if (document.getElementById('accountField') != null) {" + + " if (isDocumentAccount) {" + + " document.getElementById('accountField').style.display = 'block';" + + " } else {" + + " document.getElementById('accountField').style.display = 'none';" + + " }" + + " }" + + " }" + + " showAccountInput();" + + " </script>" + + "<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=") + .append(serverAdress).append(">\n") + .append(t("lima-business.document.date.begin")) + .append("<input value=\"") + .append(DATEFORMAT.format(beginDatePicker)) + .append("\" type=\"date\" name=\"beginDate\">\n") + .append(t("lima-business.document.date.end")) + .append("<input value=\"") + .append(DATEFORMAT.format(endDatePicker)) + .append("\" type=\"date\" name=\"endDate\">\n<br/><br/>"); + //+ "Format : <select name=\"format\">"); + + /*TODO : voir pour générer des pdf avec éventuellement iReport*/ + /*for (FormatsEnum formatsEnum : FormatsEnum.values()) { + pageContent.append("<option value=\"" + + formatsEnum.getExtension() + "\">" + + formatsEnum.getDescription() + "</option>\n"); + }*/ + + pageContent.append(/*"</select>\n" + + */"Documents : <select id=\"model\" name=\"model\" onchange='showAccountInput()'>"); + + for (DocumentsEnum documentsEnum : DocumentsEnum.values()) { + pageContent.append("<option value=\"") + .append(documentsEnum.getFileName()) + .append("\">") + .append(documentsEnum.getDescription()) + .append("</option>\n"); + } + + List<Account> accounts = accountService.getAllAccounts(); + + StringBuilder optionAccounts = new StringBuilder(); + for (Account account1:accounts) { + optionAccounts.append("<option value=\"" + account1.getTopiaId() + "\">"); + optionAccounts.append(account1.getAccountNumber() + " - " + account1.getLabel()); + optionAccounts.append("</option>\n"); + } + + pageContent.append("</select>" + + "<div id='accountField'>Compte : <select id=\"account\" name=\"account\">" + + optionAccounts.toString() + + "</select></div>" + + "<input type=\"submit\">\n" + + "</form></td>" + + "<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" + + "<tr><td class=\"tdright\"><img src=\"?img=fiscalperiods.png\"/></td></tr>\n" + + "</table>\n" + + "<script type=\"text/javascript\">" + + " showAccountInput();" + + "</script>" + + "</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); + } + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/IdentityServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,77 @@ +/* + * #%L + * Lima business + * + * $Id: IdentityServiceImpl.java 3410 2012-05-11 10:26:46Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import java.util.List; + +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.IdentityService; +import org.chorem.lima.entity.Identity; +import org.chorem.lima.entity.IdentityTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +@Stateless +@Remote(IdentityService.class) +@TransactionAttribute +public class IdentityServiceImpl extends AbstractLimaService implements IdentityService { + + @Override + public Identity getIdentity() + throws LimaException { + Identity identity = null; + try { + + IdentityTopiaDao identityTopiaDao = getDaoHelper().getIdentityTopiaDao(); + List<Identity> identities = identityTopiaDao.findAll(); + if (identities.size() != 0) { + identity = identities.get(0); + } + } catch (TopiaException ex) { + throw new LimaException("Can't get identity", ex); + } + return identity; + } + + @Override + public void updateIdentity(Identity identity) throws LimaException { + try { + IdentityTopiaDao identityTopiaDao = getDaoHelper().getIdentityTopiaDao(); + List<Identity> identities = identityTopiaDao.findAll(); + if (identities.size() != 0) { + identityTopiaDao.delete(identities.get(0)); + } + identityTopiaDao.create(identity); + + } catch (TopiaException ex) { + throw new LimaException("Can't update identity", ex); + } + } + +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ImportServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,1273 @@ +/* + * #%L + * Lima business + * + * $Id: ImportServiceImpl.java 3782 2014-05-06 15:41:32Z dcosse $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import static org.nuiton.i18n.I18n.t; + +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 javax.ejb.EJB; +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +import org.apache.commons.lang3.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; +import org.chorem.lima.FinancialStatementWayEnum; +import org.chorem.lima.beans.AccountEBP; +import org.chorem.lima.beans.AccountEBPImpl; +import org.chorem.lima.beans.ClosedPeriodicEntryBookImport; +import org.chorem.lima.beans.ClosedPeriodicEntryBookImportImpl; +import org.chorem.lima.beans.EntryEBP; +import org.chorem.lima.beans.EntryEBPImpl; +import org.chorem.lima.beans.EntryImport; +import org.chorem.lima.beans.EntryImportImpl; +import org.chorem.lima.beans.FinancialStatementImport; +import org.chorem.lima.beans.FinancialStatementImportImpl; +import org.chorem.lima.beans.FinancialTransactionImport; +import org.chorem.lima.beans.FinancialTransactionImportImpl; +import org.chorem.lima.beans.VatStatementImport; +import org.chorem.lima.beans.VatStatementImportImpl; +import org.chorem.lima.business.LimaBusinessException; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.AccountService; +import org.chorem.lima.business.api.ClosedPeriodicEntryBookService; +import org.chorem.lima.business.api.EntryBookService; +import org.chorem.lima.business.api.EntryService; +import org.chorem.lima.business.api.FinancialPeriodService; +import org.chorem.lima.business.api.FinancialStatementService; +import org.chorem.lima.business.api.FinancialTransactionService; +import org.chorem.lima.business.api.FiscalPeriodService; +import org.chorem.lima.business.api.IdentityService; +import org.chorem.lima.business.api.ImportService; +import org.chorem.lima.business.api.VatStatementService; +import org.chorem.lima.business.utils.DocumentsEnum; +import org.chorem.lima.business.utils.EntryEBPComparator; +import org.chorem.lima.business.utils.FiscalPeriodComparator; +import org.chorem.lima.business.utils.ImportExportEntityEnum; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountImpl; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryBookImpl; +import org.chorem.lima.entity.EntryImpl; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialStatement; +import org.chorem.lima.entity.FinancialStatementImpl; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionImpl; +import org.chorem.lima.entity.FiscalPeriod; +import org.chorem.lima.entity.FiscalPeriodImpl; +import org.chorem.lima.entity.Identity; +import org.chorem.lima.entity.IdentityImpl; +import org.chorem.lima.entity.VatStatement; +import org.chorem.lima.entity.VatStatementImpl; +import org.nuiton.topia.persistence.TopiaException; + +import au.com.bytecode.opencsv.CSVReader; +import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy; +import au.com.bytecode.opencsv.bean.CsvToBean; + +/** + * Import export service. + * Currently import and export as CSV and EBP. + */ +@Stateless +@Remote(ImportService.class) +@TransactionAttribute +public class ImportServiceImpl extends AbstractLimaService implements ImportService { + + private static final Log log = LogFactory.getLog(ImportServiceImpl.class); + + protected final String DATE_PATTERN = "dd/MM/yyyy"; + + @EJB + private AccountService accountService; + + @EJB + private FiscalPeriodService fiscalPeriodService; + + @EJB + private FinancialPeriodService financialPeriodService; + + @EJB + private FinancialTransactionService financialTransactionService; + + @EJB + private FinancialStatementService financialStatementService; + + @EJB + private VatStatementService vatStatementService; + + @EJB + private EntryBookService entryBookService; + + @EJB + private IdentityService identityService; + + @EJB + private ClosedPeriodicEntryBookService closedPeriodicEntryBookService; + + @EJB + private EntryService entryService; + + private static final SimpleDateFormat SDATEFORMAT = new SimpleDateFormat( + "dd,MM,yyyy HH:mm:ss"); + + // ################ IMPORT THIRD PART ACCOUNTING SOFTWARE ################ + + @Override + public String importEntriesFromEbp(String datas) throws LimaException { + + if (datas.isEmpty()) { + throw new LimaBusinessException(t("lima-business.import.ebpnoentry")); + } + + // use for logs + long before = System.currentTimeMillis(); + + SimpleDateFormat epbDateFormat = new SimpleDateFormat(DATE_PATTERN); + StringBuilder result = new StringBuilder(); + CSVReader csvReader = null; + + try { + csvReader = new CSVReader(new StringReader(datas)); + ColumnPositionMappingStrategy<EntryEBPImpl> strat = new ColumnPositionMappingStrategy<EntryEBPImpl>(); + strat.setType(EntryEBPImpl.class); + // read header to set strategy mapping + strat.setColumnMapping(csvReader.readNext()); + + // check if file have a good header + List<String> headEntry = new ArrayList<String>(); + headEntry.add("DatEcr"); + headEntry.add("Journal"); + headEntry.add("Compte"); + headEntry.add("Libelle"); + headEntry.add("Piece"); + headEntry.add("Debit"); + headEntry.add("Credit"); + headEntry.add("Lettre"); + if (!Arrays.asList(strat.getColumnMapping()).containsAll(headEntry)) { + throw new LimaBusinessException( + t("lima-business.import.ebpnoheader")); + } + + // Sorts the list according to the entry date + CsvToBean<EntryEBPImpl> csv = new CsvToBean<EntryEBPImpl>(); + List<EntryEBPImpl> list = csv.parse(strat, csvReader); + Collections.sort(list, new EntryEBPComparator()); + + // Get all the valid fiscalPeriods Ordered by date. + List<FiscalPeriod> fiscalPeriods = fiscalPeriodService + .getAllUnblockedFiscalPeriods(); + Collections.sort(fiscalPeriods, new FiscalPeriodComparator()); + + // There are no valid fiscalPeriods -> exception + int nbFiscalPeriods = fiscalPeriods.size(); + if (nbFiscalPeriods == 0) { + throw new LimaBusinessException( + t("lima-business.import.nofiscalperiodopen")); + } + + // attributes declaration + FinancialTransaction financialTransaction = null; + Date dateEcr; + Account account; + Entry entry; + BigDecimal debit; + String entryBookCode; + EntryBook entryBook; + + // For all entries loaded from the file + // the entry is validate (checking for valide FiscalPeriod and existing Account associated to it) + // if valid entry + // the entry entity is created and the association with it's dependant entites (Account are FinancialTransaction) are created + + for (EntryEBP entryEBP : list) { + dateEcr = epbDateFormat.parse(entryEBP.getDatEcr()); + + // account loading + account = accountService.getAccountByNumber(entryEBP.getCompte()); + + // if entry date have fiscalperiod open + if (dateEcr.compareTo(fiscalPeriods.get(0).getBeginDate()) < 0 + || dateEcr.compareTo(fiscalPeriods.get(nbFiscalPeriods - 1).getEndDate()) > 0) { + result.append(t( + "lima-business.import.entriesoutofdatesrange", dateEcr)); + } + + // if account not exist not export -> exception + else if (account == null) { + throw new LimaBusinessException(t( + "lima-business.import.ebpmissingaccount", + entryEBP.getCompte())); + } + + // create entry + else { + + // creation of the entry + // initialisation of this attributs + + entry = new EntryImpl(); + + // the entry has one amount witch can be Debit or Credit + // regarding the value of the boolean:debit + debit = new BigDecimal(entryEBP.getDebit()); + if (BigDecimal.ZERO.compareTo(debit)==0) { + entry.setDebit(false); + entry.setAmount(new BigDecimal(entryEBP.getCredit())); + } else { + entry.setDebit(true); + entry.setAmount(debit); + } + entry.setAccount(account); + entry.setDescription(StringUtils.trimToNull(entryEBP.getLibelle())); + entry.setVoucher(StringUtils.trimToNull(entryEBP.getPiece())); + entry.setLettering(StringUtils.trimToNull(entryEBP.getLettre())); + + // Association of the entry with the financialTransaction + // Each financialTransaction is associated with an entryBook + // loading of the entryBook from the db according to the entryBookCode + // if the entryBook doesn't exist it's entity is created + // if any financialTransaction exist for the entry + // a financialTransaction entity is created associated with the entryBook + // creation of the entry entity + // association between the entry and the financialTransaction is done. + + entryBookCode = entryEBP.getJournal(); + // entryBook loading + entryBook = entryBookService.getEntryBookByCode(entryBookCode); + + // if entrybook not exist create it ! + if (entryBook == null) { + entryBook = new EntryBookImpl(); + entryBook.setCode(entryBookCode); + //financialTransaction = null; + // create it + entryBook = entryBookService.createEntryBook(entryBook); + result.append(t( + "lima-business.import.entrybooknotexist", + entryBook)); + } + + // create transaction + if (financialTransaction == null + || !(dateEcr.equals(financialTransaction + .getTransactionDate()) && entryBook + .getCode().equals( + financialTransaction.getEntryBook() + .getCode()))) { + // create financial transaction + financialTransaction = new FinancialTransactionImpl(); + financialTransaction.setEntryBook(entryBook); + financialTransaction.setTransactionDate(dateEcr); + financialTransaction = financialTransactionService + .createFinancialTransaction(financialTransaction); + result.append(t( + "lima-business.import.transactionadded", dateEcr, + entryBook.getCode())); + } + // Inside the db, the entries reference the financialTransaction + entry.setFinancialTransaction(financialTransaction); + entry = financialTransactionService.createEntry(entry); + result.append(t("lima-business.import.entryadded", + entry.getDescription(), entry.getAmount())); + + } + } + if (log.isInfoEnabled()) { + + long after = System.currentTimeMillis(); + log.info("Imported form EBP : " + list.size() + " entries in " + + (after - before) + " ms"); + } + } catch (Exception ex) { + throw new LimaException("Can't import", ex); + } finally { + if (csvReader != null) { + try { + csvReader.close(); + } catch (IOException e) { + // on fait rien + } + } + } + return result.toString(); + } + + @Override + public String importAccountsChartFromEbp(String datas) throws LimaException { + long before = System.currentTimeMillis(); + StringBuilder result = new StringBuilder(); + CSVReader csvReader = null; + try { + csvReader = new CSVReader(new StringReader(datas)); + ColumnPositionMappingStrategy<AccountEBPImpl> strat = new ColumnPositionMappingStrategy<AccountEBPImpl>(); + strat.setType(AccountEBPImpl.class); + // read header to set strategy mapping + strat.setColumnMapping(csvReader.readNext()); + // check if file have a good header + List<String> headAccount = new ArrayList<String>(); + headAccount.add("Numero"); + headAccount.add("Intitule"); + if (!Arrays.asList(strat.getColumnMapping()).containsAll( + headAccount)) { + throw new LimaBusinessException( + t("lima-business.import.noaccount")); + } + + // FIXME echatellier 20120424 read csv line by line without + // creating beans instance + CsvToBean<AccountEBPImpl> csv = new CsvToBean<AccountEBPImpl>(); + List<AccountEBPImpl> list = csv.parse(strat, csvReader); + + for (AccountEBP accountEBP : list) { + String accountNumber = accountEBP.getNumero(); + String label = accountEBP.getIntitule(); + Account account = new AccountImpl(); + account.setAccountNumber(accountNumber); + account.setLabel(label); + accountService.createAccount(account); + result.append(t("lima-business.import.accountadded", + accountNumber, label)); + } + + if (log.isInfoEnabled()) { + long after = System.currentTimeMillis(); + log.info("Imported form EBP : " + list.size() + " accounts in " + + (after - before) + " ms"); + } + + } catch (Exception ex) { + throw new LimaException("Can't import", ex); + } finally { + if (csvReader != null) { + try { + csvReader.close(); + } catch (IOException e) { + // on fait rien + } + } + } + return result.toString(); + } + + @Override + public String importEntryBookFromEbp(String datas) throws LimaException { + long before = System.currentTimeMillis(); + + StringBuilder result = new StringBuilder(); + CSVReader csvReader = null; + + try { + csvReader = new CSVReader(new StringReader(datas)); + + // check if file have a good header + String[] headers = csvReader.readNext(); + if (!headers[0].equals("Code") || !headers[2].equals("Libelle")) { + throw new LimaBusinessException( + t("lima-business.import.noaccount")); + } + + // create entry book for each line + int count = 0; + String[] line = csvReader.readNext(); + while (line != null) { + EntryBook entryBook = new EntryBookImpl(); + entryBook.setCode(StringUtils.trimToNull(line[0])); + entryBook.setLabel(StringUtils.trimToNull(line[2])); + entryBookService.createEntryBook(entryBook); + result.append(t("lima-business.import.accountadded", entryBook.getCode(), entryBook.getLabel())); + count++; + + line = csvReader.readNext(); + } + + if (log.isInfoEnabled()) { + long after = System.currentTimeMillis(); + log.info("Imported form EBP : " + count + " accounts in " + (after-before) + " ms"); + } + + } catch (Exception ex) { + throw new LimaException("Can't import", ex); + } finally { + if (csvReader != null) { + try { + csvReader.close(); + } catch (IOException e) { + // on fait rien + } + } + } + + return result.toString(); + } + + + // ################ IMPORT ################ + + /** Remote methode to call all entities import from UI */ + @Override + public String importAllAsCSV(String datas) throws LimaException { + StringBuilder result = new StringBuilder(); + + Map<String, List<FinancialStatementImport>> financialStatements = + new LinkedHashMap<String, List<FinancialStatementImport>>(); + + Map<String, List<VatStatementImport>> vatStatements = + new LinkedHashMap<String, List<VatStatementImport>>(); + + List<FiscalPeriod> fiscalPeriods = new ArrayList<FiscalPeriod>(); + + List<ClosedPeriodicEntryBookImport> closedPeriodicEntryBooks = + new ArrayList<ClosedPeriodicEntryBookImport>(); + + Map<Integer, FinancialTransactionImport> financialTransactions = + new HashMap<Integer, FinancialTransactionImport>(); + + Map<Integer, List<EntryImport>> entries = + new HashMap<Integer, List<EntryImport>>(); + + CSVReader csvReader = null; + try { + + String[] nextLine; + csvReader = new CSVReader(new StringReader(datas), ';'); + + while ((nextLine = csvReader.readNext()) != null) { + ImportExportEntityEnum importExportEntityEnum = ImportExportEntityEnum + .valueOfLabel(nextLine[0]); + if (importExportEntityEnum != null) { + switch (importExportEntityEnum) { + case ACCOUNT: + result.append(importAccountsChartsCSV(nextLine)); + break; + case ENTRYBOOK: + result.append(importEntryBooksChartCSV(nextLine)); + break; + case FINANCIALSTATEMENT: + result.append(importFinancialsStatementChartCSV(nextLine, + financialStatements)); + break; + case VATSTATEMENT: + result.append(importVatStatementChartCSV(nextLine, + vatStatements)); + break; + case FISCALPERIOD: + result.append(importFiscalPeriodCSV(nextLine, + fiscalPeriods)); + break; + case CLOSEDPERIODICENTRYBOOK: + importClosedPeriodicEntryBookCSV(nextLine, + closedPeriodicEntryBooks); + break; + case FINANCIALTRANSACTION: + importFinancialTransactionsCSV(nextLine, + financialTransactions); + break; + case ENTRY: + importEntriesCSV(nextLine, entries); + break; + case IDENTITY: + importIdentity(nextLine); + break; + } + } + } + + // create financialStatements + result.append(createFinancialStatements(financialStatements)); + // create vatStatements + result.append(createVatStatements(vatStatements)); + // create fiscalperiod + Collections.sort(fiscalPeriods, new FiscalPeriodComparator()); + result.append(createFiscalPeriod(fiscalPeriods)); + // update closedperiodicentrybooks + result.append(updateClosedPeriodicEntryBooks(closedPeriodicEntryBooks)); + // create financialtransaction and entries + result.append(createFinancialTransactionsAndEntries( + financialTransactions, entries)); + + } catch (Exception ex) { + throw new LimaException("Can't import", ex); + } finally { + if (csvReader != null) { + try { + csvReader.close(); + } catch (IOException e) { + // on fait rien + } + } + } + return result.toString(); + } + + /** + * Remote methode to call entity import from UI + * This methode let import just on type of entity + */ + @Override + public String importAsCSV(String datas, + ImportExportEntityEnum importExportEntityEnum) + throws LimaException { + StringBuilder result = new StringBuilder(); + + // FinancialStatements + Map<String, List<FinancialStatementImport>> financialStatements = null; + // VatStatement + Map<String, List<VatStatementImport>> vatStatements = null; + // Transactions and entries + Map<Integer, FinancialTransactionImport> financialTransactions = null; + Map<Integer, List<EntryImport>> entries = null; + + + switch (importExportEntityEnum) { + case FINANCIALSTATEMENT: + financialStatements = new LinkedHashMap<String, List<FinancialStatementImport>>(); + break; + case VATSTATEMENT: + vatStatements = new LinkedHashMap<String, List<VatStatementImport>>(); + break; + case FINANCIALTRANSACTION: + case ENTRY: + financialTransactions = new HashMap<Integer, FinancialTransactionImport>(); + entries = new HashMap<Integer, List<EntryImport>>(); + break; + } + CSVReader csvReader = null; + try { + + String[] nextLine; + csvReader = new CSVReader(new StringReader(datas), ';'); + + while ((nextLine = csvReader.readNext()) != null) { + if (ImportExportEntityEnum.valueOfLabel(nextLine[0]) == importExportEntityEnum + || importExportEntityEnum == ImportExportEntityEnum.FINANCIALTRANSACTION + || importExportEntityEnum == ImportExportEntityEnum.ENTRY) { + switch (importExportEntityEnum) { + case ENTRYBOOK: + result.append(importEntryBooksChartCSV(nextLine)); + break; + case ACCOUNT: + result.append(importAccountsChartsCSV(nextLine)); + break; + case FINANCIALSTATEMENT: + result.append(importFinancialsStatementChartCSV(nextLine, + financialStatements)); + break; + case VATSTATEMENT: + result.append(importVatStatementChartCSV(nextLine, + vatStatements)); + break; + case FINANCIALTRANSACTION: + case ENTRY: + // Entries and transactions always go along + ImportExportEntityEnum type = + ImportExportEntityEnum.valueOfLabel(nextLine[0]); + if (type != null) { + switch (type) { + case FINANCIALTRANSACTION: + importFinancialTransactionsCSV(nextLine, + financialTransactions); + break; + case ENTRY: + importEntriesCSV(nextLine, entries); + break; + } + } + break; + } + } + } + + //create entity + switch (importExportEntityEnum) { + case FINANCIALSTATEMENT: + result.append(createFinancialStatements(financialStatements)); + break; + case VATSTATEMENT: + result.append(createVatStatements(vatStatements)); + break; + case FINANCIALTRANSACTION: + case ENTRY: + result.append(createFinancialTransactionsAndEntries( + financialTransactions, entries)); + break; + } + + } catch (Exception ex) { + throw new LimaException("Can't import", ex); + } finally { + if (csvReader != null) { + try { + csvReader.close(); + } catch (IOException e) { + // on fait rien + } + } + } + return result.toString(); + } + + @Override + public String importAsPDF(String datas, + ImportExportEntityEnum importExportEntityEnum, + boolean setMode) throws LimaException { + + StringBuilder result = new StringBuilder(); + + PDDocument doc = null; + try { + String path = LimaConfig.getInstance().getReportsDir().getAbsolutePath(); + + String filePathDefault = path + File.separator + + DocumentsEnum.VAT.getFileName() + "_default.pdf"; + String filePathStructured = path + File.separator + + DocumentsEnum.VAT.getFileName() + "_structure.pdf"; + + InputStream reportsStream = new FileInputStream(datas); + //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()); + } + + // 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); + } + } catch (IOException ex) { + log.error("Can't read vat pdf", ex); + result.append("Can't read vat pdf"); + } catch (COSVisitorException ex) { + log.error("Can't save vat pdf", ex); + result.append("Can't save vat pdf"); + } finally { + try { + if (doc != null) { + doc.close(); + } + } catch (Exception e) { + // Nothing to do + } + } + return result.toString(); + } + + /** + * Import and create accounts Structure : TYPE | accountNumber | label + * | [thirdparty] + * + * @param nextLine The line to import + * @return Success or error message + * @throws LimaException If the line format is invalid + * @throws TopiaException + */ + protected String importAccountsChartsCSV(String[] nextLine) + throws LimaException, TopiaException { + // Check line format + if (nextLine.length < 3 + || ! nextLine[0].equals(ImportExportEntityEnum.ACCOUNT.getLabel())) { + throw new LimaException(t("lima-business.import.lineformatmismatch")); + } + + StringBuilder result = new StringBuilder(); + + String accountNumber = nextLine[1]; + // if not exists, create it + if (accountService.getAccountByNumber(accountNumber) == null) { + + Account account = new AccountImpl(); + account.setAccountNumber(accountNumber); + String label = nextLine[2]; + account.setLabel(label); + if (nextLine.length > 3) { + String thirdParty = nextLine[3]; + account.setThirdParty(thirdParty); + } + + accountService.createAccount(account); + result.append(t("lima-business.import.accountadded", + account.getAccountNumber(), + account.getLabel())); + } else { + result.append(t("lima-business.import.accountalreadyexist", accountNumber)); + } + + return result.toString(); + } + + /** + * Import and create fiscal period Structure : TYPE | BeginDate | EndDate + * | Locked + * + * @param nextLine + * @param fiscalPeriods + * @return + * @throws ParseException + * @throws TopiaException + */ + protected String importFiscalPeriodCSV(String[] nextLine, + List<FiscalPeriod> fiscalPeriods) + throws ParseException, TopiaException { + StringBuilder result = new StringBuilder(); + + FiscalPeriod fiscalPeriod = new FiscalPeriodImpl(); + Date beginDate = SDATEFORMAT.parse(nextLine[1]); + fiscalPeriod.setBeginDate(beginDate); + Date endDate = SDATEFORMAT.parse(nextLine[2]); + fiscalPeriod.setEndDate(endDate); + fiscalPeriod.setLocked(Boolean.parseBoolean(nextLine[3])); + + // if not exist, skip + if (financialPeriodService.getFinancialPeriods(beginDate, endDate) == null) { + fiscalPeriods.add(fiscalPeriod); + } else { + result.append(t("lima-business.import.fiscalperiodalreadyexist", beginDate, endDate)); + } + + return result.toString(); + } + + /** + * Import and create entrybooks Structure : TYPE | Code | Label | Type + * + * @param nextLine + * @return + * @throws TopiaException + * @throws LimaException + */ + protected String importEntryBooksChartCSV(String[] nextLine) throws TopiaException, LimaException { + StringBuilder result = new StringBuilder(); + + EntryBook entryBook = new EntryBookImpl(); + entryBook.setCode(StringUtils.trimToNull(nextLine[1])); + entryBook.setLabel(StringUtils.trimToNull(nextLine[2])); + + // if exist, skip + if (entryBookService.getEntryBookByCode(entryBook.getCode()) != null) { + result.append(t("lima-business.import.entrybookalreadyexist", entryBook.getLabel())); + } else { + // create it + entryBookService.createEntryBook(entryBook); + result.append(t("lima-business.import.financialstatementadded", entryBook.getLabel())); + } + + return result.toString(); + } + + /** + * Import and create closedperiodicentrybook import Structure : TYPE | + * BeginDate | EndDate | Locked + * + * @param nextLine + * @param closedPeriodicEntryBooks + * @throws LimaException + */ + protected void importClosedPeriodicEntryBookCSV(String[] nextLine, + List<ClosedPeriodicEntryBookImport> closedPeriodicEntryBooks) throws LimaException { + String locked = nextLine[1]; + String beginDate = nextLine[2]; + String endDate = nextLine[3]; + String entryBookCode = nextLine[4]; + + if (Boolean.parseBoolean(locked)) { + ClosedPeriodicEntryBookImport closedPeriodicEntryBookImport = new ClosedPeriodicEntryBookImportImpl(); + closedPeriodicEntryBookImport.setLocked(locked); + closedPeriodicEntryBookImport + .setBeginDateFinancialPeriod(beginDate); + closedPeriodicEntryBookImport.setEndDateFinancialPeriod(endDate); + closedPeriodicEntryBookImport.setCodeEntryBook(entryBookCode); + + closedPeriodicEntryBooks.add(closedPeriodicEntryBookImport); + } + } + + /** + * Import and create financialstatement Structure : TYPE | label | header + * | accounts | debitAccount | creditAccount | + * provisitionDeprecationAccounts | subAmount | headerAmount + * | masterFinancialStatement + * + * @param nextLine + * @param financialStatements + * @return + * @throws LimaException + * @throws TopiaException + */ + protected String importFinancialsStatementChartCSV(String[] nextLine, + Map<String, List<FinancialStatementImport>> financialStatements) throws LimaException, TopiaException { + StringBuilder result = new StringBuilder(); + + String label = StringUtils.trimToNull(nextLine[1]); + String header = nextLine[2]; + String accounts = StringUtils.trimToNull(nextLine[3]); + String debitAccounts = StringUtils.trimToNull(nextLine[4]); + String creditAccounts = StringUtils.trimToNull(nextLine[5]); + String provisionDeprecationAccounts = StringUtils.trimToNull(nextLine[6]); + String subAmount = nextLine[7]; + String headerAmount = nextLine[8]; + String masterFinancialStatement = nextLine[9]; + String financialStatementWay = nextLine[10]; + + // if exist, skip + if (!financialStatementService.checkFinancialStatementExist(label)) { + // create it + FinancialStatementImport financialStatementImport = new FinancialStatementImportImpl(); + financialStatementImport.setLabel(label); + financialStatementImport.setHeader(header); + financialStatementImport.setAccounts(accounts); + financialStatementImport.setCreditAccounts(creditAccounts); + financialStatementImport.setDebitAccounts(debitAccounts); + financialStatementImport.setHeaderAmount(headerAmount); + financialStatementImport + .setProvisionDeprecationAccounts(provisionDeprecationAccounts); + financialStatementImport.setSubAmount(subAmount); + financialStatementImport + .setMasterFinancialStatement(masterFinancialStatement); + financialStatementImport.setWay(financialStatementWay); + + // put it in hashlinkedlist + if (financialStatements.containsKey(label)) { + financialStatements.get(label).add(financialStatementImport); + } else { + List<FinancialStatementImport> list = new ArrayList<FinancialStatementImport>(); + list.add(financialStatementImport); + financialStatements.put(label, list); + } + } else { + result.append(t("lima-business.import.financialstatementalreadyexist", label)); + } + + return result.toString(); + } + + + /** + * Import and create vatstatement Structure : TYPE | boxName | label + * | header | accounts | masterVatStatement + * + * @param nextLine + * @param vatStatements + * @return + * @throws LimaException + * @throws TopiaException + */ + protected String importVatStatementChartCSV(String[] nextLine, + Map<String, List<VatStatementImport>> vatStatements) throws LimaException, TopiaException { + + StringBuilder result = new StringBuilder(); + + String boxName = nextLine[1]; + String label = StringUtils.trimToNull(nextLine[2]); + String header = nextLine[3]; + String accounts = StringUtils.trimToNull(nextLine[4]); + String masterVatStatement = nextLine[5]; + + // if exist, skip + if (!vatStatementService.checkVatStatementExist(label)) { + // create it + VatStatementImport vatStatementImport = new VatStatementImportImpl(); + vatStatementImport.setLabel(label); + vatStatementImport.setBoxName(boxName); + vatStatementImport.setHeader(header); + vatStatementImport.setAccounts(accounts); + vatStatementImport.setMasterVatStatement(masterVatStatement); + + // put it in hashlinkedlist + if (vatStatements.containsKey(label)) { + vatStatements.get(label).add(vatStatementImport); + } else { + List<VatStatementImport> list = new ArrayList<VatStatementImport>(); + list.add(vatStatementImport); + vatStatements.put(label, list); + } + } else { + result.append(t("lima-business.import.vatstatementalreadyexist", label)); + } + + return result.toString(); + } + + + /** + * Import and create financialtransactions Structure : TYPE | NumTransac | + * TransactionDate | AmountDebit | AmountCredit | EntryBook Code + * + * @param nextLine + * @param financialTransactions + * @throws LimaException + */ + protected void importFinancialTransactionsCSV(String[] nextLine, + Map<Integer, FinancialTransactionImport> financialTransactions) throws LimaException { + int num = new Integer(nextLine[1]); + FinancialTransactionImport financialTransactionImport = new FinancialTransactionImportImpl(); + financialTransactionImport.setDate(nextLine[2]); + financialTransactionImport.setAmountDebit(nextLine[3]); + financialTransactionImport.setAmountCredit(nextLine[4]); + financialTransactionImport.setCodeEntryBook(nextLine[5]); + + financialTransactions.put(num, financialTransactionImport); + } + + /** + * Import and create entries Structure : TYPE | NumTransac | Description | + * Amount | Debit | Lettering | Detail | Voucher | Position | Account + * + * @param nextLine + * @param entries + * @throws LimaException + */ + protected void importEntriesCSV(String[] nextLine, + Map<Integer, List<EntryImport>> entries) throws LimaException { + int num = new Integer(nextLine[1]); + + EntryImport entryImport = new EntryImportImpl(); + entryImport.setDescription(StringUtils.trimToNull(nextLine[2])); + entryImport.setAmount(nextLine[3]); + entryImport.setDebit(nextLine[4]); + entryImport.setLettering(StringUtils.trimToNull(nextLine[5])); + entryImport.setDetail(StringUtils.trimToNull(nextLine[6])); + entryImport.setVoucher(StringUtils.trimToNull(nextLine[7])); + entryImport.setPosition(StringUtils.trimToNull(nextLine[8])); + entryImport.setAccount(nextLine[9]); + + if (entries.containsKey(num)) { + List<EntryImport> entryImports = entries.get(num); + entryImports.add(entryImport); + } else { + List<EntryImport> entryImports = new ArrayList<EntryImport>(); + entryImports.add(entryImport); + entries.put(num, entryImports); + } + } + + // ################ CREATE ENTITY IN DB FOR IMPORT ################ + + /** + * @throws TopiaException + * @deprecated do only one method import without bean use (and remove beans) + */ + @Deprecated + protected String createFinancialStatements(Map<String, List<FinancialStatementImport>> financialStatements) throws LimaException, TopiaException { + StringBuilder result = new StringBuilder(); + + while (financialStatements.size() > 0) { + for (Iterator<List<FinancialStatementImport>> itr = financialStatements + .values().iterator(); itr.hasNext(); ) { + List<FinancialStatementImport> financialStatementImports = + itr.next(); + + for (Iterator<FinancialStatementImport> itr2 = financialStatementImports.iterator(); itr2.hasNext(); ) { + FinancialStatementImport financialStatementImport = + itr2.next(); + String masterFinancialStatementLabel = financialStatementImport + .getMasterFinancialStatement(); + FinancialStatement masterFinancialStatement = financialStatementService.getFinancialStatementByLabel(masterFinancialStatementLabel); + + if (masterFinancialStatementLabel.equals("") + || masterFinancialStatement != null) { + // create it + FinancialStatement financialStatement = new FinancialStatementImpl(); + financialStatement.setLabel(financialStatementImport + .getLabel()); + financialStatement.setHeader(Boolean + .parseBoolean(financialStatementImport + .getHeader())); + financialStatement.setAccounts(financialStatementImport + .getAccounts()); + financialStatement + .setDebitAccounts(financialStatementImport + .getDebitAccounts()); + financialStatement + .setCreditAccounts(financialStatementImport + .getCreditAccounts()); + financialStatement + .setProvisionDeprecationAccounts(financialStatementImport + .getProvisionDeprecationAccounts()); + financialStatement.setSubAmount(Boolean + .parseBoolean(financialStatementImport + .getSubAmount())); + financialStatement.setHeaderAmount(Boolean + .parseBoolean(financialStatementImport + .getHeaderAmount())); + String financialStatementWay = financialStatementImport.getWay(); + if (!financialStatementWay.equals("")) { + FinancialStatementWayEnum financialStatementWayEnum = + FinancialStatementWayEnum.valueOf(financialStatementWay); + financialStatement.setWay(financialStatementWayEnum); + } + + + financialStatementService + .createFinancialStatement( + masterFinancialStatement, + financialStatement); + + result.append(t("lima-business.import.financialstatementadded", + financialStatementImport.getLabel())); + + itr2.remove(); + } else if (!financialStatements + .containsKey(masterFinancialStatementLabel)) { + result.append(t("lima-business.import.financialstatementalnomaster", + financialStatementImport.getLabel(), + masterFinancialStatementLabel)); + itr2.remove(); + } + } + if (financialStatementImports.isEmpty()) { + itr.remove(); + } + } + } + return result.toString(); + } + + /** + * @throws TopiaException + * @deprecated do only one method import without bean use (and remove beans) + */ + @Deprecated + protected String createVatStatements(Map<String, List<VatStatementImport>> vatStatements) throws LimaException, TopiaException { + + StringBuilder result = new StringBuilder(); + + while (vatStatements.size() > 0) { + for (Iterator<List<VatStatementImport>> itr = vatStatements + .values().iterator(); itr.hasNext(); ) { + List<VatStatementImport> vatStatementImports = + itr.next(); + + for (Iterator<VatStatementImport> itr2 = vatStatementImports.iterator(); itr2.hasNext(); ) { + VatStatementImport vatStatementImport = + itr2.next(); + String masterVatStatementLabel = vatStatementImport + .getMasterVatStatement(); + VatStatement masterVatStatement = vatStatementService.findVatStatementByLabel(masterVatStatementLabel); + + if (masterVatStatementLabel.equals("") + || masterVatStatement != null) { + // create it + VatStatement vatStatement = new VatStatementImpl(); + vatStatement.setBoxName(vatStatementImport + .getBoxName()); + vatStatement.setLabel(vatStatementImport + .getLabel()); + vatStatement.setAccounts(vatStatementImport + .getAccounts()); + vatStatement.setHeader(Boolean + .parseBoolean(vatStatementImport + .getHeader())); + + vatStatementService + .createVatStatement( + masterVatStatement, + vatStatement); + + result.append(t("lima-business.import.vatstatementadded", + vatStatementImport.getLabel())); + + itr2.remove(); + } else if (!vatStatements + .containsKey(masterVatStatementLabel)) { + result.append(t("lima-business.import.vatstatementalnomaster", + vatStatementImport.getLabel(), + masterVatStatementLabel)); + itr2.remove(); + } + } + if (vatStatementImports.isEmpty()) { + itr.remove(); + } + } + } + + return result.toString(); + } + + protected String createFiscalPeriod(List<FiscalPeriod> fiscalPeriods) { + StringBuilder result = new StringBuilder(); + for (FiscalPeriod fiscalPeriod : fiscalPeriods) { + // create fiscalPeriod + try { + fiscalPeriodService.createFiscalPeriod(fiscalPeriod); + result.append(t("lima-business.import.fiscalperiodadded", + fiscalPeriod.getBeginDate(), + fiscalPeriod.getEndDate())); + } catch (LimaException eee) { + result.append(t("lima-business.common.failed", eee.getMessage())); + } + } + return result.toString(); + } + + /** + * @throws ParseException + * @throws TopiaException + * @deprecated do only one method import without bean use (and remove beans) + */ + @Deprecated + protected String updateClosedPeriodicEntryBooks( + List<ClosedPeriodicEntryBookImport> closedPeriodicEntryBooks) throws LimaException, ParseException, TopiaException { + StringBuilder result = new StringBuilder(); + + for (ClosedPeriodicEntryBookImport closedPeriodicEntryBookImport : closedPeriodicEntryBooks) { + // update closedPeriodicEntryBook + Date beginDateFinancialPeriod = SDATEFORMAT + .parse(closedPeriodicEntryBookImport + .getBeginDateFinancialPeriod()); + Date endDateFinancialPeriod = SDATEFORMAT + .parse(closedPeriodicEntryBookImport + .getEndDateFinancialPeriod()); + FinancialPeriod financialPeriod = financialPeriodService.getFinancialPeriodByNaturalIds(beginDateFinancialPeriod, endDateFinancialPeriod); + + String codeEntryBook = closedPeriodicEntryBookImport + .getCodeEntryBook(); + EntryBook entryBook = entryBookService.getEntryBookByCode(codeEntryBook); + ClosedPeriodicEntryBook closedPeriodicEntryBook = closedPeriodicEntryBookService.getByEntryBookAndFinancialPeriod(entryBook, + financialPeriod); + try { + financialPeriodService + .blockClosedPeriodicEntryBook(closedPeriodicEntryBook); + result.append(t("lima-business.import.closedperiodicentrybookupdated", + beginDateFinancialPeriod, endDateFinancialPeriod, codeEntryBook)); + } catch (LimaException eee) { + result.append(t("lima-business.common.failed", eee)); + } + } + + return result.toString(); + } + + /** + * @throws ParseException + * @throws TopiaException + * @deprecated do only one method import without bean use (and remove beans) + */ + @Deprecated + protected String createFinancialTransactionsAndEntries( + Map<Integer, FinancialTransactionImport> financialTransactions, + Map<Integer, List<EntryImport>> entries) + throws LimaException, ParseException, TopiaException { + + for (Map.Entry<Integer, FinancialTransactionImport> map : financialTransactions + .entrySet()) { + FinancialTransactionImport financialTransactionImport = map + .getValue(); + FinancialTransaction financialTransaction = new FinancialTransactionImpl(); + Date dateFinancialTransaction = SDATEFORMAT + .parse(financialTransactionImport.getDate()); + financialTransaction + .setTransactionDate(dateFinancialTransaction); + + EntryBook entryBook = entryBookService.getEntryBookByCode(financialTransactionImport + .getCodeEntryBook()); + financialTransaction.setEntryBook(entryBook); + + financialTransactionService.createFinancialTransaction(financialTransaction); + + List<EntryImport> entryImports = entries.get(map.getKey()); + for (EntryImport entryImport : entryImports) { + Entry entry = new EntryImpl(); + Account account = accountService.getAccountByNumber(entryImport.getAccount()); + entry.setAccount(account); + entry.setDescription(StringUtils.trimToNull(entryImport.getDescription())); + entry.setAmount(new BigDecimal(entryImport.getAmount())); + entry.setDebit(Boolean.parseBoolean(entryImport.getDebit())); + entry.setLettering(StringUtils.trimToNull(entryImport.getLettering())); + entry.setDetail(StringUtils.trimToNull(entryImport.getDetail())); + entry.setVoucher(StringUtils.trimToNull(entryImport.getVoucher())); + entry.setPosition(StringUtils.trimToNull(entryImport.getPosition())); + entryService.createEntry(entry); + financialTransaction.addEntry(entry); + } + } + return ""; + } + + protected String importIdentity(String[] nextLine) throws LimaException { + StringBuilder result = new StringBuilder(); + + Identity identity = new IdentityImpl(); + nextLine[0] = ImportExportEntityEnum.IDENTITY.getLabel(); + identity.setName(nextLine[1]); + identity.setDescription(nextLine[2]); + identity.setAddress(nextLine[3]); + identity.setAddress2(nextLine[4]); + identity.setCity(nextLine[5]); + identity.setPhoneNumber(nextLine[6]); + identity.setEmail(nextLine[7]); + identity.setZipCode(nextLine[8]); + identity.setVatNumber(nextLine[9]); + identity.setClassificationCode(nextLine[10]); + identity.setBusinessNumber(nextLine[11]); + + identityService.updateIdentity(identity); + // create it + result.append(t("lima-business.import.identityadded", identity.getName())); + + return result.toString(); + } + +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/OptionsServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,66 @@ +/* + * #%L + * Lima :: business + * + * $Id: OptionsServiceImpl.java 3410 2012-05-11 10:26:46Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import javax.ejb.Remote; +import javax.ejb.Stateless; + +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.api.OptionsService; + +@Stateless +@Remote(OptionsService.class) +public class OptionsServiceImpl extends AbstractLimaService implements OptionsService { + + protected String scale; + + protected String vatPDFUrl; + + public OptionsServiceImpl() { + scale = LimaConfig.getInstance().getScale(); + vatPDFUrl = LimaConfig.getInstance().getVatPDFUrl(); + } + + public int getScale() { + if (scale == null || 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); + } + +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ReportServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,433 @@ +/* + * #%L + * Lima business + * + * $Id: ReportServiceImpl.java 3742 2014-01-31 14:17:41Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import org.apache.commons.lang3.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.LimaException; +import org.chorem.lima.business.api.AccountService; +import org.chorem.lima.business.api.FinancialPeriodService; +import org.chorem.lima.business.api.ReportService; +import org.chorem.lima.business.utils.AccountComparator; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountTopiaDao; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryTopiaDao; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FiscalPeriod; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.EJB; +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +@Stateless +@Remote(ReportService.class) +@TransactionAttribute +public class ReportServiceImpl extends AbstractLimaService implements ReportService { + + @EJB + protected FinancialPeriodService financialPeriodService; + + @EJB + protected AccountService accountService; + + protected static final Log log = LogFactory.getLog(ReportServiceImpl.class); + + /** + * Recursiv + * 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 + */ + @Override + public ReportsDatas generateAccountsReports(Account account, Boolean thirdPartAccountsMode, + Date beginDate, Date endDate) throws LimaException { + ReportsDatas reportsDatas; + + try { + BigDecimal credit = new BigDecimal(0); + BigDecimal debit = new BigDecimal(0); + BigDecimal solde = new BigDecimal(0); + List<Entry> entries = new ArrayList<Entry>(); + + reportsDatas = generateSubAccountReports(account, + beginDate, endDate); + debit = debit.add(reportsDatas.getAmountDebit()); + credit = credit.add(reportsDatas.getAmountCredit()); + entries.addAll(reportsDatas.getListEntry()); + + //Get allsubaccounts and thirdParts accounts + List<Account> accounts = accountService.getAllSubAccounts(account); + + for (Account subAccount : accounts) { + reportsDatas = generateSubAccountReports(subAccount, + beginDate, endDate); + debit = debit.add(reportsDatas.getAmountDebit()); + credit = credit.add(reportsDatas.getAmountCredit()); + entries.addAll(reportsDatas.getListEntry()); + } + + //solde = debit - credit + solde = solde.add(debit); + solde = solde.subtract(credit); + + if (solde.compareTo(BigDecimal.ZERO) == 1) { + reportsDatas.setSoldeDebit(true); + } + solde = solde.abs(); + reportsDatas.setAmountCredit(credit); + reportsDatas.setAmountDebit(debit); + reportsDatas.setAmountSolde(solde); + + reportsDatas.setListEntry(entries); + + } catch (TopiaException ex) { + throw new LimaException("Can't generate report", ex); + } + return reportsDatas; + } + + /** + * Get list entries + * Calculate all credit, debit and solde amounts for the accounts reports + * + * @param account + * @param beginDate + * @param endDate + * @return + * @throws LimaException + * @throws TopiaException + */ + protected ReportsDatas generateSubAccountReports(Account account, + Date beginDate, Date endDate) throws TopiaException { + ReportsDatas reportsDatas = new ReportsDatasImpl(); + BigDecimal credit = new BigDecimal(0); + BigDecimal debit = new BigDecimal(0); + BigDecimal solde = new BigDecimal(0); + + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + + // trouve les entrees associées à ca compte entre les date données + List<Entry> listEntries = entryTopiaDao.findAllEntryOfBalancedTransaction(account, beginDate, endDate); + reportsDatas.setListEntry(listEntries); + + // recupere les totaux pour le compte + List<Object[]> results = entryTopiaDao.getDebitCreditOfBalancedTransaction(account, beginDate, endDate); + int nbAmount = results.size(); + 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]; + } 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) { + reportsDatas.setSoldeDebit(true); + } + solde = solde.abs(); + + reportsDatas.setAmountCredit(credit); + reportsDatas.setAmountDebit(debit); + reportsDatas.setAmountSolde(solde); + + return reportsDatas; + } + + /** + * Calculate all credit, debit and solde amounts for the balance + * <p/> + * Get all entries if true + * @throws TopiaException + */ + public ReportsDatas generateSubAccountBalance(Account account, + Date beginDate, Date endDate, Boolean getEntries) throws LimaException, TopiaException { + ReportsDatas reportsDatas = new ReportsDatasImpl(); + BigDecimal credit = new BigDecimal(0); + BigDecimal debit = new BigDecimal(0); + BigDecimal solde = new BigDecimal(0); + + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + + if (getEntries) { + List<Entry> listEntries = entryTopiaDao.findAllEntryOfBalancedTransaction(account, beginDate, endDate); + reportsDatas.setListEntry(listEntries); + } + + List<Object[]> results = entryTopiaDao.getDebitCreditOfBalancedTransaction(account, beginDate, endDate); + int nbAmount = results.size(); + 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]; + } 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) { + reportsDatas.setSoldeDebit(true); + + } + solde = solde.abs(); + + reportsDatas.setAmountCredit(credit); + reportsDatas.setAmountDebit(debit); + reportsDatas.setAmountSolde(solde); + + 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 { + ReportsDatas reportsDatas = new ReportsDatasImpl(); + BigDecimal credit = new BigDecimal(0); + BigDecimal debit = new BigDecimal(0); + BigDecimal solde = new BigDecimal(0); + + // Get all entries with a topia query + try { + EntryTopiaDao entryTopiaDao = getDaoHelper().getEntryTopiaDao(); + List<Entry> entries = entryTopiaDao.findAllEntryOfBalancedTransaction(entryBook, beginDate, endDate); + reportsDatas.setListEntry(entries); + + List<Object[]> results = entryTopiaDao.getDebitCreditOfBalancedTransaction(entryBook, beginDate, endDate); + int nbAmount = results.size(); + 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]; + } 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) { + reportsDatas.setSoldeDebit(true); + } + solde = solde.abs(); + + reportsDatas.setAmountCredit(credit); + reportsDatas.setAmountDebit(debit); + reportsDatas.setAmountSolde(solde); + } catch (TopiaException ex) { + throw new LimaException("Can't generate report", ex); + } + + return reportsDatas; + } + + /** + * 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 + */ + @Override + 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); + + try { + + AccountTopiaDao accountTopiaDao = getDaoHelper().getAccountTopiaDao(); + //for each account create a balance sheet with a ReportsDatas + + List<Account> accounts; + + //Remove Spaces + String result = StringUtils.deleteWhitespace(selectedAccounts); + //if no filter account + if (result == null || result.equals("")) { + accounts = accountTopiaDao.findAll(); + } + //build list account from selectedAccounts + else { + accounts = accountTopiaDao.stringToListAccounts( result, false); + } + + Collections.sort(accounts, new AccountComparator()); + + for (Account account : accounts) { + ReportsDatas reportsDatas = + generateSubAccountBalance(account, beginDate, + endDate, getEntries); + reportsDatas.setAccount(account); + BigDecimal amount = reportsDatas.getAmountSolde(); + if (amount == null) { + amount = new BigDecimal(0); + } + if (movementedFilter) { + if (!reportsDatas.getAmountCredit().equals(BigDecimal.ZERO) + || !reportsDatas.getAmountDebit().equals(BigDecimal.ZERO)) { + // add balance sheet to balance trial + balanceTrial.addReportsDatas(reportsDatas); + } + } else { + // add balance sheet to balance trial + balanceTrial.addReportsDatas(reportsDatas); + } + + if (reportsDatas.getSoldeDebit()) { + debit = debit.add(amount); + } 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) { + balanceTrial.setSoldeDebit(true); + } + solde = solde.abs(); + balanceTrial.setAmountCredit(credit); + balanceTrial.setAmountDebit(debit); + balanceTrial.setAmountSolde(solde); + } catch (Exception ex) { + throw new LimaException("Can't generate report", ex); + } + + 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); + } + + /** + * Generate VAT + * + * @param fiscalPeriod + * @throws LimaException, TopiaException + */ + @Override + public List<Object> generateVat(FiscalPeriod fiscalPeriod) throws LimaException { + List<Object> list = new ArrayList<Object>(); + try { + + //lists all accounts + AccountTopiaDao accountTopiaDao = getDaoHelper().getAccountTopiaDao(); + List<Account> accountsList; + //gets all financial periods from the fiscal period + List<FinancialPeriod> financialPeriod = financialPeriodService.getFinancialPeriods( + fiscalPeriod.getBeginDate(), fiscalPeriod.getEndDate()); + for (FinancialPeriod fp : financialPeriod) { + list.add(fp); + accountsList = accountTopiaDao.findAll(); + for (Account account : accountsList) { + //VAT accounts start only with number 44 + //FIXME echatellier 44 is hardcoded and depends on + //french rule ? + if (account.getAccountNumber().startsWith("44")) { + list.add(generateBalanceTrial(fp.getBeginDate(), + fp.getEndDate(), account.getAccountNumber(), + true, false)); + } + } + } + } catch (TopiaException ex) { + throw new LimaException("Can't generate report", ex); + } + return list; + } +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/VatStatementServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,398 @@ +/* + * #%L + * Lima :: business + * + * $Id: VatStatementServiceImpl.java 3740 2014-01-17 22:12:04Z dcosse $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.ejb; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.ejb.EJB; +import javax.ejb.Remote; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +import org.chorem.lima.beans.ReportsDatas; +import org.chorem.lima.beans.VatStatementAmounts; +import org.chorem.lima.beans.VatStatementAmountsImpl; +import org.chorem.lima.beans.VatStatementDatas; +import org.chorem.lima.beans.VatStatementDatasImpl; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.business.api.ReportService; +import org.chorem.lima.business.api.VatStatementService; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountTopiaDao; +import org.chorem.lima.entity.VatStatement; +import org.chorem.lima.entity.VatStatementTopiaDao; +import org.nuiton.topia.persistence.TopiaException; + +/** + * Permet d'implémenter le plan de la déclaration de TVA + * + * @author vsalaun + */ +@Stateless +@Remote(VatStatementService.class) +@TransactionAttribute +public class VatStatementServiceImpl extends AbstractLimaService implements VatStatementService { + + @EJB + private ReportService reportService; + + @Override + public void createVatStatement(VatStatement masterVatStatement, + VatStatement vatStatement) throws LimaException { + + try { + VatStatementTopiaDao vatStatementTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + + vatStatementTopiaDao.create(vatStatement); + + VatStatement mastervatStatementUpdate = null; + if (masterVatStatement != null) { + mastervatStatementUpdate = vatStatementTopiaDao.findByLabel(masterVatStatement.getLabel()); + } + + // check if parent account exist; + if (mastervatStatementUpdate != null) { + mastervatStatementUpdate.addSubVatStatements(vatStatement); + vatStatementTopiaDao.update(mastervatStatementUpdate); + } + + } catch (TopiaException ex) { + throw new LimaException("Can't create vat statement", ex); + } + + } + + @Override + public List<VatStatement> getAllVatStatements() throws LimaException { + + List<VatStatement> vatStatements; + try { + VatStatementTopiaDao vatStatementTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + vatStatements = vatStatementTopiaDao.findAll(); + } catch (Exception ex) { + throw new LimaException("Can't get vat statements", ex); + } + return vatStatements; + + } + + @Override + public List<VatStatement> getAllChildrenVatStatement( + VatStatement vatStatement, List<VatStatement> result) throws LimaException { + + List<VatStatement> 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; + try { + + VatStatementTopiaDao vatStatementTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + vatStatements = vatStatementTopiaDao.getChildrenVatStatement(masterVatStatement); + } catch (TopiaException ex) { + throw new LimaException("Can't get vat statements", ex); + } + return vatStatements; + + } + + @Override + public void updateVatStatement(VatStatement vatStatement) throws LimaException { + + try { + // TopiaDao + VatStatementTopiaDao vatStatementHeaderTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + //update + vatStatementHeaderTopiaDao.update(vatStatement); + } catch (TopiaException ex) { + throw new LimaException("Can't update vat statement", ex); + } + } + + /* TODO echatellier 20120510 unused function + 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); + Boolean substract = false; + try { + AccountTopiaDao accountTopiaDao = LimaCallaoTopiaDaoHelper.getAccountTopiaDao(topiaContext); + //Remove Spaces + String result = StringUtils.deleteWhitespace(accountsNumberList); + StringTokenizer stQuote = new StringTokenizer(result, ","); + while (stQuote.hasMoreTokens()) { + String s = stQuote.nextToken(); + List<Account> accountsList = accountTopiaDao.stringToListAccounts(s, false); + BigDecimal debitTemp = new BigDecimal(0); + BigDecimal creditTemp = new BigDecimal(0); + for (Account account : accountsList) { + ReportsDatas reportsDatas = reportServiceLocal. + generateAccountReportsWithTransaction(account, true, + selectedBeginDate, selectedEndDate, topiaContext); + if (reportsDatas.getSoldeDebit()) { + debitTemp = debitTemp.add(reportsDatas.getAmountSolde()); + } else { + creditTemp = creditTemp.add(reportsDatas.getAmountSolde()); + } + } + if (!substract) { + debit = debitTemp; + credit = creditTemp; + } + //compte(s) précédé du signe - + else { + debit = debit.subtract(debitTemp); + credit = credit.subtract(creditTemp); + } + substract = true; + } + amounts.setCredit(credit); + amounts.setDebit(debit); + } catch (TopiaException e) { + doCatch(topiaContext, e); + } + return amounts; + }*/ + + /** + * Gives the list of account numbers from a VatStatement. + * + * @param vatStatement + * @return accountNumbersList + * @throws LimaException + */ + protected String findAccountNumberByVatStatement(VatStatement vatStatement) throws LimaException { + + String accountNumbersList = null; + + try { + VatStatementTopiaDao vatStatementTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + VatStatement vatStatement2 = vatStatementTopiaDao.findVatStatementByLabel(vatStatement.getLabel()); + + if (vatStatement2 != null) { + accountNumbersList = vatStatement2.getAccounts(); + } + } catch (TopiaException ex) { + throw new LimaException("Can't find accountNumber by vatStatement", ex); + } + return accountNumbersList; + } + + @Override + public VatStatementAmounts vatStatementAmounts(VatStatement vatStatement, + Date selectedBeginDate, + Date selectedEndDate) throws LimaException { + VatStatementAmounts vatStatementAmounts = new VatStatementAmountsImpl(); + + BigDecimal debitTemp = new BigDecimal(0); + BigDecimal creditTemp = new BigDecimal(0); + + try { + + String accountNumbersList = findAccountNumberByVatStatement(vatStatement); + + AccountTopiaDao accountTopiaDao = getDaoHelper().getAccountTopiaDao(); + List<Account> accountsList = accountTopiaDao.stringToListAccounts(accountNumbersList, false); + + for (Account account : accountsList) { + ReportsDatas reportsDatas = reportService. + generateAccountsReports(account, true, + selectedBeginDate, selectedEndDate); + if (reportsDatas.getSoldeDebit()) { + debitTemp = debitTemp.add(reportsDatas.getAmountSolde()); + } else { + creditTemp = creditTemp.add(reportsDatas.getAmountSolde()); + } + } + } catch (TopiaException ex) { + throw new LimaException("Error in vatStatementAmounts", ex); + } + //return debitTemp.subtract(creditTemp).abs(); + vatStatementAmounts.setAmount(debitTemp.subtract(creditTemp).abs()); + return vatStatementAmounts; + + } + + @Override + public VatStatement findVatStatementByLabel(String label) throws LimaException { + + VatStatement vatStatement; + + try { + + VatStatementTopiaDao vatStatementTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + vatStatement = vatStatementTopiaDao.findVatStatementByLabel(label); + + } catch (TopiaException ex) { + throw new LimaException("Can't find vatstatement", ex); + } + return vatStatement; + } + + /** remote methode to get list of financial statement */ + public List<VatStatementAmounts> vatStatementReport(Date beginDate, Date endDate) throws LimaException { + + //create list form tree + VatStatementDatas vatStatementDatas = vatStatementReport(null, beginDate, endDate, + new VatStatementDatasImpl()); + List<VatStatementAmounts> result = vatStatementDatas.getListResult(); + + return result; + } + + /** + * Créé la liste de postes contenant les calculs de comptes + * + * @throws LimaException + */ + public VatStatementDatas vatStatementReport(VatStatement vatStatement, + Date selectedBeginDate, + Date selectedEndDate, + VatStatementDatas result) throws LimaException { + List<VatStatement> vatStatements = + getChildrenVatStatement(vatStatement); + + BigDecimal amount = new BigDecimal(0); + List<VatStatementAmounts> subResult = + new ArrayList<VatStatementAmounts>(); + for (VatStatement subVatStatement : vatStatements) { + VatStatementAmounts vatStatementAmounts = + vatStatementAmounts(subVatStatement, + selectedBeginDate, selectedEndDate); + vatStatementAmounts.setLabel(subVatStatement.getLabel()); + if (!subVatStatement.isHeader()) { + //on calcul + amount = + amount.add(vatStatementAmounts.getAmount()); + subResult.add(vatStatementAmounts); + } else { + VatStatementDatas vatStatementDatas = + vatStatementReport(subVatStatement, + selectedBeginDate, selectedEndDate, result); + amount = amount.add(vatStatementDatas. + getVatStatementAmounts().getAmount()); + + + VatStatementAmounts headerVatStatementAmounts = + vatStatementDatas.getVatStatementAmounts(); + //Si sous-total + if (subVatStatement.isHeader()) { + VatStatementAmounts header = + new VatStatementAmountsImpl(); + header.setLabel(headerVatStatementAmounts.getLabel()); + header.setLevel(headerVatStatementAmounts.getLevel()); + header.setHeader(true); + //ajoute header + subResult.add(header); + //ajoute liste + if (vatStatementDatas.getListResult() != null) { + subResult.addAll(vatStatementDatas.getListResult()); + } + //ajoute une ligne vide + subResult.add(new VatStatementAmountsImpl()); + + } + } + } + VatStatementAmounts vatStatementAmounts = + new VatStatementAmountsImpl(); + vatStatementAmounts.setAmount(amount); + if (vatStatement != null) { + vatStatementAmounts.setLabel(vatStatement.getLabel()); + vatStatementAmounts.setHeader(vatStatement.isHeader()); + vatStatementAmounts.setLevel(vatStatement.getLevel()); + } + result.setVatStatementAmounts(vatStatementAmounts); + result.setListResult(subResult); + + return result; + } + + @Override + public void removeVatStatement(VatStatement vatStatement) throws LimaException { + + try { + VatStatementTopiaDao vatStatementTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + + // remove vatstatement + VatStatement vatStatementToDelete = + vatStatementTopiaDao.findByTopiaId( + vatStatement.getTopiaId()); + vatStatementTopiaDao.delete(vatStatementToDelete); + + //get all subVatStatement + List<VatStatement> vatStatements = + getAllChildrenVatStatement(vatStatement, + new ArrayList<VatStatement>()); + + //if VatStatement have subVatStatement + if (vatStatements.size() > 0) { + for (VatStatement subVatStatement : vatStatements) { + VatStatement subVatStatementToDelete = + vatStatementTopiaDao.findByTopiaId( + subVatStatement.getTopiaId()); + vatStatementTopiaDao.delete(subVatStatementToDelete); + } + } + + } catch (TopiaException ex) { + throw new LimaException("Can't remove vatstatement", ex); + } + } + + @Override + public boolean checkVatStatementExist(String label) throws LimaException { + boolean result; + try { + VatStatementTopiaDao vatStatementTopiaDao = getDaoHelper().getVatStatementTopiaDao(); + result = vatStatementTopiaDao.forProperties(VatStatement.PROPERTY_LABEL, label).exists(); + } catch (TopiaException e) { + throw new LimaException("Can't check VAT statement", e); + } + return result; + } + + @Override + public void removeAllVatStatement() throws LimaException { + for (VatStatement vatStatement : getChildrenVatStatement(null)) { + removeVatStatement(vatStatement); + } + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/migration/DatabaseMigrationClass.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/migration/DatabaseMigrationClass.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/migration/DatabaseMigrationClass.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,82 @@ +/* + * #%L + * Lima :: business + * + * $Id: DatabaseMigrationClass.java 3322 2012-01-17 09:35:25Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2011 CodeLutin, Victor Salaun + * %% + * 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.migration; + +import org.chorem.lima.entity.LimaCallaoTopiaPersistenceContext; +import org.nuiton.topia.migration.TopiaMigrationCallbackByClass; +import org.nuiton.topia.persistence.TopiaPersistenceContext; +import org.nuiton.topia.persistence.support.TopiaSqlSupport; +import org.nuiton.util.Version; + +import java.util.List; + +public class DatabaseMigrationClass extends TopiaMigrationCallbackByClass<LimaCallaoTopiaPersistenceContext> { + + protected static final Version VERSION_0_5 = new Version("0.5"); + protected static final Version VERSION_0_6 = new Version("0.6"); + + public DatabaseMigrationClass() { + super(new MigrationResolver()); + } + + protected static class MigrationResolver implements MigrationCallBackForVersionResolver { + + @Override + public Class<? extends MigrationCallBackForVersion> getCallBack(Version version) { + Class<? extends MigrationCallBackForVersion> result = null; + + if (version.equals(VERSION_0_5)) { + result = MigrationV0V0_5.class; + } else if (version.equals(VERSION_0_6)) { + result = MigrationV0_6.class; + } + return result; + } + + } + + @Override + public Version[] getAvailableVersions() { + Version[] result = new Version[]{VERSION_0_5, VERSION_0_6}; + return result; + } + +// @Override +// public Version getApplicationVersion() { +// // TODO DCossé 15/05/14 do it when i know how to do it +// //Version appVersion = new Version(LimaCallaoDAOHelper.getModelVersion()); +// return new Version(); +// } + + @Override + public boolean askUser(Version dbVersion, List<Version> versions) { + return true; + } + + @Override + protected TopiaSqlSupport getSqlSupport(LimaCallaoTopiaPersistenceContext topiaPersistenceContext) { + return topiaPersistenceContext.getSqlSupport(); + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/migration/MigrationV0V0_5.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/migration/MigrationV0V0_5.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/migration/MigrationV0V0_5.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,47 @@ +/* + * #%L + * Lima :: business + * + * $Id: MigrationV0V0_5.java 3296 2011-09-20 17:49:06Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2011 CodeLutin, Victor Salaun + * %% + * 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.migration; + +import org.nuiton.topia.migration.TopiaMigrationCallbackByClass; +import org.nuiton.topia.migration.TopiaMigrationCallbackByClass.MigrationCallBackForVersion; +import org.nuiton.topia.persistence.TopiaException; +import org.nuiton.topia.persistence.TopiaPersistenceContext; +import org.nuiton.util.Version; +import java.util.List; + +public class MigrationV0V0_5 extends MigrationCallBackForVersion { + + public MigrationV0V0_5(Version version, TopiaMigrationCallbackByClass callBack) { + super(version, callBack); + } + + @Override + protected void prepareMigrationScript(TopiaPersistenceContext tx, + List<String> queries, + boolean showSql, + boolean showProgression) throws TopiaException { + queries.add("Alter table record alter AMOUNT clob;"); + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/migration/MigrationV0_6.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/migration/MigrationV0_6.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/migration/MigrationV0_6.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,84 @@ +/* + * #%L + * Lima :: business + * + * $Id: MigrationV0_6.java 3421 2012-05-15 09:53:13Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2011 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.migration; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.migration.TopiaMigrationCallbackByClass; +import org.nuiton.topia.persistence.TopiaException; +import org.nuiton.topia.persistence.TopiaPersistenceContext; +import org.nuiton.util.Version; + +import java.util.List; + +/** + * Migration code from 0.5 to 0.6. + * + * @author tchemit <chemit@codelutin.com> + * @since 0.6 + */ +public class MigrationV0_6 extends TopiaMigrationCallbackByClass.MigrationCallBackForVersion { + + /** Logger. */ + private static final Log log = LogFactory.getLog(MigrationV0_6.class); + + public MigrationV0_6(Version version, TopiaMigrationCallbackByClass callBack) { + super(version, callBack); + } + + @Override + protected void prepareMigrationScript(TopiaPersistenceContext tx, + List<String> queries, + boolean showSql, + boolean showProgression) throws TopiaException { + + if (log.isInfoEnabled()) { + log.info("Migrates to version 0.6"); + } + + // migration from h2 to 1.3.166 not supporting index on clob + queries.add("Alter table account alter column accountnumber varchar"); + + // add new columns + queries.add("alter table account drop column masteraccount"); + queries.add("alter table account drop column generalledger"); + queries.add("alter table entry add column lettering varchar(30)"); + queries.add("alter table financialtransaction drop column financialperiod"); + + // perform some migration + queries.add("update entry e set lettering = (select l.code from Letter l where l.topiaid = e.letter)"); + + // delete non necessary fields + queries.add("Alter table FINANCIALTRANSACTION drop column AMOUNTDEBIT"); + queries.add("Alter table FINANCIALTRANSACTION drop column AMOUNTCREDIT"); + queries.add("alter table vatstatement drop column amount"); + queries.add("alter table entry drop column letter"); + + // delete tables + queries.add("drop table record"); + queries.add("drop table letter"); + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/AccountComparator.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/AccountComparator.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/AccountComparator.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,43 @@ +/* + * #%L + * Lima business + * + * $Id: AccountComparator.java 3290 2011-09-17 12:55:34Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2010 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.utils; + +import org.chorem.lima.entity.Account; + +import java.io.Serializable; +import java.util.Comparator; + +public class AccountComparator implements Serializable, Comparator<Account> { + + private static final long serialVersionUID = 1L; + + /** sort by accout number in lexicographical order */ + @Override + public int compare(Account o1, Account o2) { + return o1.getAccountNumber().compareTo(o2.getAccountNumber()); + } + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/AccountEBPComparator.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/AccountEBPComparator.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/AccountEBPComparator.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,42 @@ +/* + * #%L + * Lima business + * + * $Id: AccountEBPComparator.java 3290 2011-09-17 12:55:34Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2010 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.utils; + +import org.chorem.lima.beans.AccountEBP; + +import java.io.Serializable; +import java.util.Comparator; + +public class AccountEBPComparator implements Serializable, Comparator<AccountEBP> { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(AccountEBP o1, AccountEBP o2) { + return o1.getNumero().compareTo(o2.getNumero()); + } + +} Added: 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 (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/DocumentsEnum.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,70 @@ +/* + * #%L + * Lima business + * + * $Id: DocumentsEnum.java 3777 2014-04-14 07:29:08Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2010 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.utils; + +import static org.nuiton.i18n.I18n.t; + + +public enum DocumentsEnum { + + GENERAL_ENTRYBOOK(t("lima-business.document.generalentrybook"), "lima_general_entybook"), + ENTRYBOOKS(t("lima-business.document.entrybook"), "lima_entrybooks"), + BALANCE(t("lima-business.document.balance"), "lima_balance"), + LEDGER(t("lima-business.document.ledger"), "lima_ledger"), + FINANCIALSTATEMENT(t("lima-business.document.financialstatement"), "lima_financialstatements"), + VAT(t("lima-business.document.vat"), "lima_vat"), + ACCOUNT(t("lima-business.document.account"), "lima_account"); + + private final String fileName; + + private final String description; + + private DocumentsEnum(String description, String fileName) { + this.description = description; + this.fileName = fileName; + } + + public String getFileName() { + return fileName; + } + + public String getDescription() { + return description; + } + + public static DocumentsEnum valueOfLink(String label) { + DocumentsEnum value = null; + + for (DocumentsEnum documentsEnum : DocumentsEnum.values()) { + if (label.equals(documentsEnum.fileName)) { + value = documentsEnum; + break; + } + } + return value; + } + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/EntryComparator.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/EntryComparator.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/EntryComparator.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,49 @@ +/* + * #%L + * Lima business + * + * $Id: EntryComparator.java 3721 2013-12-31 15:03:48Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.utils; + +import org.chorem.lima.entity.Entry; + +import java.io.Serializable; +import java.util.Comparator; + +public class EntryComparator implements Serializable, Comparator<Entry> { + + private static final long serialVersionUID = 1L; + + @Override + public int compare(Entry o1, Entry o2) { + int result = o1.getFinancialTransaction().getTransactionDate().compareTo(o2.getFinancialTransaction().getTransactionDate()); + if (result == 0) { + result = o1.getFinancialTransaction().getTopiaCreateDate().compareTo(o2.getFinancialTransaction().getTopiaCreateDate()); + } + if (result == 0) { + result = o1.getTopiaCreateDate().compareTo(o2.getTopiaCreateDate()); + } + return result; + } + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/EntryEBPComparator.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/EntryEBPComparator.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/EntryEBPComparator.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,64 @@ +/* + * #%L + * Lima business + * + * $Id: EntryEBPComparator.java 3290 2011-09-17 12:55:34Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2010 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.utils; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.beans.EntryEBP; + +import java.io.Serializable; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Comparator; +import java.util.Date; + +public class EntryEBPComparator implements Serializable, Comparator<EntryEBP> { + + private static final Log log = + LogFactory.getLog(EntryEBPComparator.class); + + private static final long serialVersionUID = 1L; + + @Override + public int compare(EntryEBP o1, EntryEBP o2) { + int result = 0; + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); + try { + Date date1 = sdf.parse(o1.getDatEcr()); + Date date2 = sdf.parse(o2.getDatEcr()); + result = date1.compareTo(date2); + if (result == 0) { + result = o1.getJournal().compareTo(o2.getJournal()); + } + } catch (ParseException eee) { + log.error("Can't parse date", eee); + } + + + return result; + } + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FinancialPeriodComparator.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FinancialPeriodComparator.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FinancialPeriodComparator.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,53 @@ +/* + * #%L + * Lima :: business + * + * $Id: FinancialPeriodComparator.java 3442 2012-06-05 14:51:55Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2011 CodeLutin, Victor Salaun + * %% + * 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.utils; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.entity.ClosedPeriodicEntryBook; + +import java.io.Serializable; +import java.util.Comparator; + +public class FinancialPeriodComparator implements Serializable, Comparator<ClosedPeriodicEntryBook> { + + private static final long serialVersionUID = 1L; + + private static final Log log = LogFactory.getLog(FinancialPeriodComparator.class); + + @Override + public int compare(ClosedPeriodicEntryBook o1, ClosedPeriodicEntryBook o2) { + if (o1.getFinancialPeriod().getBeginDate().compareTo(o2.getFinancialPeriod().getBeginDate()) == 0) { + if (o1.getEntryBook().getCode().compareToIgnoreCase(o2.getEntryBook().getCode()) == 0) { + return o1.getTopiaCreateDate().compareTo(o2.getTopiaCreateDate()); + } else { + return o1.getEntryBook().getCode().compareToIgnoreCase(o2.getEntryBook().getCode()); + } + } else { + return o1.getFinancialPeriod().getBeginDate().compareTo(o2.getFinancialPeriod().getBeginDate()); + } + } + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FinancialTransactionComparator.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FinancialTransactionComparator.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FinancialTransactionComparator.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,44 @@ +package org.chorem.lima.business.utils; + +/* + * #%L + * Lima :: business + * $Id: FinancialTransactionComparator.java 3695 2013-07-10 09:11:39Z athimel $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2013 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% + */ + +import org.chorem.lima.entity.FinancialTransaction; + +import java.util.Comparator; + +/** + * @author Sylvain Bavencoff <bavencoff@codelutin.com> + */ +public class FinancialTransactionComparator implements Comparator<FinancialTransaction> { + + @Override + public int compare(FinancialTransaction o1, FinancialTransaction o2) { + int result = o1.getTransactionDate().compareTo(o2.getTransactionDate()); + if (result == 0) { + result = o1.getTopiaCreateDate().compareTo(o2.getTopiaCreateDate()); + } + return result; + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FiscalPeriodComparator.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FiscalPeriodComparator.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/FiscalPeriodComparator.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,43 @@ +/* + * #%L + * Lima business + * + * $Id: FiscalPeriodComparator.java 3290 2011-09-17 12:55:34Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2010 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.utils; + +import org.chorem.lima.entity.FiscalPeriod; + +import java.io.Serializable; +import java.util.Comparator; + +public class FiscalPeriodComparator implements Serializable, Comparator<FiscalPeriod> { + + private static final long serialVersionUID = 1L; + + /** sort by fiscal begin date */ + @Override + public int compare(FiscalPeriod o1, FiscalPeriod o2) { + return o1.getBeginDate().compareTo(o2.getBeginDate()); + } + +} Added: trunk/lima-business/src/main/java/org/chorem/lima/business/utils/LetteringComparator.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/utils/LetteringComparator.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/utils/LetteringComparator.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,50 @@ +package org.chorem.lima.business.utils; +/* + * #%L + * Lima :: business + * $Id: LetteringComparator.java 3740 2014-01-17 22:12:04Z dcosse $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2012 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% + */ + +import java.io.Serializable; +import java.util.Comparator; + +public class LetteringComparator implements Serializable , Comparator<String> { + private static final long serialVersionUID = 1L; + + @Override + public int compare(String firstString, String secondString) { + + int lengthFirstString = firstString.length(); + int lengthSecondString = secondString.length(); + + int result; + + if (lengthFirstString < lengthSecondString) { + result = -1; + } else if (lengthFirstString > lengthSecondString) { + result = 1; + } else { + result = firstString.compareTo(secondString); + } + + return result; + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/service/LimaServiceFactory.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/service/LimaServiceFactory.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/service/LimaServiceFactory.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,184 @@ +/* + * #%L + * Lima business + * + * $Id: LimaServiceFactory.java 3797 2014-05-14 11:51:21Z echatellier $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/main/java/org/chorem/lima... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.service; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.ServiceListener; +import org.chorem.lima.business.ServiceMonitorable; +import org.nuiton.config.ApplicationConfig; + +import javax.ejb.embeddable.EJBContainer; +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. */ +public class LimaServiceFactory { + + /** Log. */ + private static Log log = LogFactory.getLog(LimaServiceFactory.class); + + /** Single instance. */ + private static LimaServiceFactory instance; + + /** Service cache. */ + protected Map<Class, Object> services = new HashMap<Class, Object>(); + + /** EJB container. */ + protected static EJBContainer container; + + /** EJB service namespace. */ + protected static final String NAMESPACE = "java:global/lima/"; + + /** + * Init openejb container. + * + * @param config configuration + */ + public static void initFactory(ApplicationConfig config) { + + // make a copy of options + Properties props = new Properties(); + + // warning, make a clean properties, openejb put all those properties in jvm wide scope + // introducing strange behaviour in AppConfig loading + // only copy necessary options + props.putAll(config.getOptionStartsWith("java.naming")); + + // transmission des options de logging a openejb + // sinon, il utilise son propre pattern interne + InputStream log4jFile = null; + try { + log4jFile = LimaServiceFactory.class.getResourceAsStream("/log4j.properties"); + Properties propsLog4j = new Properties(); + propsLog4j.load(log4jFile); + props.putAll(propsLog4j); + } catch (IOException ex) { + if (log.isErrorEnabled()) { + log.error("Can't find log4j properties file", ex); + } + } finally { + IOUtils.closeQuietly(log4jFile); + } + + // as of openejb 4.6, bean-finder-shaded 3.15 doesn't scan full classpath anymore by default + // see http://list.chorem.org/pipermail/lima-devel/2014-May/000154.html for more details + System.setProperty("xbean.finder.use.get-resources", "true"); + + // see http://openejb.apache.org/embedded-configuration.html + // http://openejb.apache.org/properties-listing.html + // for embedded configuration + container = EJBContainer.createEJBContainer(props); + } + + public static <M> M getService(Class<M> serviceMonitorableClass) { + LimaServiceFactory factory = getInstance(); + Map<Class, Object> services = factory.getServices(); + M result = (M) services.get(serviceMonitorableClass); + if (result == null) { + result = factory.newService(serviceMonitorableClass); + services.put(serviceMonitorableClass, result); + } + return result; + } + + public static <M> void addServiceListener(Class<M> serviceClass, ServiceListener listener) { + M service = getService(serviceClass); + addServiceListener(service, listener); + } + + public static <M> void addServiceListener(M service, ServiceListener listener) { + if (!(service instanceof ServiceMonitorable)) { + throw new IllegalArgumentException( + "service " + service + " does not implement " + ServiceMonitorable.class); + } + ((ServiceMonitorable) service).addServiceListener(listener); + } + + + public static <M> void removeServiceListener(Class<M> serviceClass, ServiceListener listener) { + ServiceMonitorable service = (ServiceMonitorable) getService(serviceClass); + service.removeServiceListener(listener); + } + + /** + * Close openejb container. + */ + public static void destroy() { + if (container != null) { + container.close(); + } + } + + /** + * Return service factory singleton instance. + * <p/> + * Init it at first call. + * + * @return singleton instance + */ + protected static LimaServiceFactory getInstance() { + if (instance == null) { + instance = new LimaServiceFactory(); + } + return instance; + } + + protected Map<Class, Object> getServices() { + return services; + } + + protected <M> M newService(Class<M> serviceMonitorableClass) { + Object ejbHome; + String serviceName = serviceMonitorableClass.getSimpleName().replace("Monitorable", "Impl"); + // only usefull during non monitorable transition + if (!serviceName.endsWith("Impl")) { + serviceName += "Impl"; + } + try { + ejbHome = container.getContext().lookup(NAMESPACE + serviceName); + } catch (NamingException eee) { + throw new RuntimeException( + "Can't lookup for service : " + serviceName, eee); + + } + InvocationHandler handler = new ServiceMonitorableHandler(ejbHome); + ClassLoader classLoader = serviceMonitorableClass.getClassLoader(); + M result = (M) Proxy.newProxyInstance( + classLoader, + new Class[]{ServiceMonitorable.class, serviceMonitorableClass}, + handler + ); + return result; + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/service/ServiceMonitorableHandler.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/service/ServiceMonitorableHandler.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/service/ServiceMonitorableHandler.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,104 @@ +/* + * #%L + * Lima Swing + * + * $Id: ServiceMonitorableHandler.java 3322 2012-01-17 09:35:25Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.service; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.ServiceListener; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +/** + * This class surround a real service, but intercept addServiceListener + * and removeServiceListener that are not defined on delegated service + * object. + * + * All other call are forwarded on notified to registered listeners. + * + * @author chatellier + * @version $Revision: 3322 $ + * + * Last update : $Date: 2012-01-17 10:35:25 +0100 (mar. 17 janv. 2012) $ + * By : $Author: echatellier $ + */ +public class ServiceMonitorableHandler implements InvocationHandler { + + private static final Log log = + LogFactory.getLog(ServiceMonitorableHandler.class); + + /** The proxied service. */ + private Object service; + + /** Listeners on the service. */ + private List<ServiceListener> listeners; + + public ServiceMonitorableHandler(Object service) { + this.service = service; + listeners = new ArrayList<ServiceListener>(); + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Object result = null; + if (method.getName().equals("addServiceListener")) { + addServiceListener((ServiceListener) args[0]); + } else if (method.getName().equals("removeServiceListener")) { + removeServiceListener((ServiceListener) args[0]); + } else { + try { + result = method.invoke(service, args); + } catch (InvocationTargetException eee) { + throw eee.getCause(); + } + notifyMethod(method); + } + return result; + } + + protected void addServiceListener(ServiceListener serviceListener) { + listeners.add(serviceListener); + } + + protected void removeServiceListener(ServiceListener serviceListener) { + listeners.remove(serviceListener); + } + + protected void notifyMethod(Method method) { + String methodName = method.getName(); + + // get is removed to only notify write modification + if (!methodName.startsWith("get")) { + for (ServiceListener serviceListener : listeners) { + serviceListener.notifyMethod(service.toString(), methodName); + log.debug("proxy : " + service.toString() + " " + methodName); + } + } + } +} Added: trunk/lima-business/src/main/java/org/chorem/lima/service/package-info.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/service/package-info.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/service/package-info.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,30 @@ +/* + * #%L + * Lima Business + * + * $Id: package-info.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/main/java/org/chorem/... $ + * %% + * Copyright (C) 2012 CodeLutin, Chatellier Eric + * %% + * 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% + */ +/** + * This package defined factory to access for service definied on OpenEJB. + * + * This is a client side package but can be usefull for unit test too. + */ +package org.chorem.lima.service; Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/AbstractLimaTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/AbstractLimaTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/AbstractLimaTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,324 +0,0 @@ -/* - * #%L - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2011 - 2012 Codelutin, Chatellier Eric - * %% - * 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; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.text.DateFormat; -import java.text.ParseException; -import java.util.Locale; -import java.util.Properties; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.business.LimaConfig.Option; -import org.chorem.lima.business.accountingrules.TestAccountingRules; -import org.chorem.lima.business.api.AccountService; -import org.chorem.lima.business.api.EntryBookService; -import org.chorem.lima.business.api.FinancialPeriodService; -import org.chorem.lima.business.api.FinancialTransactionService; -import org.chorem.lima.business.api.FiscalPeriodService; -import org.chorem.lima.business.api.ImportService; -import org.chorem.lima.business.api.ReportService; -import org.chorem.lima.business.ejb.ClearService; -import org.chorem.lima.entity.Account; -import org.chorem.lima.entity.AccountImpl; -import org.chorem.lima.entity.Entry; -import org.chorem.lima.entity.EntryBook; -import org.chorem.lima.entity.EntryBookImpl; -import org.chorem.lima.entity.EntryImpl; -import org.chorem.lima.entity.FinancialTransaction; -import org.chorem.lima.entity.FinancialTransactionImpl; -import org.chorem.lima.entity.FiscalPeriod; -import org.chorem.lima.entity.FiscalPeriodImpl; -import org.chorem.lima.entity.LimaCallaoDAOHelper; -import org.chorem.lima.service.LimaServiceFactory; -import org.junit.After; -import org.junit.BeforeClass; -import org.nuiton.i18n.I18n; -import org.nuiton.i18n.init.ClassPathI18nInitializer; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaNotFoundException; -import org.nuiton.topia.TopiaRuntimeException; - -/** - * Common initialization code for all lima tests. - * - * @author chatellier - * @version $Revision$ - * <p/> - * Last update : $Date$ - * By : $Author$ - */ -public abstract class AbstractLimaTest { - - private static final Log log = LogFactory.getLog(AbstractLimaTest.class); - - protected static DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.ENGLISH); - - protected static ClearService clearService; - protected static AccountService accountService; - protected static EntryBookService entryBookService; - protected static FinancialPeriodService financialPeriodService; - protected static FinancialTransactionService financialTransactionService; - protected static FiscalPeriodService fiscalPeriodService; - protected static ReportService reportService; - protected static ImportService importService; - - /** - * This is a before class method, but junit will fail to run inherited - * BeforeClass methods if there is one. - * - * @throws Exception - */ - @BeforeClass - public static void initAbstractTest() throws Exception { - setUpLocale(); - setUpTestConfig(); - setUpDefaultRule(); - initServices(); - } - - protected static void setUpLocale() throws Exception { - I18n.init(new ClassPathI18nInitializer(), Locale.UK); - } - - /** - * Init services after i18n#init(). - * @throws IOException - */ - protected static void initServices() throws IOException { - clearService = LimaServiceFactory.getService(ClearService.class); - accountService = LimaServiceFactory.getService(AccountService.class); - entryBookService = LimaServiceFactory.getService(EntryBookService.class); - financialPeriodService = LimaServiceFactory.getService(FinancialPeriodService.class); - financialTransactionService = LimaServiceFactory.getService(FinancialTransactionService.class); - fiscalPeriodService = LimaServiceFactory.getService(FiscalPeriodService.class); - reportService = LimaServiceFactory.getService(ReportService.class); - importService = LimaServiceFactory.getService(ImportService.class); - } - - /** - * Return a new instance of configuration defined on a new database at - * each call. - * - * @return single test config - */ - protected static LimaConfig getTestConfiguration() { - LimaConfig instance = new LimaConfig(); - - // do not call parse() method (don't read /etc...) - // load file manually (lima.properties) - Properties testProperties = new Properties(); - InputStream streamMain = null; - InputStream streamTest = null; - - try { - streamMain = AbstractLimaTest.class.getResourceAsStream("/" + Option.CONFIG_FILE.getDefaultValue()); - testProperties.load(streamMain); - streamMain.close(); - - streamTest = AbstractLimaTest.class.getResourceAsStream("/lima-test.properties"); - testProperties.load(streamTest); - streamTest.close(); - } catch (IOException ex) { - throw new RuntimeException("Can't init test configuration", ex); - } finally { - IOUtils.closeQuietly(streamMain); - IOUtils.closeQuietly(streamTest); - } - - // override somes - String testDir = System.getProperty("java.io.tmpdir") + File.separator + "limaopenejbdb"; - testProperties.setProperty(Option.DATA_DIR.getKey(), testDir); - testProperties.setProperty("hibernate.connection.url", "jdbc:h2:file:" + testDir + File.separator + "data"); - //testProperties.setProperty("hibernate.hbm2ddl.auto", "update"); - - instance.setOptions(testProperties); - instance.setOption("topia.persistence.classes", LimaCallaoDAOHelper.getImplementationClassesAsString()); - - if (log.isDebugEnabled()) { - log.debug("Using test configuration" + instance.getFlatOptions()); - } - return instance; - } - - protected static void setUpTestConfig() throws Exception { - LimaConfig.instance = getTestConfiguration(); - LimaServiceFactory.initFactory(LimaConfig.getInstance()); - } - - @After - public void cleanDatabase() throws IOException { - LimaConfig config = LimaConfig.getInstance(); - FileUtils.deleteDirectory(config.getDataDir()); - } - - /** - * Default rule configuration should stay in France rule. - * - * But test will run without a specific rule during normal tests - * and france rule will be re-enabled for specifics tests. - * @throws Exception - */ - protected static void setUpDefaultRule() throws Exception { - LimaConfig config = LimaConfig.getInstance(); - config.setAccountingRule(TestAccountingRules.class.getName()); - } - - /** - * Create a basic database with some objects to reuse then in subtests. - * - * Not called by default (<code>@Before</code>) to allow init test with - * CSV or EBP import. - * - * @throws LimaException - * @throws ParseException - */ - protected void initTestDatabase() throws LimaException, ParseException { - - // clear database - clearService.clearDatabase(); - - initTestAccounts(); - initTestTransactions(); - } - - /** - * Create a basic account plan. - * - * @throws LimaException - * @throws ParseException - */ - protected void initTestAccounts() throws LimaException, ParseException { - - // creation d'un plan compatble de test - Account classFinancier = new AccountImpl(); - classFinancier.setAccountNumber("5"); - classFinancier.setLabel("Comptes financiers"); - accountService.createAccount(classFinancier); - - Account accountVmp = new AccountImpl(); - accountVmp.setAccountNumber("50"); - accountVmp.setLabel("Valeurs mobilières de placement"); - accountService.createAccount(accountVmp); - - Account accountPel = new AccountImpl(); - accountPel.setAccountNumber("501"); - accountPel.setLabel("Parts dans des entreprises liées"); - accountService.createAccount(accountPel); - - Account accountAP = new AccountImpl(); - accountAP.setAccountNumber("502"); - accountAP.setLabel("Actions propres"); - accountService.createAccount(accountAP); - - Account accountBefa = new AccountImpl(); - accountBefa.setAccountNumber("51"); - accountBefa.setLabel("Banques établissements financiers et assimilés"); - accountService.createAccount(accountBefa); - - Account accountVmpVae = new AccountImpl(); - accountVmpVae.setAccountNumber("511"); - accountVmpVae.setLabel("Valeurs à l'encaissement"); - accountService.createAccount(accountVmpVae); - - Account accountBanques = new AccountImpl(); - accountBanques.setAccountNumber("512"); - accountBanques.setLabel("Banques"); - accountService.createAccount(accountBanques); - - // creation d'un journal - EntryBook journalDesVentes = new EntryBookImpl(); - journalDesVentes.setLabel("Journal des ventes"); - journalDesVentes.setCode("jdv"); - entryBookService.createEntryBook(journalDesVentes); - - // creation d'un exercice fiscal - FiscalPeriod fiscalPeriod = new FiscalPeriodImpl(); - fiscalPeriod.setBeginDate(df.parse("January 1, 2012")); - fiscalPeriod.setEndDate(df.parse("December 31, 2012")); - fiscalPeriodService.createFiscalPeriod(fiscalPeriod); - } - - /** - * Create some transaction in previous accounts. - * - * @throws LimaException - * @throws ParseException - */ - protected void initTestTransactions() throws LimaException, ParseException { - // add some transactions - // FIXME echatellier 20120221 fix test, following instance already in current method - EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); - Account accountVmpVae = accountService.getAccountByNumber("511"); - - FinancialTransaction transaction1 = new FinancialTransactionImpl(); - transaction1.setTransactionDate(df.parse("April 4, 2012")); - transaction1.setEntryBook(journalDesVentes); - transaction1 = financialTransactionService.createFinancialTransaction(transaction1); - - Entry tr1Entry1 = new EntryImpl(); - tr1Entry1.setAmount(BigDecimal.valueOf(42.0)); - tr1Entry1.setAccount(accountVmpVae); - tr1Entry1.setFinancialTransaction(transaction1); - tr1Entry1.setDescription("test desc"); - tr1Entry1.setVoucher("voucher"); - tr1Entry1 = financialTransactionService.createEntry(tr1Entry1); - - Entry tr1Entry2 = new EntryImpl(); - tr1Entry2.setAmount(BigDecimal.valueOf(42.0)); - tr1Entry2.setDebit(true); - tr1Entry2.setAccount(accountVmpVae); - tr1Entry2.setFinancialTransaction(transaction1); - tr1Entry2.setDescription("test desc"); - tr1Entry2.setVoucher("voucher"); - tr1Entry2 = financialTransactionService.createEntry(tr1Entry2); - } - - /** - * Method to use only for class that need a context to be tester. - * Only for DOA for now. - * - * @return a topia context - */ - protected static TopiaContext getTestContext() { - try { - LimaConfig config = LimaConfig.getInstance(); - Properties options = config.getFlatOptions(); - - if (log.isDebugEnabled()) { - log.debug("Opening context to database : " + options.getProperty("hibernate.connection.url")); - } - return TopiaContextFactory.getContext(options); - } catch (TopiaNotFoundException ex) { - throw new TopiaRuntimeException("Could not acquire root context", ex); - } - } -} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/AbstractLimaTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/AbstractLimaTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/AbstractLimaTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,324 @@ +/* + * #%L + * $Id: AbstractLimaTest.java 3408 2012-05-09 15:37:59Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2011 - 2012 Codelutin, Chatellier Eric + * %% + * 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; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Locale; +import java.util.Properties; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaConfig.Option; +import org.chorem.lima.business.accountingrules.TestAccountingRules; +import org.chorem.lima.business.api.AccountService; +import org.chorem.lima.business.api.EntryBookService; +import org.chorem.lima.business.api.FinancialPeriodService; +import org.chorem.lima.business.api.FinancialTransactionService; +import org.chorem.lima.business.api.FiscalPeriodService; +import org.chorem.lima.business.api.ImportService; +import org.chorem.lima.business.api.ReportService; +import org.chorem.lima.business.ejb.ClearService; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountImpl; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryBookImpl; +import org.chorem.lima.entity.EntryImpl; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionImpl; +import org.chorem.lima.entity.FiscalPeriod; +import org.chorem.lima.entity.FiscalPeriodImpl; +import org.chorem.lima.entity.LimaCallaoDAOHelper; +import org.chorem.lima.service.LimaServiceFactory; +import org.junit.After; +import org.junit.BeforeClass; +import org.nuiton.i18n.I18n; +import org.nuiton.i18n.init.ClassPathI18nInitializer; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.persistence.TopiaConfigurationConstants; +import org.nuiton.topia.persistence.TopiaNotFoundException; +import org.nuiton.topia.TopiaRuntimeException; + +/** + * Common initialization code for all lima tests. + * + * @author chatellier + * @version $Revision: 3408 $ + * <p/> + * Last update : $Date: 2012-05-09 17:37:59 +0200 (mer. 09 mai 2012) $ + * By : $Author: echatellier $ + */ +public abstract class AbstractLimaTest { + + private static final Log log = LogFactory.getLog(AbstractLimaTest.class); + + protected static DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.ENGLISH); + + protected static ClearService clearService; + protected static AccountService accountService; + protected static EntryBookService entryBookService; + protected static FinancialPeriodService financialPeriodService; + protected static FinancialTransactionService financialTransactionService; + protected static FiscalPeriodService fiscalPeriodService; + protected static ReportService reportService; + protected static ImportService importService; + + /** + * This is a before class method, but junit will fail to run inherited + * BeforeClass methods if there is one. + * + * @throws Exception + */ + @BeforeClass + public static void initAbstractTest() throws Exception { + setUpLocale(); + setUpTestConfig(); + setUpDefaultRule(); + initServices(); + } + + protected static void setUpLocale() throws Exception { + I18n.init(new ClassPathI18nInitializer(), Locale.UK); + } + + /** + * Init services after i18n#init(). + * @throws IOException + */ + protected static void initServices() throws IOException { + clearService = LimaServiceFactory.getService(ClearService.class); + accountService = LimaServiceFactory.getService(AccountService.class); + entryBookService = LimaServiceFactory.getService(EntryBookService.class); + financialPeriodService = LimaServiceFactory.getService(FinancialPeriodService.class); + financialTransactionService = LimaServiceFactory.getService(FinancialTransactionService.class); + fiscalPeriodService = LimaServiceFactory.getService(FiscalPeriodService.class); + reportService = LimaServiceFactory.getService(ReportService.class); + importService = LimaServiceFactory.getService(ImportService.class); + } + + /** + * Return a new instance of configuration defined on a new database at + * each call. + * + * @return single test config + */ + protected static LimaConfig getTestConfiguration() { + LimaConfig instance = new LimaConfig(); + + // do not call parse() method (don't read /etc...) + // load file manually (lima.properties) + Properties testProperties = new Properties(); + InputStream streamMain = null; + InputStream streamTest = null; + + try { + streamMain = AbstractLimaTest.class.getResourceAsStream("/" + Option.CONFIG_FILE.getDefaultValue()); + testProperties.load(streamMain); + streamMain.close(); + + streamTest = AbstractLimaTest.class.getResourceAsStream("/lima-test.properties"); + testProperties.load(streamTest); + streamTest.close(); + } catch (IOException ex) {org.nuiton.topia.persistence.TopiaNotFoundException + throw new RuntimeException("Can't init test configuration", ex); + } finally { + IOUtils.closeQuietly(streamMain); + IOUtils.closeQuietly(streamTest); + } + + // override somes + String testDir = System.getProperty("java.io.tmpdir") + File.separator + "limaopenejbdb"; + testProperties.setProperty(Option.DATA_DIR.getKey(), testDir); + testProperties.setProperty("hibernate.connection.url", "jdbc:h2:file:" + testDir + File.separator + "data"); + //testProperties.setProperty("hibernate.hbm2ddl.auto", "update"); + + instance.setOptions(testProperties); + instance.setOption("topia.persistence.classes", LimaCallaoDAOHelper.getImplementationClassesAsString()); + + if (log.isDebugEnabled()) { + log.debug("Using test configuration" + instance.getFlatOptions()); + } + return instance; + } + + protected static void setUpTestConfig() throws Exception { + LimaConfig.instance = getTestConfiguration(); + LimaServiceFactory.initFactory(LimaConfig.getInstance()); + } + + @After + public void cleanDatabase() throws IOException { + LimaConfig config = LimaConfig.getInstance(); + FileUtils.deleteDirectory(config.getDataDir()); + } + + /** + * Default rule configuration should stay in France rule. + * + * But test will run without a specific rule during normal tests + * and france rule will be re-enabled for specifics tests. + * @throws Exception + */ + protected static void setUpDefaultRule() throws Exception { + LimaConfig config = LimaConfig.getInstance(); + config.setAccountingRule(TestAccountingRules.class.getName()); + } + + /** + * Create a basic database with some objects to reuse then in subtests. + * + * Not called by default (<code>@Before</code>) to allow init test with + * CSV or EBP import. + * + * @throws LimaException + * @throws ParseException + */ + protected void initTestDatabase() throws LimaException, ParseException { + + // clear database + clearService.clearDatabase(); + + initTestAccounts(); + initTestTransactions(); + } + + /** + * Create a basic account plan. + * + * @throws LimaException + * @throws ParseException + */ + protected void initTestAccounts() throws LimaException, ParseException { + + // creation d'un plan compatble de test + Account classFinancier = new AccountImpl(); + classFinancier.setAccountNumber("5"); + classFinancier.setLabel("Comptes financiers"); + accountService.createAccount(classFinancier); + + Account accountVmp = new AccountImpl(); + accountVmp.setAccountNumber("50"); + accountVmp.setLabel("Valeurs mobilières de placement"); + accountService.createAccount(accountVmp); + + Account accountPel = new AccountImpl(); + accountPel.setAccountNumber("501"); + accountPel.setLabel("Parts dans des entreprises liées"); + accountService.createAccount(accountPel); + + Account accountAP = new AccountImpl(); + accountAP.setAccountNumber("502"); + accountAP.setLabel("Actions propres"); + accountService.createAccount(accountAP); + + Account accountBefa = new AccountImpl(); + accountBefa.setAccountNumber("51"); + accountBefa.setLabel("Banques établissements financiers et assimilés"); + accountService.createAccount(accountBefa); + + Account accountVmpVae = new AccountImpl(); + accountVmpVae.setAccountNumber("511"); + accountVmpVae.setLabel("Valeurs à l'encaissement"); + accountService.createAccount(accountVmpVae); + + Account accountBanques = new AccountImpl(); + accountBanques.setAccountNumber("512"); + accountBanques.setLabel("Banques"); + accountService.createAccount(accountBanques); + + // creation d'un journal + EntryBook journalDesVentes = new EntryBookImpl(); + journalDesVentes.setLabel("Journal des ventes"); + journalDesVentes.setCode("jdv"); + entryBookService.createEntryBook(journalDesVentes); + + // creation d'un exercice fiscal + FiscalPeriod fiscalPeriod = new FiscalPeriodImpl(); + fiscalPeriod.setBeginDate(df.parse("January 1, 2012")); + fiscalPeriod.setEndDate(df.parse("December 31, 2012")); + fiscalPeriodService.createFiscalPeriod(fiscalPeriod); + } + + /** + * Create some transaction in previous accounts. + * + * @throws LimaException + * @throws ParseException + */ + protected void initTestTransactions() throws LimaException, ParseException { + // add some transactions + // FIXME echatellier 20120221 fix test, following instance already in current method + EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); + Account accountVmpVae = accountService.getAccountByNumber("511"); + + FinancialTransaction transaction1 = new FinancialTransactionImpl(); + transaction1.setTransactionDate(df.parse("April 4, 2012")); + transaction1.setEntryBook(journalDesVentes); + transaction1 = financialTransactionService.createFinancialTransaction(transaction1); + + Entry tr1Entry1 = new EntryImpl(); + tr1Entry1.setAmount(BigDecimal.valueOf(42.0)); + tr1Entry1.setAccount(accountVmpVae); + tr1Entry1.setFinancialTransaction(transaction1); + tr1Entry1.setDescription("test desc"); + tr1Entry1.setVoucher("voucher"); + tr1Entry1 = financialTransactionService.createEntry(tr1Entry1); + + Entry tr1Entry2 = new EntryImpl(); + tr1Entry2.setAmount(BigDecimal.valueOf(42.0)); + tr1Entry2.setDebit(true); + tr1Entry2.setAccount(accountVmpVae); + tr1Entry2.setFinancialTransaction(transaction1); + tr1Entry2.setDescription("test desc"); + tr1Entry2.setVoucher("voucher"); + tr1Entry2 = financialTransactionService.createEntry(tr1Entry2); + } + + /** + * Method to use only for class that need a context to be tester. + * Only for DOA for now. + * + * @return a topia context + */ + protected static TopiaContext getTestContext() { + try { + LimaConfig config = LimaConfig.getInstance(); + Properties options = config.getFlatOptions(); + + if (log.isDebugEnabled()) { + log.debug("Opening context to database : " + options.getProperty("hibernate.connection.url")); + } + return TopiaContextFactory.getContext(options); + } catch (TopiaNotFoundException ex) { + throw new TopiaRuntimeException("Could not acquire root context", ex); + } + } +} Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,223 +0,0 @@ -/* - * #%L - * Lima business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric - * %% - * 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; - -import org.chorem.lima.entity.Account; -import org.chorem.lima.entity.AccountImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -/** - * Tests pour la gestion des comptes dans le plan comptable. - * - * Vérification sur l'ajout, la modification et suppression d'un compte. - * Il existe également des tests sur des actions à partir de DTO. La classe - * AccountServiceImplTest possède une méthode upload qui, à partir d'un DTO, - * va mettre à jour automatiquement dans la base de données. - * - * @author Rémi Chapelet - */ -public class AccountServiceImplTest extends AbstractLimaTest { - - @Before - public void initTest() throws Exception { - initTestDatabase(); - } - - /** - * Création d'un compte dans le plan comptable. - * @throws LimaException - */ - @Test - public void createAccountTest() throws LimaException { - Account myAccount = new AccountImpl(); - myAccount.setAccountNumber("2"); - myAccount.setLabel("Comptes d'immobilisations"); - accountService.createAccount(myAccount); - } - - /** - * Création d'un compte dans le plan comptable (echec duplication). - * - * @throws LimaException - */ - @Test(expected = LimaException.class) - public void createAccountEchecTest() throws LimaException { - Account myAccount = new AccountImpl(); - myAccount.setAccountNumber("5"); - myAccount.setLabel("Comptes de capitaux"); - accountService.createAccount(myAccount); - } - - /** - * Création d'un compte dans le plan comptable. - * - * Le test ne doit pas echoué avec les regles par defaut, mais peut echouer - * suivant certaines autres regles. - * - * @throws LimaException - */ - @Test - public void testCreateAccountWrongNumber() throws LimaException { - Account myAccount = new AccountImpl(); - myAccount.setAccountNumber("42"); // erreur de compte (4) - myAccount.setLabel("Comptes de tiers"); - accountService.createAccount(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 createAccountWithChildTest() throws LimaException { - // Création des comptes - Account classCharges = new AccountImpl(); - classCharges.setAccountNumber("6"); - classCharges.setLabel("Comptes de charges"); - accountService.createAccount(classCharges); - - Account accountAchat = new AccountImpl(); - accountAchat.setAccountNumber("60"); - accountAchat.setLabel("Achats (sauf 603)"); - accountService.createAccount(accountAchat); - - Account accountSe = new AccountImpl(); - accountSe.setAccountNumber("61"); - accountSe.setLabel("Services extérieurs"); - accountService.createAccount(accountSe); - - Account accountVs = new AccountImpl(); - accountVs.setAccountNumber("603"); - accountVs.setLabel("Variations des stocks (approvisionnements et marchandises)"); - accountService.createAccount(accountVs); - } - - /** - * 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(expected = LimaException.class) - public void createAccountWithChildFailureTest() throws LimaException { - // Création des comptes - Account classFinancier = new AccountImpl(); - classFinancier.setAccountNumber("5"); - classFinancier.setLabel("Comptes financiers"); - accountService.createAccount(classFinancier); - - Account accountVmp = new AccountImpl(); - accountVmp.setAccountNumber("40"); - accountVmp.setLabel("Fournisseurs et comptes rattachés"); - accountService.createAccount(accountVmp); - } - - /** - * 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 5 Comptes financiers - Account result = accountService.getAccountByNumber("5"); - Assert.assertEquals("Comptes financiers", result.getLabel()); - } - - /** - * Permet de tester la méthode recherchant tous les comptes. - * - * @throws LimaException - */ - @Test - public void getAllAccountTest() throws LimaException { - List<Account> listAccount = accountService.getAllAccounts(); - Assert.assertEquals(7, listAccount.size()); - } - - /** - * Find all leaf account. - * - * @throws LimaException - */ - @Test - public void getAllLeafAccountTest() throws LimaException { - List<Account> listAccount = accountService.getAllLeafAccounts(); - Assert.assertEquals(4, listAccount.size()); - } - - /** - * Test get all subaccounts. - * - * @throws LimaException - */ - @Test - public void getAllSubAccountsTest() throws LimaException { - Account parent = accountService.getAccountByNumber("50"); - List<Account> listAccount = accountService.getAllSubAccounts(parent); - Assert.assertEquals(2, listAccount.size()); - - parent = accountService.getAccountByNumber("501"); - listAccount = accountService.getAllSubAccounts(parent); - Assert.assertEquals(0, listAccount.size()); - } - - /** - * Permet de tester si un compte est bien effacé. - * - * @throws LimaException - */ - @Test - public void removeAccountTest() throws LimaException { - Account accountToRemove = accountService.getAccountByNumber("50"); - - // On souhaite supprimer le compte 51. Ce compte existe bien. - accountService.removeAccount(accountToRemove); - - // Il ne doit rester que 6 compte - Assert.assertEquals(6, accountService.getAllAccounts().size()); - } - - /** - * On souhaite supprimer le compte 422, ce dernier n'existe pas. La - * suppression ne peut s'effectuer. - * - * @throws LimaException - */ - @Test(expected = LimaException.class) - public void removeUnexistedAccountTest() throws LimaException { - Account account4 = new AccountImpl(); - account4.setAccountNumber("422"); - account4.setLabel("Unsaved account"); - accountService.removeAccount(account4); - } -} \ No newline at end of file Added: trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/AccountServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,223 @@ +/* + * #%L + * Lima business + * + * $Id: AccountServiceImplTest.java 3400 2012-05-04 09:43:18Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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; + +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountImpl; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; + +/** + * Tests pour la gestion des comptes dans le plan comptable. + * + * Vérification sur l'ajout, la modification et suppression d'un compte. + * Il existe également des tests sur des actions à partir de DTO. La classe + * AccountServiceImplTest possède une méthode upload qui, à partir d'un DTO, + * va mettre à jour automatiquement dans la base de données. + * + * @author Rémi Chapelet + */ +public class AccountServiceImplTest extends AbstractLimaTest { + + @Before + public void initTest() throws Exception { + initTestDatabase(); + } + + /** + * Création d'un compte dans le plan comptable. + * @throws LimaException + */ + @Test + public void createAccountTest() throws LimaException { + Account myAccount = new AccountImpl(); + myAccount.setAccountNumber("2"); + myAccount.setLabel("Comptes d'immobilisations"); + accountService.createAccount(myAccount); + } + + /** + * Création d'un compte dans le plan comptable (echec duplication). + * + * @throws LimaException + */ + @Test(expected = LimaException.class) + public void createAccountEchecTest() throws LimaException { + Account myAccount = new AccountImpl(); + myAccount.setAccountNumber("5"); + myAccount.setLabel("Comptes de capitaux"); + accountService.createAccount(myAccount); + } + + /** + * Création d'un compte dans le plan comptable. + * + * Le test ne doit pas echoué avec les regles par defaut, mais peut echouer + * suivant certaines autres regles. + * + * @throws LimaException + */ + @Test + public void testCreateAccountWrongNumber() throws LimaException { + Account myAccount = new AccountImpl(); + myAccount.setAccountNumber("42"); // erreur de compte (4) + myAccount.setLabel("Comptes de tiers"); + accountService.createAccount(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 createAccountWithChildTest() throws LimaException { + // Création des comptes + Account classCharges = new AccountImpl(); + classCharges.setAccountNumber("6"); + classCharges.setLabel("Comptes de charges"); + accountService.createAccount(classCharges); + + Account accountAchat = new AccountImpl(); + accountAchat.setAccountNumber("60"); + accountAchat.setLabel("Achats (sauf 603)"); + accountService.createAccount(accountAchat); + + Account accountSe = new AccountImpl(); + accountSe.setAccountNumber("61"); + accountSe.setLabel("Services extérieurs"); + accountService.createAccount(accountSe); + + Account accountVs = new AccountImpl(); + accountVs.setAccountNumber("603"); + accountVs.setLabel("Variations des stocks (approvisionnements et marchandises)"); + accountService.createAccount(accountVs); + } + + /** + * 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(expected = LimaException.class) + public void createAccountWithChildFailureTest() throws LimaException { + // Création des comptes + Account classFinancier = new AccountImpl(); + classFinancier.setAccountNumber("5"); + classFinancier.setLabel("Comptes financiers"); + accountService.createAccount(classFinancier); + + Account accountVmp = new AccountImpl(); + accountVmp.setAccountNumber("40"); + accountVmp.setLabel("Fournisseurs et comptes rattachés"); + accountService.createAccount(accountVmp); + } + + /** + * 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 5 Comptes financiers + Account result = accountService.getAccountByNumber("5"); + Assert.assertEquals("Comptes financiers", result.getLabel()); + } + + /** + * Permet de tester la méthode recherchant tous les comptes. + * + * @throws LimaException + */ + @Test + public void getAllAccountTest() throws LimaException { + List<Account> listAccount = accountService.getAllAccounts(); + Assert.assertEquals(7, listAccount.size()); + } + + /** + * Find all leaf account. + * + * @throws LimaException + */ + @Test + public void getAllLeafAccountTest() throws LimaException { + List<Account> listAccount = accountService.getAllLeafAccounts(); + Assert.assertEquals(4, listAccount.size()); + } + + /** + * Test get all subaccounts. + * + * @throws LimaException + */ + @Test + public void getAllSubAccountsTest() throws LimaException { + Account parent = accountService.getAccountByNumber("50"); + List<Account> listAccount = accountService.getAllSubAccounts(parent); + Assert.assertEquals(2, listAccount.size()); + + parent = accountService.getAccountByNumber("501"); + listAccount = accountService.getAllSubAccounts(parent); + Assert.assertEquals(0, listAccount.size()); + } + + /** + * Permet de tester si un compte est bien effacé. + * + * @throws LimaException + */ + @Test + public void removeAccountTest() throws LimaException { + Account accountToRemove = accountService.getAccountByNumber("50"); + + // On souhaite supprimer le compte 51. Ce compte existe bien. + accountService.removeAccount(accountToRemove); + + // Il ne doit rester que 6 compte + Assert.assertEquals(6, accountService.getAllAccounts().size()); + } + + /** + * On souhaite supprimer le compte 422, ce dernier n'existe pas. La + * suppression ne peut s'effectuer. + * + * @throws LimaException + */ + @Test(expected = LimaException.class) + public void removeUnexistedAccountTest() throws LimaException { + Account account4 = new AccountImpl(); + account4.setAccountNumber("422"); + account4.setLabel("Unsaved account"); + accountService.removeAccount(account4); + } +} \ No newline at end of file Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/EntryBookServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/EntryBookServiceImplTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/EntryBookServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,100 +0,0 @@ -/* - * #%L - * Lima business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric - * %% - * 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; - -import org.chorem.lima.entity.EntryBook; -import org.chorem.lima.entity.EntryBookImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests pour la gestion des journaux. - * <p/> - * L'application peut gérer plusieurs journaux pour la gestion des transactions. - * Il est tester ici l'ajout, la recherche. - * - * @author Rémi Chapelet - */ -public class EntryBookServiceImplTest extends AbstractLimaTest { - - protected static final String JOURNAL_DES_VENTES = "Journal des ventes"; - - @Before - public void initTest() throws Exception { - initTestDatabase(); - } - - /** - * Permet de tester la modification d'un journal suivant son préfixe. - * - * @throws LimaException - */ - @Test - public void modifyJournalTest() throws LimaException { - - EntryBook entryBook = entryBookService.getAllEntryBooks().get(0); - Assert.assertNotNull(entryBook); - Assert.assertEquals(JOURNAL_DES_VENTES, entryBook.getLabel()); - entryBook.setLabel("Journal des achats"); - entryBookService.updateEntryBook(entryBook); - - // Recherche du journal dans la bdd - entryBook = entryBookService.getAllEntryBooks().get(0); - Assert.assertNotNull(entryBook); - Assert.assertEquals("Journal des achats", entryBook.getLabel()); - } - - /** - * Test que la suppression d'un journal utilisé n'est pas possible. - * - * @throws LimaException - */ - @Test(expected=LimaBusinessException.class) - public void deleteUsedEntryBook() throws LimaException { - EntryBook entryBook = entryBookService.getAllEntryBooks().get(0); // VTE - Assert.assertNotNull(entryBook); - entryBookService.removeEntryBook(entryBook); - } - - /** - * Un journal tout juste créé doit pouvoir être supprimé, y compris - * les closed qui sont lié entre le journal et les periodes. - * - * @throws LimaException - */ - @Test - public void deleteNonUsedEntryBookTest() throws LimaException { - EntryBook myEntryBook = new EntryBookImpl(); - myEntryBook.setCode("JRN"); - myEntryBook.setLabel("MyJournal"); - myEntryBook = entryBookService.createEntryBook(myEntryBook); - entryBookService.removeEntryBook(myEntryBook); - - Assert.assertEquals(1, entryBookService.getAllEntryBooks().size()); - - } -} \ No newline at end of file Added: trunk/lima-business/src/test/java/org/chorem/lima/business/EntryBookServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/EntryBookServiceImplTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/EntryBookServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,100 @@ +/* + * #%L + * Lima business + * + * $Id: EntryBookServiceImplTest.java 3391 2012-04-25 08:28:20Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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; + +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryBookImpl; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests pour la gestion des journaux. + * <p/> + * L'application peut gérer plusieurs journaux pour la gestion des transactions. + * Il est tester ici l'ajout, la recherche. + * + * @author Rémi Chapelet + */ +public class EntryBookServiceImplTest extends AbstractLimaTest { + + protected static final String JOURNAL_DES_VENTES = "Journal des ventes"; + + @Before + public void initTest() throws Exception { + initTestDatabase(); + } + + /** + * Permet de tester la modification d'un journal suivant son préfixe. + * + * @throws LimaException + */ + @Test + public void modifyJournalTest() throws LimaException { + + EntryBook entryBook = entryBookService.getAllEntryBooks().get(0); + Assert.assertNotNull(entryBook); + Assert.assertEquals(JOURNAL_DES_VENTES, entryBook.getLabel()); + entryBook.setLabel("Journal des achats"); + entryBookService.updateEntryBook(entryBook); + + // Recherche du journal dans la bdd + entryBook = entryBookService.getAllEntryBooks().get(0); + Assert.assertNotNull(entryBook); + Assert.assertEquals("Journal des achats", entryBook.getLabel()); + } + + /** + * Test que la suppression d'un journal utilisé n'est pas possible. + * + * @throws LimaException + */ + @Test(expected=LimaBusinessException.class) + public void deleteUsedEntryBook() throws LimaException { + EntryBook entryBook = entryBookService.getAllEntryBooks().get(0); // VTE + Assert.assertNotNull(entryBook); + entryBookService.removeEntryBook(entryBook); + } + + /** + * Un journal tout juste créé doit pouvoir être supprimé, y compris + * les closed qui sont lié entre le journal et les periodes. + * + * @throws LimaException + */ + @Test + public void deleteNonUsedEntryBookTest() throws LimaException { + EntryBook myEntryBook = new EntryBookImpl(); + myEntryBook.setCode("JRN"); + myEntryBook.setLabel("MyJournal"); + myEntryBook = entryBookService.createEntryBook(myEntryBook); + entryBookService.removeEntryBook(myEntryBook); + + Assert.assertEquals(1, entryBookService.getAllEntryBooks().size()); + + } +} \ No newline at end of file Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialPeriodServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialPeriodServiceImplTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialPeriodServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,81 +0,0 @@ -/* - * #%L - * Lima business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric - * %% - * 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; - -import org.chorem.lima.entity.ClosedPeriodicEntryBook; -import org.chorem.lima.entity.ClosedPeriodicEntryBookDAO; -import org.chorem.lima.entity.LimaCallaoDAOHelper; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; - -/** - * Tests pour la gestion des timespans - * <p/> - * Fonctions : - * _ création d'un timespan - * _ bloquer un timespan - * _ débloquer un timespan - * _ rechercher un timespan - * _ rechercher une période à partir d'un timespan - * - * @author Rémi Chapelet - */ -public class FinancialPeriodServiceImplTest extends AbstractLimaTest { - - @Before - public void initTest() throws Exception { - initTestDatabase(); - } - - /** - * Test de la fermeture d'une periode comptable pour un journal donné. - * - * @throws Exception - */ - @Test - public void blockClosedPeriodicEntryBookTest() throws Exception { - - // find one closed to close - TopiaContext context = getTestContext().beginTransaction(); - ClosedPeriodicEntryBookDAO dao = LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(context); - ClosedPeriodicEntryBook closedPeriodic = dao.findAll().get(0); - context.closeContext(); - - // block it - Assert.assertFalse(closedPeriodic.isLocked()); - closedPeriodic = financialPeriodService.blockClosedPeriodicEntryBook(closedPeriodic); - - // check it's blocked - context = getTestContext().beginTransaction(); - dao = LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(context); - closedPeriodic = dao.findAll().get(0); - context.closeContext(); - Assert.assertFalse(closedPeriodic.isLocked()); - } - -} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialPeriodServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialPeriodServiceImplTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialPeriodServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,81 @@ +/* + * #%L + * Lima business + * + * $Id: FinancialPeriodServiceImplTest.java 3614 2012-08-20 11:59:56Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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; + +import org.chorem.lima.entity.ClosedPeriodicEntryBook; +import org.chorem.lima.entity.ClosedPeriodicEntryBookDAO; +import org.chorem.lima.entity.LimaCallaoDAOHelper; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.nuiton.topia.TopiaContext; + +/** + * Tests pour la gestion des timespans + * <p/> + * Fonctions : + * _ création d'un timespan + * _ bloquer un timespan + * _ débloquer un timespan + * _ rechercher un timespan + * _ rechercher une période à partir d'un timespan + * + * @author Rémi Chapelet + */ +public class FinancialPeriodServiceImplTest extends AbstractLimaTest { + + @Before + public void initTest() throws Exception { + initTestDatabase(); + } + + /** + * Test de la fermeture d'une periode comptable pour un journal donné. + * + * @throws Exception + */ + @Test + public void blockClosedPeriodicEntryBookTest() throws Exception { + + // find one closed to close + TopiaContext context = getTestContext().beginTransaction(); + ClosedPeriodicEntryBookDAO dao = LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(context); + ClosedPeriodicEntryBook closedPeriodic = dao.findAll().get(0); + context.closeContext(); + + // block it + Assert.assertFalse(closedPeriodic.isLocked()); + closedPeriodic = financialPeriodService.blockClosedPeriodicEntryBook(closedPeriodic); + + // check it's blocked + context = getTestContext().beginTransaction(); + dao = LimaCallaoDAOHelper.getClosedPeriodicEntryBookDAO(context); + closedPeriodic = dao.findAll().get(0); + context.closeContext(); + Assert.assertFalse(closedPeriodic.isLocked()); + } + +} Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialTransactionServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialTransactionServiceImplTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialTransactionServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,177 +0,0 @@ -/* - * #%L - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 Codelutin, Chatellier Eric - * %% - * 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; - -import org.chorem.lima.business.ejb.FinancialTransactionServiceImpl; -import org.chorem.lima.entity.Account; -import org.chorem.lima.entity.Entry; -import org.chorem.lima.entity.EntryBook; -import org.chorem.lima.entity.EntryImpl; -import org.chorem.lima.entity.FinancialTransaction; -import org.chorem.lima.entity.FinancialTransactionImpl; -import org.chorem.lima.entity.FiscalPeriod; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.math.BigDecimal; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Test on financial transaction service. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class FinancialTransactionServiceImplTest extends AbstractLimaTest { - - @Before - public void initTest() throws LimaException, ParseException { - initTestDatabase(); - } - - /** - * Test to find all unbalanced transactions. - * Nothing wrong here. - * - * @throws ParseException - * @throws LimaException - */ - @Test - public void testGetInexactTransactionAllGood() throws ParseException, LimaException { - FiscalPeriod fiscalPeriod = fiscalPeriodService.getAllFiscalPeriods().get(0); - List<FinancialTransaction> transactions = financialTransactionService.getAllInexactFinancialTransactions(fiscalPeriod); - Assert.assertTrue(transactions.isEmpty()); - } - - /** - * Test to find all unbalanced transactions. - * - * wrong data. - * - * @throws ParseException - * @throws LimaException - */ - @Test - public void testGetInexactTransactionNotAllGood() throws ParseException, LimaException { - - EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); - Account accountVmpVae = accountService.getAccountByNumber("511"); - - FinancialTransaction transaction1 = new FinancialTransactionImpl(); - transaction1.setTransactionDate(df.parse("April 5, 2012")); - transaction1.setEntryBook(journalDesVentes); - transaction1 = financialTransactionService.createFinancialTransaction(transaction1); - - Entry tr1Entry1 = new EntryImpl(); - tr1Entry1.setAmount(BigDecimal.valueOf(42.0)); - tr1Entry1.setAccount(accountVmpVae); - tr1Entry1.setFinancialTransaction(transaction1); - //tr1Entry1.setDescription("test desc"); - tr1Entry1.setVoucher("voucher"); - tr1Entry1 = financialTransactionService.createEntry(tr1Entry1); - - Entry tr1Entry2 = new EntryImpl(); - tr1Entry2.setAmount(BigDecimal.valueOf(42.0)); - tr1Entry2.setDebit(true); - tr1Entry2.setAccount(accountVmpVae); - tr1Entry2.setFinancialTransaction(transaction1); - tr1Entry2.setDescription("test desc"); - tr1Entry2.setVoucher("voucher"); - tr1Entry2 = financialTransactionService.createEntry(tr1Entry2); - - // one in period - FiscalPeriod fiscalPeriod = fiscalPeriodService.getAllFiscalPeriods().get(0); - List<FinancialTransaction> transactions = financialTransactionService.getAllInexactFinancialTransactions(fiscalPeriod); - Assert.assertEquals(1, transactions.size()); - } - - /** - * Test to find all unbalanced transactions. - * - * Test only unbalanced transactions (no data errors : fields). - * - * @throws ParseException - * @throws LimaException - */ - @Test - public void testGetUnbalancedTransactionNotAllGood() throws ParseException, LimaException { - - EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); - Account accountVmpVae = accountService.getAccountByNumber("511"); - - FinancialTransaction transaction1 = new FinancialTransactionImpl(); - transaction1.setTransactionDate(df.parse("April 5, 2012")); - transaction1.setEntryBook(journalDesVentes); - transaction1 = financialTransactionService.createFinancialTransaction(transaction1); - - Entry tr1Entry1 = new EntryImpl(); - tr1Entry1.setAmount(BigDecimal.valueOf(54.0)); - tr1Entry1.setAccount(accountVmpVae); - tr1Entry1.setFinancialTransaction(transaction1); - tr1Entry1.setDescription("test desc"); - tr1Entry1.setVoucher("voucher"); - tr1Entry1 = financialTransactionService.createEntry(tr1Entry1); - - // one in period - FiscalPeriod fiscalPeriod = fiscalPeriodService.getAllFiscalPeriods().get(0); - List<FinancialTransaction> transactions = financialTransactionService.getAllInexactFinancialTransactions(fiscalPeriod); - Assert.assertEquals(1, transactions.size()); - } - - @Test - public void testLettersAfter() { - - Assert.assertEquals("A", FinancialTransactionServiceImpl.lettersAfter(null)); - Assert.assertEquals("A", FinancialTransactionServiceImpl.lettersAfter("")); - Assert.assertEquals("E", FinancialTransactionServiceImpl.lettersAfter("D")); - Assert.assertEquals("AA", FinancialTransactionServiceImpl.lettersAfter("Z")); - Assert.assertEquals("ASDGUAAAA", FinancialTransactionServiceImpl.lettersAfter("ASDGTZZZZ")); - - } - - @Test - public void testFindLastLetter() { - - FinancialTransactionServiceImpl instance = new FinancialTransactionServiceImpl(); - - String nextLetter = instance.findLastLetter(Arrays.asList("A", "BZ", "ZZZ", "C", "Z", "E")); - Assert.assertEquals("ZZZ", nextLetter); - - nextLetter = instance.findLastLetter(Arrays.asList("sfvq", "sfvr")); - Assert.assertEquals("", nextLetter); - - nextLetter = instance.findLastLetter(Arrays.asList("zzz", "ABC", "DEF")); - Assert.assertEquals("DEF", nextLetter); - - nextLetter = instance.findLastLetter(new ArrayList<String>()); - Assert.assertEquals("", nextLetter); - } -} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialTransactionServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialTransactionServiceImplTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/FinancialTransactionServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,177 @@ +/* + * #%L + * $Id: FinancialTransactionServiceImplTest.java 3710 2013-10-11 13:56:17Z Bavencoff $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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; + +import org.chorem.lima.business.ejb.FinancialTransactionServiceImpl; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryImpl; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionImpl; +import org.chorem.lima.entity.FiscalPeriod; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Test on financial transaction service. + * + * @author chatellier + * @version $Revision: 3710 $ + * + * Last update : $Date: 2013-10-11 15:56:17 +0200 (ven. 11 oct. 2013) $ + * By : $Author: Bavencoff $ + */ +public class FinancialTransactionServiceImplTest extends AbstractLimaTest { + + @Before + public void initTest() throws LimaException, ParseException { + initTestDatabase(); + } + + /** + * Test to find all unbalanced transactions. + * Nothing wrong here. + * + * @throws ParseException + * @throws LimaException + */ + @Test + public void testGetInexactTransactionAllGood() throws ParseException, LimaException { + FiscalPeriod fiscalPeriod = fiscalPeriodService.getAllFiscalPeriods().get(0); + List<FinancialTransaction> transactions = financialTransactionService.getAllInexactFinancialTransactions(fiscalPeriod); + Assert.assertTrue(transactions.isEmpty()); + } + + /** + * Test to find all unbalanced transactions. + * + * wrong data. + * + * @throws ParseException + * @throws LimaException + */ + @Test + public void testGetInexactTransactionNotAllGood() throws ParseException, LimaException { + + EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); + Account accountVmpVae = accountService.getAccountByNumber("511"); + + FinancialTransaction transaction1 = new FinancialTransactionImpl(); + transaction1.setTransactionDate(df.parse("April 5, 2012")); + transaction1.setEntryBook(journalDesVentes); + transaction1 = financialTransactionService.createFinancialTransaction(transaction1); + + Entry tr1Entry1 = new EntryImpl(); + tr1Entry1.setAmount(BigDecimal.valueOf(42.0)); + tr1Entry1.setAccount(accountVmpVae); + tr1Entry1.setFinancialTransaction(transaction1); + //tr1Entry1.setDescription("test desc"); + tr1Entry1.setVoucher("voucher"); + tr1Entry1 = financialTransactionService.createEntry(tr1Entry1); + + Entry tr1Entry2 = new EntryImpl(); + tr1Entry2.setAmount(BigDecimal.valueOf(42.0)); + tr1Entry2.setDebit(true); + tr1Entry2.setAccount(accountVmpVae); + tr1Entry2.setFinancialTransaction(transaction1); + tr1Entry2.setDescription("test desc"); + tr1Entry2.setVoucher("voucher"); + tr1Entry2 = financialTransactionService.createEntry(tr1Entry2); + + // one in period + FiscalPeriod fiscalPeriod = fiscalPeriodService.getAllFiscalPeriods().get(0); + List<FinancialTransaction> transactions = financialTransactionService.getAllInexactFinancialTransactions(fiscalPeriod); + Assert.assertEquals(1, transactions.size()); + } + + /** + * Test to find all unbalanced transactions. + * + * Test only unbalanced transactions (no data errors : fields). + * + * @throws ParseException + * @throws LimaException + */ + @Test + public void testGetUnbalancedTransactionNotAllGood() throws ParseException, LimaException { + + EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); + Account accountVmpVae = accountService.getAccountByNumber("511"); + + FinancialTransaction transaction1 = new FinancialTransactionImpl(); + transaction1.setTransactionDate(df.parse("April 5, 2012")); + transaction1.setEntryBook(journalDesVentes); + transaction1 = financialTransactionService.createFinancialTransaction(transaction1); + + Entry tr1Entry1 = new EntryImpl(); + tr1Entry1.setAmount(BigDecimal.valueOf(54.0)); + tr1Entry1.setAccount(accountVmpVae); + tr1Entry1.setFinancialTransaction(transaction1); + tr1Entry1.setDescription("test desc"); + tr1Entry1.setVoucher("voucher"); + tr1Entry1 = financialTransactionService.createEntry(tr1Entry1); + + // one in period + FiscalPeriod fiscalPeriod = fiscalPeriodService.getAllFiscalPeriods().get(0); + List<FinancialTransaction> transactions = financialTransactionService.getAllInexactFinancialTransactions(fiscalPeriod); + Assert.assertEquals(1, transactions.size()); + } + + @Test + public void testLettersAfter() { + + Assert.assertEquals("A", FinancialTransactionServiceImpl.lettersAfter(null)); + Assert.assertEquals("A", FinancialTransactionServiceImpl.lettersAfter("")); + Assert.assertEquals("E", FinancialTransactionServiceImpl.lettersAfter("D")); + Assert.assertEquals("AA", FinancialTransactionServiceImpl.lettersAfter("Z")); + Assert.assertEquals("ASDGUAAAA", FinancialTransactionServiceImpl.lettersAfter("ASDGTZZZZ")); + + } + + @Test + public void testFindLastLetter() { + + FinancialTransactionServiceImpl instance = new FinancialTransactionServiceImpl(); + + String nextLetter = instance.findLastLetter(Arrays.asList("A", "BZ", "ZZZ", "C", "Z", "E")); + Assert.assertEquals("ZZZ", nextLetter); + + nextLetter = instance.findLastLetter(Arrays.asList("sfvq", "sfvr")); + Assert.assertEquals("", nextLetter); + + nextLetter = instance.findLastLetter(Arrays.asList("zzz", "ABC", "DEF")); + Assert.assertEquals("DEF", nextLetter); + + nextLetter = instance.findLastLetter(new ArrayList<String>()); + Assert.assertEquals("", nextLetter); + } +} Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/FiscalPeriodServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/FiscalPeriodServiceImplTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/FiscalPeriodServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,278 +0,0 @@ -/* - * #%L - * Lima business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric - * %% - * 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; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests pour la gestion des périodes - * <p/> - * Fonctions : - * _ création d'une période - * _ valider une période (si elle est correcte) - * _ bloquer une période (ATTENTION : on ne peut débloquer une période !) - * _ rechercher une période - * - * @author Rémi Chapelet - */ -public class FiscalPeriodServiceImplTest extends AbstractLimaTest { - - /** log. */ - private static final Log log = LogFactory - .getLog(FiscalPeriodServiceImplTest.class); - - @Before - public void initTest() throws Exception { - initTestDatabase(); - } - - /** - * On nettoie la base de données - * - * @throws Exception - */ - @AfterClass - public static void tearDownClass() throws Exception { - /*Date d = new Date(110,0,1); - PeriodDTO periodDTO = instance.searchPeriodDTOWithDate(d); - instance.removePeriod(periodDTO); - d = new Date(109,0,1); - periodDTO = instance.searchPeriodDTOWithDate(d); - instance.removePeriod(periodDTO);*/ - } - - - @Test - public void blockFiscalPeriodTest() throws Exception { - - /*TopiaContext transaction = null; - FiscalPeriod recentFiscalPeriod = new FiscalPeriodImpl(); - FiscalPeriod oldestFiscalPeriod = new FiscalPeriodImpl(); - - try { - - transaction = beginTransaction(); - - FiscalPeriodDAO fiscalPeriodDAO = - LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); - - FinancialPeriodServiceImpl financialPeriodService = - new FinancialPeriodServiceImpl(); - - //On crée deux période, une récente - - FinancialPeriod financialPeriod = new FinancialPeriodImpl(); - Calendar beginCalendar = Calendar.getInstance(); - recentFiscalPeriod.setBeginDate(beginCalendar.getTime()); - Calendar endCalendar = beginCalendar; - endCalendar.add(Calendar.MONTH, 12); - recentFiscalPeriod.setEndDate(endCalendar.getTime()); - fiscalPeriodDAO.create(recentFiscalPeriod); - recentFiscalPeriod.addFinancialPeriod(financialPeriod); - - List<FinancialPeriod> financialPeriodsList = new ArrayList<FinancialPeriod>(); - financialPeriodsList.add(financialPeriod); - financialPeriodService.createFinancialPeriods(financialPeriodsList); - - - //une plus ancienne - beginCalendar.add(Calendar.YEAR, -2); - oldestFiscalPeriod.setBeginDate(beginCalendar.getTime()); - endCalendar.add(Calendar.YEAR, -2); - oldestFiscalPeriod.setEndDate(endCalendar.getTime()); - fiscalPeriodDAO.create(oldestFiscalPeriod); - oldestFiscalPeriod.addFinancialPeriod(financialPeriod); - - transaction.commitTransaction(); - - } finally { - transaction.closeContext(); - } - - - Assert.assertNotSame(recentFiscalPeriod.getTopiaId(), - oldestFiscalPeriod.getTopiaId()); - - FiscalPeriodService fiscalPeriodService = new FiscalPeriodServiceImpl(); - - - try{ - fiscalPeriodService.blockFiscalPeriod(oldestFiscalPeriod); - } catch (Exception ex){ - log.debug("Error test block Period", ex); - Assert.assertEquals(LimaBusinessException.class, ex.getClass()); - } - try { - fiscalPeriodService.blockFiscalPeriod(recentFiscalPeriod); - } catch (Exception ex){ - log.debug("Error test block Period", ex); - Assert.assertEquals(LimaBusinessException.class, ex.getClass()); - }*/ - } - - - /** Permet de tester l'ajout d'une période. */ - @Test - public void createPeriodTest() { - /*String result; - // debut 1 janvier 2009 - Date beginPeriod = new Date(109, 0, 1); - // fin 31 décembre 2009 - Date endPeriod = new Date(109, 11, 31); - // Création période avec son découpage sur 12 mois - result = instance.createPeriod(beginPeriod, endPeriod, false); - Assert.assertEquals(ServiceHelper.RESPOND_SUCCESS, result);*/ - } - - /** - * Permet de tester si différentes périodes sont correctes ou non - * La création d'une nouvelle période doit remplir ce contrat. - * On définit plusieurs périodes pour les créer dans Callao. Pour chaque - * création, la période est testée si elle est correcte ou non. - */ - @Test - public void isCorrectPeriodTest() { - /*// Période déja créée Jan 2009 - Déc 2009 (et non bloquée) (createPeriodTest) - // debut 1 janvier 2010 - Date beginPeriod = new Date(110, 0, 1); - // fin 1 février 2010 - Date endPeriod = new Date(110, 1, 1); - String result; - // Cette période est non correcte, car il n'y a pas 12 mois complets - // Et la période précédente est non bloquée. - result = instance.createPeriod(beginPeriod, endPeriod, false); - Assert.assertEquals(ServiceHelper.RESPOND_ERROR, result); - // Création période sur 12 mois, MAIS période précédente non bloquée ! - // fin 31 décembre 2010 pour avoir 12 mois complets - endPeriod = new Date(110, 11, 31); - result = instance.createPeriod(beginPeriod, endPeriod, false); - Assert.assertEquals(ServiceHelper.RESPOND_ERROR, result); - // Période précédente non bloquée et non collée au niveau des dates - // de début et fin - // debut 1 avril 2009 - beginPeriod = new Date(109, 3, 1); - // fin 31 mars 2010 - endPeriod = new Date(110, 2, 31); - result = instance.createPeriod(beginPeriod, endPeriod, false); - Assert.assertEquals(ServiceHelper.RESPOND_ERROR, result); - // Création période qui chevauche la période 2009. - // debut 1 fevrier 2008 - beginPeriod = new Date(108, 1, 1); - // fin 1 janvier 2009 - endPeriod = new Date(109, 0, 1); - result = instance.createPeriod(beginPeriod, endPeriod, false); - Assert.assertEquals(ServiceHelper.RESPOND_ERROR, result);*/ - } - - /** - * Permet de tester la recherche sur les périodes. Il suffit de donner une - * date quelconque, il est renvoyé alors la période dont l'intervalle de - * temps comprend cette date. - */ - @Test - public void searchPeriodWithDateTest() { - /*// Période créée Jan 2009 - Déc 2009 (et non bloquée) (createPeriodTest) - // Date recherchée 17 avril 2009 - Date dateSearch = new Date(109, 3, 17); - Period period = instance.searchPeriodWithDate(dateSearch); - assertTrue(period != null); // Période trouvée - // Date recherchée 17 septembre 2000 - dateSearch = new Date(100, 8, 17); - period = instance.searchPeriodWithDate(dateSearch); - assertTrue(period == null); // Période non trouvée - // Recherche la période sur la date de debut de période. - // Date recherchée 1 janvier 2009 - dateSearch = new Date(109, 0, 1); - period = instance.searchPeriodWithDate(dateSearch); - assertTrue(period != null); // Période trouvée - // Recherche la période sur la date de fin de période. - // Date recherchée 31 décembre 2009 - dateSearch = new Date(109, 11, 31); - period = instance.searchPeriodWithDate(dateSearch); - assertTrue(period != null); // Période trouvée*/ - } - - /** - * Permet de tester si les périodes peuvent être bloquées ou non - * Test également la fonction permettant de bloquer tous les timespans - * d'une période. - */ - @Test - public void blockPeriodTest() { - /*// Période créée Jan 2009 - Déc 2009 (et non bloquée) (createPeriodTest) - // debut 1 janvier 2009 - Date beginTimeSpan = new Date(109, 0, 1); - String result; - // On souhaite bloquer la période, MAIS les timeSpans ne le sont pas - // On recherche la période Jan 2009 - Déc 2009 - Period period = instance.searchPeriodWithDate(beginTimeSpan); - result = instance.blockPeriod(period); - Assert.assertEquals(ServiceHelper.PERIOD_TIMESPAN_NOT_BLOCK, result); - // On bloque tous les timeSpans et la période ensuite - result = instance.blockAllTimeSpanOfPeriod(period); - Assert.assertEquals(ServiceHelper.RESPOND_SUCCESS, result); - // On bloque de nouveau la période - result = instance.blockPeriod(period); - Assert.assertEquals(ServiceHelper.RESPOND_SUCCESS, result);*/ - } - - /** - * Permet de tester les objets DTO pour la période. - * Création d'une période 2015 avec la création des 12 timeSpans - */ - @Test - public void PeriodDTOTest() { - /*// Création période DTO - Date dateBegin = new Date(110, 0, 1); - Date dateEnd = new Date(110, 11, 31); - PeriodDTO periodDTO = new PeriodDTO(); - periodDTO.setBeginPeriod(dateBegin); - periodDTO.setEndPeriod(dateEnd); - // Création BDD - String result = instance.createPeriod(periodDTO); - Assert.assertEquals(ServiceHelper.RESPOND_SUCCESS, result);*/ - } - - /** - * Permet de tester la transformation d'une période en DTO avec ses timeSpans - * associés. - */ - @Test - public void searchPeriodDTOTest() { - /*// Cherche la période 2009 - Date dateBegin = new Date(109, 0, 1); - PeriodDTO periodDTO = instance.searchPeriodDTOWithDate(dateBegin); - Assert.assertEquals(dateBegin, periodDTO.getBeginPeriod()); - // Recherche des timeSpanDTO - List<TimeSpanDTO> listTimeSpanDTO = periodDTO.getListTimeSpan(); - // Nombre 12 timeSpans mensuels - Assert.assertEquals(12, listTimeSpanDTO.size());*/ - } -} \ No newline at end of file Added: trunk/lima-business/src/test/java/org/chorem/lima/business/FiscalPeriodServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/FiscalPeriodServiceImplTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/FiscalPeriodServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,278 @@ +/* + * #%L + * Lima business + * + * $Id: FiscalPeriodServiceImplTest.java 3391 2012-04-25 08:28:20Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests pour la gestion des périodes + * <p/> + * Fonctions : + * _ création d'une période + * _ valider une période (si elle est correcte) + * _ bloquer une période (ATTENTION : on ne peut débloquer une période !) + * _ rechercher une période + * + * @author Rémi Chapelet + */ +public class FiscalPeriodServiceImplTest extends AbstractLimaTest { + + /** log. */ + private static final Log log = LogFactory + .getLog(FiscalPeriodServiceImplTest.class); + + @Before + public void initTest() throws Exception { + initTestDatabase(); + } + + /** + * On nettoie la base de données + * + * @throws Exception + */ + @AfterClass + public static void tearDownClass() throws Exception { + /*Date d = new Date(110,0,1); + PeriodDTO periodDTO = instance.searchPeriodDTOWithDate(d); + instance.removePeriod(periodDTO); + d = new Date(109,0,1); + periodDTO = instance.searchPeriodDTOWithDate(d); + instance.removePeriod(periodDTO);*/ + } + + + @Test + public void blockFiscalPeriodTest() throws Exception { + + /*TopiaContext transaction = null; + FiscalPeriod recentFiscalPeriod = new FiscalPeriodImpl(); + FiscalPeriod oldestFiscalPeriod = new FiscalPeriodImpl(); + + try { + + transaction = beginTransaction(); + + FiscalPeriodDAO fiscalPeriodDAO = + LimaCallaoDAOHelper.getFiscalPeriodDAO(transaction); + + FinancialPeriodServiceImpl financialPeriodService = + new FinancialPeriodServiceImpl(); + + //On crée deux période, une récente + + FinancialPeriod financialPeriod = new FinancialPeriodImpl(); + Calendar beginCalendar = Calendar.getInstance(); + recentFiscalPeriod.setBeginDate(beginCalendar.getTime()); + Calendar endCalendar = beginCalendar; + endCalendar.add(Calendar.MONTH, 12); + recentFiscalPeriod.setEndDate(endCalendar.getTime()); + fiscalPeriodDAO.create(recentFiscalPeriod); + recentFiscalPeriod.addFinancialPeriod(financialPeriod); + + List<FinancialPeriod> financialPeriodsList = new ArrayList<FinancialPeriod>(); + financialPeriodsList.add(financialPeriod); + financialPeriodService.createFinancialPeriods(financialPeriodsList); + + + //une plus ancienne + beginCalendar.add(Calendar.YEAR, -2); + oldestFiscalPeriod.setBeginDate(beginCalendar.getTime()); + endCalendar.add(Calendar.YEAR, -2); + oldestFiscalPeriod.setEndDate(endCalendar.getTime()); + fiscalPeriodDAO.create(oldestFiscalPeriod); + oldestFiscalPeriod.addFinancialPeriod(financialPeriod); + + transaction.commitTransaction(); + + } finally { + transaction.closeContext(); + } + + + Assert.assertNotSame(recentFiscalPeriod.getTopiaId(), + oldestFiscalPeriod.getTopiaId()); + + FiscalPeriodService fiscalPeriodService = new FiscalPeriodServiceImpl(); + + + try{ + fiscalPeriodService.blockFiscalPeriod(oldestFiscalPeriod); + } catch (Exception ex){ + log.debug("Error test block Period", ex); + Assert.assertEquals(LimaBusinessException.class, ex.getClass()); + } + try { + fiscalPeriodService.blockFiscalPeriod(recentFiscalPeriod); + } catch (Exception ex){ + log.debug("Error test block Period", ex); + Assert.assertEquals(LimaBusinessException.class, ex.getClass()); + }*/ + } + + + /** Permet de tester l'ajout d'une période. */ + @Test + public void createPeriodTest() { + /*String result; + // debut 1 janvier 2009 + Date beginPeriod = new Date(109, 0, 1); + // fin 31 décembre 2009 + Date endPeriod = new Date(109, 11, 31); + // Création période avec son découpage sur 12 mois + result = instance.createPeriod(beginPeriod, endPeriod, false); + Assert.assertEquals(ServiceHelper.RESPOND_SUCCESS, result);*/ + } + + /** + * Permet de tester si différentes périodes sont correctes ou non + * La création d'une nouvelle période doit remplir ce contrat. + * On définit plusieurs périodes pour les créer dans Callao. Pour chaque + * création, la période est testée si elle est correcte ou non. + */ + @Test + public void isCorrectPeriodTest() { + /*// Période déja créée Jan 2009 - Déc 2009 (et non bloquée) (createPeriodTest) + // debut 1 janvier 2010 + Date beginPeriod = new Date(110, 0, 1); + // fin 1 février 2010 + Date endPeriod = new Date(110, 1, 1); + String result; + // Cette période est non correcte, car il n'y a pas 12 mois complets + // Et la période précédente est non bloquée. + result = instance.createPeriod(beginPeriod, endPeriod, false); + Assert.assertEquals(ServiceHelper.RESPOND_ERROR, result); + // Création période sur 12 mois, MAIS période précédente non bloquée ! + // fin 31 décembre 2010 pour avoir 12 mois complets + endPeriod = new Date(110, 11, 31); + result = instance.createPeriod(beginPeriod, endPeriod, false); + Assert.assertEquals(ServiceHelper.RESPOND_ERROR, result); + // Période précédente non bloquée et non collée au niveau des dates + // de début et fin + // debut 1 avril 2009 + beginPeriod = new Date(109, 3, 1); + // fin 31 mars 2010 + endPeriod = new Date(110, 2, 31); + result = instance.createPeriod(beginPeriod, endPeriod, false); + Assert.assertEquals(ServiceHelper.RESPOND_ERROR, result); + // Création période qui chevauche la période 2009. + // debut 1 fevrier 2008 + beginPeriod = new Date(108, 1, 1); + // fin 1 janvier 2009 + endPeriod = new Date(109, 0, 1); + result = instance.createPeriod(beginPeriod, endPeriod, false); + Assert.assertEquals(ServiceHelper.RESPOND_ERROR, result);*/ + } + + /** + * Permet de tester la recherche sur les périodes. Il suffit de donner une + * date quelconque, il est renvoyé alors la période dont l'intervalle de + * temps comprend cette date. + */ + @Test + public void searchPeriodWithDateTest() { + /*// Période créée Jan 2009 - Déc 2009 (et non bloquée) (createPeriodTest) + // Date recherchée 17 avril 2009 + Date dateSearch = new Date(109, 3, 17); + Period period = instance.searchPeriodWithDate(dateSearch); + assertTrue(period != null); // Période trouvée + // Date recherchée 17 septembre 2000 + dateSearch = new Date(100, 8, 17); + period = instance.searchPeriodWithDate(dateSearch); + assertTrue(period == null); // Période non trouvée + // Recherche la période sur la date de debut de période. + // Date recherchée 1 janvier 2009 + dateSearch = new Date(109, 0, 1); + period = instance.searchPeriodWithDate(dateSearch); + assertTrue(period != null); // Période trouvée + // Recherche la période sur la date de fin de période. + // Date recherchée 31 décembre 2009 + dateSearch = new Date(109, 11, 31); + period = instance.searchPeriodWithDate(dateSearch); + assertTrue(period != null); // Période trouvée*/ + } + + /** + * Permet de tester si les périodes peuvent être bloquées ou non + * Test également la fonction permettant de bloquer tous les timespans + * d'une période. + */ + @Test + public void blockPeriodTest() { + /*// Période créée Jan 2009 - Déc 2009 (et non bloquée) (createPeriodTest) + // debut 1 janvier 2009 + Date beginTimeSpan = new Date(109, 0, 1); + String result; + // On souhaite bloquer la période, MAIS les timeSpans ne le sont pas + // On recherche la période Jan 2009 - Déc 2009 + Period period = instance.searchPeriodWithDate(beginTimeSpan); + result = instance.blockPeriod(period); + Assert.assertEquals(ServiceHelper.PERIOD_TIMESPAN_NOT_BLOCK, result); + // On bloque tous les timeSpans et la période ensuite + result = instance.blockAllTimeSpanOfPeriod(period); + Assert.assertEquals(ServiceHelper.RESPOND_SUCCESS, result); + // On bloque de nouveau la période + result = instance.blockPeriod(period); + Assert.assertEquals(ServiceHelper.RESPOND_SUCCESS, result);*/ + } + + /** + * Permet de tester les objets DTO pour la période. + * Création d'une période 2015 avec la création des 12 timeSpans + */ + @Test + public void PeriodDTOTest() { + /*// Création période DTO + Date dateBegin = new Date(110, 0, 1); + Date dateEnd = new Date(110, 11, 31); + PeriodDTO periodDTO = new PeriodDTO(); + periodDTO.setBeginPeriod(dateBegin); + periodDTO.setEndPeriod(dateEnd); + // Création BDD + String result = instance.createPeriod(periodDTO); + Assert.assertEquals(ServiceHelper.RESPOND_SUCCESS, result);*/ + } + + /** + * Permet de tester la transformation d'une période en DTO avec ses timeSpans + * associés. + */ + @Test + public void searchPeriodDTOTest() { + /*// Cherche la période 2009 + Date dateBegin = new Date(109, 0, 1); + PeriodDTO periodDTO = instance.searchPeriodDTOWithDate(dateBegin); + Assert.assertEquals(dateBegin, periodDTO.getBeginPeriod()); + // Recherche des timeSpanDTO + List<TimeSpanDTO> listTimeSpanDTO = periodDTO.getListTimeSpan(); + // Nombre 12 timeSpans mensuels + Assert.assertEquals(12, listTimeSpanDTO.size());*/ + } +} \ No newline at end of file Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/ImportServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/ImportServiceImplTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/ImportServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,164 +0,0 @@ -/* - * #%L - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 Codelutin, Chatellier Eric - * %% - * 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; - -import java.io.IOException; -import java.io.InputStream; -import java.text.ParseException; - -import org.apache.commons.io.IOUtils; -import org.chorem.lima.business.utils.ImportExportEntityEnum; -import org.chorem.lima.entity.Account; -import org.chorem.lima.entity.FiscalPeriod; -import org.chorem.lima.entity.FiscalPeriodImpl; -import org.junit.Assert; -import org.junit.Test; - -/** - * Test du service d'import en faisant des import/export EBP et xml. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class ImportServiceImplTest extends AbstractLimaTest { - - /** - * Import files available in src/test/resources/ebp. - * - * @throws IOException - * @throws LimaException - * @throws ParseException - */ - protected void importEBPData() throws IOException, LimaException, ParseException { - - clearService.clearDatabase(); - - // create fiscal period (mandatory for import) - FiscalPeriod fiscalPeriod = new FiscalPeriodImpl(); - fiscalPeriod.setBeginDate(df.parse("January 1, 2012")); - fiscalPeriod.setEndDate(df.parse("December 31, 2012")); - fiscalPeriodService.createFiscalPeriod(fiscalPeriod); - - // import files - InputStream accountStream = null; - InputStream entryBookStream = null; - InputStream entriesStream = null; - try { - accountStream = ImportServiceImplTest.class.getResourceAsStream("/ebp/comptes.txt"); - String accountData = IOUtils.toString(accountStream, "ISO-8859-1"); - importService.importAccountsChartFromEbp(accountData); - accountStream.close(); - - entryBookStream = ImportServiceImplTest.class.getResourceAsStream("/ebp/journaux.txt"); - String entryBookData = IOUtils.toString(entryBookStream, "ISO-8859-1"); - importService.importEntryBookFromEbp(entryBookData); - entryBookStream.close(); - - entriesStream = ImportServiceImplTest.class.getResourceAsStream("/ebp/ecritures.txt"); - String entriesData = IOUtils.toString(entriesStream, "ISO-8859-1"); - importService.importEntriesFromEbp(entriesData); - entriesStream.close(); - } - finally { - IOUtils.closeQuietly(accountStream); - IOUtils.closeQuietly(entryBookStream); - IOUtils.closeQuietly(entriesStream); - } - } - - /** - * Do some test on imported accounts. - * - * @throws Exception - */ - @Test - public void testImportAccountsEBP() throws Exception { - importEBPData(); - - Assert.assertEquals(571, accountService.getAllAccounts().size()); - Assert.assertEquals("Créances", accountService.getAccountByNumber("78174000").getLabel()); - - // test employe and client - Assert.assertNotNull(accountService.getAccountByNumber("401TEEMP")); - Assert.assertNotNull(accountService.getAccountByNumber("411TECLI")); - } - - /** - * Test que les comptes tiers sont correctement rattachés à l'arbre du - * plan comptable. - * - * @throws Exception - */ - @Test - public void testImportCreateIntermediaiteAccount() throws Exception { - importEBPData(); - - Account compteTiers = accountService.getAccountByNumber("4"); - Account employeAccount = accountService.getAccountByNumber("401TEEMP"); - Assert.assertNotNull(compteTiers); - Assert.assertNotNull(employeAccount); - } - - /** - * Do some test on imported accounts. - * - * @throws Exception - */ - @Test - public void testImportEntryBookEBP() throws Exception { - importEBPData(); - - Assert.assertNotNull(entryBookService.getEntryBookByCode("AN")); - Assert.assertNotNull(entryBookService.getEntryBookByCode("BQ")); - } - - /** - * Test que les import csv fourni avec lima s'import bien. - * @throws Exception - */ - @Test - public void testImportCSVPCG() throws Exception { - clearService.clearDatabase(); - - String pcg = IOUtils.toString(ImportServiceImplTest.class.getResourceAsStream("/import/pcg_base.csv")); - importService.importAsCSV(pcg, ImportExportEntityEnum.ACCOUNT); - Assert.assertEquals(461, accountService.getAccountCount()); - } - - /** - * Test que les import csv fourni avec lima s'import bien. - * @throws Exception - */ - @Test - public void testImportCSVEb() throws Exception { - clearService.clearDatabase(); - - String pcg = IOUtils.toString(ImportServiceImplTest.class.getResourceAsStream("/import/eb_default.csv")); - importService.importAsCSV(pcg, ImportExportEntityEnum.ENTRYBOOK); - Assert.assertEquals(5, entryBookService.getAllEntryBooks().size()); - } -} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/ImportServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/ImportServiceImplTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/ImportServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,164 @@ +/* + * #%L + * $Id: ImportServiceImplTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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; + +import java.io.IOException; +import java.io.InputStream; +import java.text.ParseException; + +import org.apache.commons.io.IOUtils; +import org.chorem.lima.business.utils.ImportExportEntityEnum; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.FiscalPeriod; +import org.chorem.lima.entity.FiscalPeriodImpl; +import org.junit.Assert; +import org.junit.Test; + +/** + * Test du service d'import en faisant des import/export EBP et xml. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class ImportServiceImplTest extends AbstractLimaTest { + + /** + * Import files available in src/test/resources/ebp. + * + * @throws IOException + * @throws LimaException + * @throws ParseException + */ + protected void importEBPData() throws IOException, LimaException, ParseException { + + clearService.clearDatabase(); + + // create fiscal period (mandatory for import) + FiscalPeriod fiscalPeriod = new FiscalPeriodImpl(); + fiscalPeriod.setBeginDate(df.parse("January 1, 2012")); + fiscalPeriod.setEndDate(df.parse("December 31, 2012")); + fiscalPeriodService.createFiscalPeriod(fiscalPeriod); + + // import files + InputStream accountStream = null; + InputStream entryBookStream = null; + InputStream entriesStream = null; + try { + accountStream = ImportServiceImplTest.class.getResourceAsStream("/ebp/comptes.txt"); + String accountData = IOUtils.toString(accountStream, "ISO-8859-1"); + importService.importAccountsChartFromEbp(accountData); + accountStream.close(); + + entryBookStream = ImportServiceImplTest.class.getResourceAsStream("/ebp/journaux.txt"); + String entryBookData = IOUtils.toString(entryBookStream, "ISO-8859-1"); + importService.importEntryBookFromEbp(entryBookData); + entryBookStream.close(); + + entriesStream = ImportServiceImplTest.class.getResourceAsStream("/ebp/ecritures.txt"); + String entriesData = IOUtils.toString(entriesStream, "ISO-8859-1"); + importService.importEntriesFromEbp(entriesData); + entriesStream.close(); + } + finally { + IOUtils.closeQuietly(accountStream); + IOUtils.closeQuietly(entryBookStream); + IOUtils.closeQuietly(entriesStream); + } + } + + /** + * Do some test on imported accounts. + * + * @throws Exception + */ + @Test + public void testImportAccountsEBP() throws Exception { + importEBPData(); + + Assert.assertEquals(571, accountService.getAllAccounts().size()); + Assert.assertEquals("Créances", accountService.getAccountByNumber("78174000").getLabel()); + + // test employe and client + Assert.assertNotNull(accountService.getAccountByNumber("401TEEMP")); + Assert.assertNotNull(accountService.getAccountByNumber("411TECLI")); + } + + /** + * Test que les comptes tiers sont correctement rattachés à l'arbre du + * plan comptable. + * + * @throws Exception + */ + @Test + public void testImportCreateIntermediaiteAccount() throws Exception { + importEBPData(); + + Account compteTiers = accountService.getAccountByNumber("4"); + Account employeAccount = accountService.getAccountByNumber("401TEEMP"); + Assert.assertNotNull(compteTiers); + Assert.assertNotNull(employeAccount); + } + + /** + * Do some test on imported accounts. + * + * @throws Exception + */ + @Test + public void testImportEntryBookEBP() throws Exception { + importEBPData(); + + Assert.assertNotNull(entryBookService.getEntryBookByCode("AN")); + Assert.assertNotNull(entryBookService.getEntryBookByCode("BQ")); + } + + /** + * Test que les import csv fourni avec lima s'import bien. + * @throws Exception + */ + @Test + public void testImportCSVPCG() throws Exception { + clearService.clearDatabase(); + + String pcg = IOUtils.toString(ImportServiceImplTest.class.getResourceAsStream("/import/pcg_base.csv")); + importService.importAsCSV(pcg, ImportExportEntityEnum.ACCOUNT); + Assert.assertEquals(461, accountService.getAccountCount()); + } + + /** + * Test que les import csv fourni avec lima s'import bien. + * @throws Exception + */ + @Test + public void testImportCSVEb() throws Exception { + clearService.clearDatabase(); + + String pcg = IOUtils.toString(ImportServiceImplTest.class.getResourceAsStream("/import/eb_default.csv")); + importService.importAsCSV(pcg, ImportExportEntityEnum.ENTRYBOOK); + Assert.assertEquals(5, entryBookService.getAllEntryBooks().size()); + } +} Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/LetteringComparatorTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/LetteringComparatorTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/LetteringComparatorTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,58 +0,0 @@ -package org.chorem.lima.business; -/* - * #%L - * Lima :: business - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 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% - */ - -import org.chorem.lima.business.utils.LetteringComparator; -import org.junit.Assert; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Created with IntelliJ IDEA. - * User: mallon - * Date: 24/07/12 - * Time: 15:42 - * To change this template use File | Settings | File Templates. - */ -public class LetteringComparatorTest { - - @Test - public void testCompare() { - List<String> letters = Arrays.asList("A", "BZ", "ZZZ", "C", "Z", "E"); - - Collections.sort(letters, new LetteringComparator()); - Collections.reverse(letters); - - Assert.assertEquals("A", letters.get(5)); - Assert.assertEquals("C", letters.get(4)); - Assert.assertEquals("E", letters.get(3)); - Assert.assertEquals("Z", letters.get(2)); - Assert.assertEquals("BZ", letters.get(1)); - Assert.assertEquals("ZZZ", letters.get(0)); - } - -} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/LetteringComparatorTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/LetteringComparatorTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/LetteringComparatorTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,58 @@ +package org.chorem.lima.business; +/* + * #%L + * Lima :: business + * $Id: LetteringComparatorTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 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% + */ + +import org.chorem.lima.business.utils.LetteringComparator; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * User: mallon + * Date: 24/07/12 + * Time: 15:42 + * To change this template use File | Settings | File Templates. + */ +public class LetteringComparatorTest { + + @Test + public void testCompare() { + List<String> letters = Arrays.asList("A", "BZ", "ZZZ", "C", "Z", "E"); + + Collections.sort(letters, new LetteringComparator()); + Collections.reverse(letters); + + Assert.assertEquals("A", letters.get(5)); + Assert.assertEquals("C", letters.get(4)); + Assert.assertEquals("E", letters.get(3)); + Assert.assertEquals("Z", letters.get(2)); + Assert.assertEquals("BZ", letters.get(1)); + Assert.assertEquals("ZZZ", letters.get(0)); + } + +} Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/LimaMiscTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/LimaMiscTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/LimaMiscTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,51 +0,0 @@ -/* - * #%L - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 Codelutin, Chatellier Eric - * %% - * 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; - -import org.chorem.lima.business.accountingrules.FranceAccountingRules; -import org.junit.Assert; -import org.junit.Test; - -/** - * Lima misc tests. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class LimaMiscTest extends AbstractLimaTest { - - /** - * Test que la regles de nationnalité par defaut est Default pour - * la majorité des tests. - */ - @Test - public void testDefaultRule() { - Assert.assertFalse(LimaConfig.getInstance().getAccountingRules() - instanceof FranceAccountingRules); - } - -} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/LimaMiscTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/LimaMiscTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/LimaMiscTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,51 @@ +/* + * #%L + * $Id: LimaMiscTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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; + +import org.chorem.lima.business.accountingrules.FranceAccountingRules; +import org.junit.Assert; +import org.junit.Test; + +/** + * Lima misc tests. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class LimaMiscTest extends AbstractLimaTest { + + /** + * Test que la regles de nationnalité par defaut est Default pour + * la majorité des tests. + */ + @Test + public void testDefaultRule() { + Assert.assertFalse(LimaConfig.getInstance().getAccountingRules() + instanceof FranceAccountingRules); + } + +} Deleted: trunk/lima-business/src/test/java/org/chorem/lima/business/ReportServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/ReportServiceImplTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/ReportServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,110 +0,0 @@ -/* - * #%L - * Lima business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 CodeLutin, Chatellier Eric - * %% - * 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; - -import org.chorem.lima.beans.ReportsDatas; -import org.chorem.lima.entity.Account; -import org.chorem.lima.entity.Entry; -import org.chorem.lima.entity.EntryBook; -import org.chorem.lima.entity.EntryImpl; -import org.chorem.lima.entity.FinancialTransaction; -import org.chorem.lima.entity.FinancialTransactionImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Test le service de génération des reports. - * - * FIXME echatellier 20120424 les tests sont désactivés car le code qui genere - * les rapports dans ReportService est commenté. - */ -@Ignore -public class ReportServiceImplTest extends AbstractLimaTest { - - @Before - public void initTest() throws Exception { - initTestDatabase(); - } - - /** - * Test de génération du rapport des comptes. - * - * @throws Exception - */ - @Test - public void testGenerateAccountsReports() throws Exception { - - Account accountBefa = accountService.getAccountByNumber("51"); - Assert.assertNotNull(accountBefa); - - Date beginDate = df.parse("April 1, 2012"); - Date endDate = df.parse("May 31, 2012"); - ReportsDatas datas = reportService.generateAccountsReports(accountBefa, false, beginDate, endDate); - Assert.assertEquals(BigDecimal.valueOf(42), datas.getAmountCredit().stripTrailingZeros()); - Assert.assertEquals(BigDecimal.valueOf(42), datas.getAmountDebit().stripTrailingZeros()); - - beginDate = df.parse("May 1, 2012"); - datas = reportService.generateAccountsReports(accountBefa, false, beginDate, endDate); - Assert.assertEquals(BigDecimal.valueOf(0), datas.getAmountCredit().stripTrailingZeros()); - Assert.assertEquals(BigDecimal.valueOf(0), datas.getAmountDebit().stripTrailingZeros()); - } - - /** - * Test de génération du rapport des comptes, en verifiant que les transactions - * non équilibrées ne sont pas présentes (modification 0.6). - * - * @throws Exception - */ - @Test - public void testGenerateAccountsReportsUnlalanced() throws Exception { - EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); - Account accountVmpVae = accountService.getAccountByNumber("511"); - - FinancialTransaction transaction1 = new FinancialTransactionImpl(); - transaction1.setTransactionDate(df.parse("April 5, 2012")); - transaction1.setEntryBook(journalDesVentes); - transaction1 = financialTransactionService.createFinancialTransaction(transaction1); - - Entry tr1Entry1 = new EntryImpl(); - tr1Entry1.setAmount(BigDecimal.valueOf(54.0)); - tr1Entry1.setAccount(accountVmpVae); - tr1Entry1.setFinancialTransaction(transaction1); - tr1Entry1.setDescription("test desc"); - tr1Entry1.setVoucher("voucher"); - tr1Entry1 = financialTransactionService.createEntry(tr1Entry1); - - Date beginDate = df.parse("April 1, 2012"); - Date endDate = df.parse("May 31, 2012"); - ReportsDatas datas = reportService.generateAccountsReports(accountVmpVae, false, beginDate, endDate); - Assert.assertEquals(BigDecimal.valueOf(42), datas.getAmountCredit().stripTrailingZeros()); - Assert.assertEquals(BigDecimal.valueOf(42), datas.getAmountDebit().stripTrailingZeros()); - } -} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/ReportServiceImplTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/ReportServiceImplTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/ReportServiceImplTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,110 @@ +/* + * #%L + * Lima business + * + * $Id: ReportServiceImplTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 CodeLutin, Chatellier Eric + * %% + * 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; + +import org.chorem.lima.beans.ReportsDatas; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryBook; +import org.chorem.lima.entity.EntryImpl; +import org.chorem.lima.entity.FinancialTransaction; +import org.chorem.lima.entity.FinancialTransactionImpl; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * Test le service de génération des reports. + * + * FIXME echatellier 20120424 les tests sont désactivés car le code qui genere + * les rapports dans ReportService est commenté. + */ +@Ignore +public class ReportServiceImplTest extends AbstractLimaTest { + + @Before + public void initTest() throws Exception { + initTestDatabase(); + } + + /** + * Test de génération du rapport des comptes. + * + * @throws Exception + */ + @Test + public void testGenerateAccountsReports() throws Exception { + + Account accountBefa = accountService.getAccountByNumber("51"); + Assert.assertNotNull(accountBefa); + + Date beginDate = df.parse("April 1, 2012"); + Date endDate = df.parse("May 31, 2012"); + ReportsDatas datas = reportService.generateAccountsReports(accountBefa, false, beginDate, endDate); + Assert.assertEquals(BigDecimal.valueOf(42), datas.getAmountCredit().stripTrailingZeros()); + Assert.assertEquals(BigDecimal.valueOf(42), datas.getAmountDebit().stripTrailingZeros()); + + beginDate = df.parse("May 1, 2012"); + datas = reportService.generateAccountsReports(accountBefa, false, beginDate, endDate); + Assert.assertEquals(BigDecimal.valueOf(0), datas.getAmountCredit().stripTrailingZeros()); + Assert.assertEquals(BigDecimal.valueOf(0), datas.getAmountDebit().stripTrailingZeros()); + } + + /** + * Test de génération du rapport des comptes, en verifiant que les transactions + * non équilibrées ne sont pas présentes (modification 0.6). + * + * @throws Exception + */ + @Test + public void testGenerateAccountsReportsUnlalanced() throws Exception { + EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); + Account accountVmpVae = accountService.getAccountByNumber("511"); + + FinancialTransaction transaction1 = new FinancialTransactionImpl(); + transaction1.setTransactionDate(df.parse("April 5, 2012")); + transaction1.setEntryBook(journalDesVentes); + transaction1 = financialTransactionService.createFinancialTransaction(transaction1); + + Entry tr1Entry1 = new EntryImpl(); + tr1Entry1.setAmount(BigDecimal.valueOf(54.0)); + tr1Entry1.setAccount(accountVmpVae); + tr1Entry1.setFinancialTransaction(transaction1); + tr1Entry1.setDescription("test desc"); + tr1Entry1.setVoucher("voucher"); + tr1Entry1 = financialTransactionService.createEntry(tr1Entry1); + + Date beginDate = df.parse("April 1, 2012"); + Date endDate = df.parse("May 31, 2012"); + ReportsDatas datas = reportService.generateAccountsReports(accountVmpVae, false, beginDate, endDate); + Assert.assertEquals(BigDecimal.valueOf(42), datas.getAmountCredit().stripTrailingZeros()); + Assert.assertEquals(BigDecimal.valueOf(42), datas.getAmountDebit().stripTrailingZeros()); + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/AccountServiceRuleFrTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/AccountServiceRuleFrTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/AccountServiceRuleFrTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,79 @@ +/* + * #%L + * $Id: AccountServiceRuleFrTest.java 3747 2014-02-17 08:41:35Z dcosse $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.chorem.lima.business.AccountServiceImplTest; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountImpl; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Add configuration to add specific test on French rules set. + * + * (redo all test defined in AccountServiceImplTest). + * + * Plus ajout de test specific à la locale FR. + * + * @author chatellier + * @version $Revision: 3747 $ + * + * Last update : $Date: 2014-02-17 09:41:35 +0100 (lun. 17 févr. 2014) $ + * By : $Author: dcosse $ + */ +public class AccountServiceRuleFrTest extends AccountServiceImplTest { + + @BeforeClass + public static void installFrenchRule() throws Exception { + LimaConfig.getInstance().setAccountingRule(FranceAccountingRules.class.getName()); + } + + /** + * Test une fois que la regles est correctement instanciée car + * elle peut être mise en cache dans {@link LimaConfig}. + */ + @Test + public void testRuleInstance() { + Assert.assertTrue(LimaConfig.getInstance().getAccountingRules() instanceof FranceAccountingRules); + } + + /** + * Création d'un compte dans le plan comptable. + * + * @throws LimaException + */ + @Ignore + @Test(expected=LimaException.class) + public void testCreateAccountWrongStart() throws LimaException { + // TODO DCossé 17/02/14 this test is no more valid as count with account number with letters are now accepted + // there is just a warning about it + Account myAccount = new AccountImpl(); + myAccount.setAccountNumber("10TEST"); + accountService.createAccount(myAccount); + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/EntryBookServiceRuleFrTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/EntryBookServiceRuleFrTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/EntryBookServiceRuleFrTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,60 @@ +/* + * #%L + * $Id: EntryBookServiceRuleFrTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.chorem.lima.business.EntryBookServiceImplTest; +import org.chorem.lima.business.LimaConfig; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Add configuration to add specific test on French rules set. + * + * (redo all test defined in EntryBookServiceImplTest). + * + * Plus ajout de test specific à la locale FR. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class EntryBookServiceRuleFrTest extends EntryBookServiceImplTest { + + @BeforeClass + public static void installFrenchRule() throws Exception { + LimaConfig.getInstance().setAccountingRule(FranceAccountingRules.class.getName()); + } + + /** + * Test une fois que la regles est correctement instanciée car + * elle peut être mise en cache dans {@link LimaConfig}. + */ + @Test + public void testRuleInstance() { + Assert.assertTrue(LimaConfig.getInstance().getAccountingRules() instanceof FranceAccountingRules); + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FinancialPeriodServiceRuleFrTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FinancialPeriodServiceRuleFrTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FinancialPeriodServiceRuleFrTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,60 @@ +/* + * #%L + * $Id: FinancialPeriodServiceRuleFrTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.chorem.lima.business.EntryBookServiceImplTest; +import org.chorem.lima.business.LimaConfig; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Add configuration to add specific test on French rules set. + * + * (redo all test defined in EntryBookServiceImplTest). + * + * Plus ajout de test specific à la locale FR. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class FinancialPeriodServiceRuleFrTest extends EntryBookServiceImplTest { + + @BeforeClass + public static void installFrenchRule() throws Exception { + LimaConfig.getInstance().setAccountingRule(FranceAccountingRules.class.getName()); + } + + /** + * Test une fois que la regles est correctement instanciée car + * elle peut être mise en cache dans {@link LimaConfig}. + */ + @Test + public void testRuleInstance() { + Assert.assertTrue(LimaConfig.getInstance().getAccountingRules() instanceof FranceAccountingRules); + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FinancialTransactionServiceRuleFrTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FinancialTransactionServiceRuleFrTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FinancialTransactionServiceRuleFrTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,60 @@ +/* + * #%L + * $Id: FinancialTransactionServiceRuleFrTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.chorem.lima.business.FinancialTransactionServiceImplTest; +import org.chorem.lima.business.LimaConfig; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Add configuration to add specific test on French rules set. + * + * (redo all test defined in FinancialTransactionServiceImplTest). + * + * Plus ajout de test specific à la locale FR. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class FinancialTransactionServiceRuleFrTest extends FinancialTransactionServiceImplTest { + + @BeforeClass + public static void installFrenchRule() throws Exception { + LimaConfig.getInstance().setAccountingRule(FranceAccountingRules.class.getName()); + } + + /** + * Test une fois que la regles est correctement instanciée car + * elle peut être mise en cache dans {@link LimaConfig}. + */ + @Test + public void testRuleInstance() { + Assert.assertTrue(LimaConfig.getInstance().getAccountingRules() instanceof FranceAccountingRules); + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FiscalPeriodServiceRuleFrTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FiscalPeriodServiceRuleFrTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/FiscalPeriodServiceRuleFrTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,60 @@ +/* + * #%L + * $Id: FiscalPeriodServiceRuleFrTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.chorem.lima.business.FiscalPeriodServiceImplTest; +import org.chorem.lima.business.LimaConfig; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Add configuration to add specific test on French rules set. + * + * (redo all test defined in FiscalPeriodServiceImplTest). + * + * Plus ajout de test specific à la locale FR. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class FiscalPeriodServiceRuleFrTest extends FiscalPeriodServiceImplTest { + + @BeforeClass + public static void installFrenchRule() throws Exception { + LimaConfig.getInstance().setAccountingRule(FranceAccountingRules.class.getName()); + } + + /** + * Test une fois que la regles est correctement instanciée car + * elle peut être mise en cache dans {@link LimaConfig}. + */ + @Test + public void testRuleInstance() { + Assert.assertTrue(LimaConfig.getInstance().getAccountingRules() instanceof FranceAccountingRules); + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ImportServiceRuleFrTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ImportServiceRuleFrTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ImportServiceRuleFrTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,60 @@ +/* + * #%L + * $Id: ImportServiceRuleFrTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.chorem.lima.business.ImportServiceImplTest; +import org.chorem.lima.business.LimaConfig; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Add configuration to add specific test on French rules set. + * + * (redo all test defined in ImportServiceImplTest). + * + * Plus ajout de test specific à la locale FR. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class ImportServiceRuleFrTest extends ImportServiceImplTest { + + @BeforeClass + public static void installFrenchRule() throws Exception { + LimaConfig.getInstance().setAccountingRule(FranceAccountingRules.class.getName()); + } + + /** + * Test une fois que la regles est correctement instanciée car + * elle peut être mise en cache dans {@link LimaConfig}. + */ + @Test + public void testRuleInstance() { + Assert.assertTrue(LimaConfig.getInstance().getAccountingRules() instanceof FranceAccountingRules); + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ReportServiceRuleFrTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ReportServiceRuleFrTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/ReportServiceRuleFrTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,64 @@ +/* + * #%L + * $Id: ReportServiceRuleFrTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.ReportServiceImplTest; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Add configuration to add specific test on French rules set. + * + * (redo all test defined in ReportServiceImplTest). + * + * Plus ajout de test specific à la locale FR. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + * + * FIXME echatellier 20120424 fix parent test first + */ +@Ignore +public class ReportServiceRuleFrTest extends ReportServiceImplTest { + + @BeforeClass + public static void installFrenchRule() throws Exception { + LimaConfig.getInstance().setAccountingRule(FranceAccountingRules.class.getName()); + } + + /** + * Test une fois que la regles est correctement instanciée car + * elle peut être mise en cache dans {@link LimaConfig}. + */ + @Test + public void testRuleInstance() { + Assert.assertTrue(LimaConfig.getInstance().getAccountingRules() instanceof FranceAccountingRules); + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/TestAccountingRules.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/TestAccountingRules.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/accountingrules/TestAccountingRules.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,123 @@ +/* + * #%L + * $Id: TestAccountingRules.java 3777 2014-04-14 07:29:08Z sbavencoff $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-business/src/test/java/org/chorem/lima... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.accountingrules; + +import org.apache.commons.lang3.time.DateUtils; +import org.chorem.lima.business.LimaBusinessException; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.entity.FinancialPeriod; +import org.chorem.lima.entity.FinancialPeriodImpl; +import org.chorem.lima.entity.FiscalPeriod; +import org.chorem.lima.entity.FiscalPeriodDAO; +import org.junit.Ignore; +import org.nuiton.topia.persistence.TopiaException; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * Cette classe existe car les tests tourne 2 fois: + * - default + * - fr rule set + * + * Par contre, dans default, il manque du code et cela ne peut pas fonctionner + * juste avec default. Donc le code manquant est ajouter dans ce jeux de regles + * de test et on lance les tests unitaires avec TestAccountingRules un fois + * et FranceAccountingRules une autre fois. + * + * @author chatellier + * @version $Revision: 3777 $ + * + * Last update : $Date: 2014-04-14 09:29:08 +0200 (lun. 14 avril 2014) $ + * By : $Author: sbavencoff $ + */ +@Ignore +public class TestAccountingRules extends DefaultAccountingRules { + + /** + * Copier/coller de la methode france. + * Le probleme ici est que le default n'en creer aucune. + */ + public List<FinancialPeriod> createFiscalPeriodRules(FiscalPeriod fiscalPeriod) throws LimaException { + super.createFiscalPeriodRules(fiscalPeriod); + List<FinancialPeriod> financialPeriods = new ArrayList<FinancialPeriod>(); + try { + FiscalPeriodDAO fiscalPeriodDAO = getDaoHelper().getFiscalPeriodDAO(); + + //Checks if is not the first fiscalperiod to create + if (fiscalPeriodDAO.count() != 0) { + + FiscalPeriod lastFiscalPeriod = fiscalPeriodDAO.getLastFiscalPeriod(); + + //check the new fiscal period adjoining the last + Date dateLastFiscalPeriod = lastFiscalPeriod.getEndDate(); + dateLastFiscalPeriod = DateUtils. + addDays(dateLastFiscalPeriod, 1); + dateLastFiscalPeriod = DateUtils.truncate(dateLastFiscalPeriod, Calendar.DATE); + Date dateFiscalPeriod = fiscalPeriod.getBeginDate(); + if (dateLastFiscalPeriod.compareTo(dateFiscalPeriod) != 0) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.newfiscalperiodadjoiningerror")); + } + + //We can create a new fiscal period meantime the last fiscal period was not locked + //But not the ante periodfiscal + int unblockedFiscalPeriod = + fiscalPeriodDAO.findAllByLocked(false).size(); + if (unblockedFiscalPeriod > 1) { + throw new LimaBusinessException(t("lima-business.franceaccountingrules.antefiscalperiodnotblocked")); + } + } + + // FinancialPeriods of 1 month are created + Date endDate = fiscalPeriod.getEndDate(); + Date loopDate = fiscalPeriod.getBeginDate(); + while (loopDate.before(endDate)) { + FinancialPeriod financialPeriod = new FinancialPeriodImpl(); + //important for fiscalperiod created from import, it can be locked, so financialperiods must be locked + financialPeriod.setLocked(fiscalPeriod.getLocked()); + financialPeriod.setBeginDate(loopDate); + loopDate = DateUtils.addMonths(loopDate, 1); + loopDate = DateUtils.truncate(loopDate, Calendar.MONTH); + loopDate = DateUtils.addMilliseconds(loopDate, -1); + if (loopDate.after(endDate)) { + financialPeriod.setEndDate(endDate); + } else { + financialPeriod.setEndDate(loopDate); + } + //create it + financialPeriods.add(financialPeriod); + //financialPeriodService.createFinancialPeriodWithTransaction(financialPeriod, transaction); + //loop incremente + loopDate = DateUtils.addMilliseconds(loopDate, 1); + } + } catch (TopiaException ex) { + throw new LimaException("Can't check rule", ex); + } + return financialPeriods; + } +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ClearService.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ClearService.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ClearService.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,48 @@ +/* + * #%L + * $Id: ClearService.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.ejb; + +import org.chorem.lima.business.LimaException; + +import javax.ejb.Remote; + +/** + * Clear database service. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +@Remote +public interface ClearService { + + /** + * Clear database. + * + * @throws LimaException + */ + void clearDatabase() throws LimaException; +} Added: trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ClearServiceImpl.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ClearServiceImpl.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/business/ejb/ClearServiceImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,59 @@ +/* + * #%L + * $Id: ClearServiceImpl.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.ejb; + +import org.chorem.lima.business.LimaException; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.persistence.TopiaException; + +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; + +/** + * Clear database service. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +@Stateless +@TransactionAttribute +public class ClearServiceImpl extends AbstractLimaService implements ClearService { + + /* + * @see org.chorem.lima.business.ejb.ClearService#clearDatabase() + */ + @Override + public void clearDatabase() throws LimaException { + try { + + TopiaContext transaction = getDaoHelper().getTopiaContext(); + transaction.createSchema(); + } catch (TopiaException ex) { + throw new LimaException("Can't clear database", ex); + } + } +} Deleted: trunk/lima-business/src/test/java/org/chorem/lima/entity/AccountDAOTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/entity/AccountDAOTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/entity/AccountDAOTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,69 +0,0 @@ -/* - * #%L - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 Codelutin, Chatellier Eric - * %% - * 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.entity; - -import org.chorem.lima.business.AbstractLimaTest; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; - -import java.util.List; - -/** - * Test for AccountDAO class. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class AccountDAOTest extends AbstractLimaTest { - - @Before - public void initTest() throws Exception { - initTestDatabase(); - } - - /** - * Test la recherche de compte par interval. - * @throws TopiaException - */ - @Test - public void testStringToListAccounts() throws TopiaException { - TopiaContext tx = getTestContext().beginTransaction(); - - AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(tx); - - List<Account> accounts = accountDAO.stringToListAccounts("50..511", false); - Assert.assertEquals(5, accounts.size()); - - accounts = accountDAO.stringToListAccounts("60..99", false); - Assert.assertEquals(0, accounts.size()); - - tx.closeContext(); - } -} Added: trunk/lima-business/src/test/java/org/chorem/lima/entity/AccountDAOTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/entity/AccountDAOTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/entity/AccountDAOTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,69 @@ +/* + * #%L + * $Id: AccountDAOTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.entity; + +import org.chorem.lima.business.AbstractLimaTest; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.persistence.TopiaException; + +import java.util.List; + +/** + * Test for AccountDAO class. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class AccountDAOTest extends AbstractLimaTest { + + @Before + public void initTest() throws Exception { + initTestDatabase(); + } + + /** + * Test la recherche de compte par interval. + * @throws TopiaException + */ + @Test + public void testStringToListAccounts() throws TopiaException { + TopiaContext tx = getTestContext().beginTransaction(); + + AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(tx); + + List<Account> accounts = accountDAO.stringToListAccounts("50..511", false); + Assert.assertEquals(5, accounts.size()); + + accounts = accountDAO.stringToListAccounts("60..99", false); + Assert.assertEquals(0, accounts.size()); + + tx.closeContext(); + } +} Deleted: trunk/lima-business/src/test/java/org/chorem/lima/entity/FinancialTransactionDAOTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/entity/FinancialTransactionDAOTest.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business/src/test/java/org/chorem/lima/entity/FinancialTransactionDAOTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,70 +0,0 @@ -/* - * #%L - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 Codelutin, Chatellier Eric - * %% - * 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.entity; - -import java.util.List; - -import org.chorem.lima.business.AbstractLimaTest; -import org.chorem.lima.business.LimaException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; - -/** - * Test for {@link FinancialTransactionDAO}. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class FinancialTransactionDAOTest extends AbstractLimaTest { - - @Before - public void initTest() throws Exception { - initTestDatabase(); - } - - /** - * Test la recherche des transactions non equilibrées. - * - * @throws TopiaException - * @throws LimaException - */ - @Test - public void testFindAllUnbalancedTransactions() throws TopiaException, LimaException { - - FinancialPeriod financialPeriod = financialPeriodService.getAllFinancialPeriods().get(0); - EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); - - TopiaContext tx = getTestContext().beginTransaction(); - FinancialTransactionDAO ftDAO = LimaCallaoDAOHelper.getFinancialTransactionDAO(tx); - List<FinancialTransaction> fTransactions = ftDAO.getAllUnbalancedTransaction(financialPeriod.getBeginDate(), - financialPeriod.getEndDate(), journalDesVentes); - Assert.assertNotNull(fTransactions); - } -} Added: trunk/lima-business/src/test/java/org/chorem/lima/entity/FinancialTransactionDAOTest.java =================================================================== --- trunk/lima-business/src/test/java/org/chorem/lima/entity/FinancialTransactionDAOTest.java (rev 0) +++ trunk/lima-business/src/test/java/org/chorem/lima/entity/FinancialTransactionDAOTest.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,69 @@ +/* + * #%L + * $Id: FinancialTransactionDAOTest.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-business/src/test/java/org/chorem/... $ + * %% + * Copyright (C) 2012 Codelutin, Chatellier Eric + * %% + * 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.entity; + +import java.util.List; + +import org.chorem.lima.business.AbstractLimaTest; +import org.chorem.lima.business.LimaException; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.persistence.TopiaException; +/** + * Test for {@link FinancialTransactionDAO}. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class FinancialTransactionDAOTest extends AbstractLimaTest { + + @Before + public void initTest() throws Exception { + initTestDatabase(); + } + + /** + * Test la recherche des transactions non equilibrées. + * + * @throws TopiaException + * @throws LimaException + */ + @Test + public void testFindAllUnbalancedTransactions() throws TopiaException, LimaException { + + FinancialPeriod financialPeriod = financialPeriodService.getAllFinancialPeriods().get(0); + EntryBook journalDesVentes = entryBookService.getEntryBookByCode("jdv"); + + TopiaContext tx = getTestContext().beginTransaction(); + FinancialTransactionDAO ftDAO = LimaCallaoDAOHelper.getFinancialTransactionDAO(tx); + List<FinancialTransaction> fTransactions = ftDAO.getAllUnbalancedTransaction(financialPeriod.getBeginDate(), + financialPeriod.getEndDate(), journalDesVentes); + Assert.assertNotNull(fTransactions); + } +} Modified: trunk/lima-business-api/src/main/java/org/chorem/lima/business/api/ReportService.java =================================================================== --- trunk/lima-business-api/src/main/java/org/chorem/lima/business/api/ReportService.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-business-api/src/main/java/org/chorem/lima/business/api/ReportService.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -31,7 +31,6 @@ import org.chorem.lima.entity.Account; import org.chorem.lima.entity.EntryBook; import org.chorem.lima.entity.FiscalPeriod; -import org.nuiton.topia.TopiaContext; import java.util.Date; import java.util.List; Modified: trunk/lima-callao/pom.xml =================================================================== --- trunk/lima-callao/pom.xml 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/pom.xml 2014-05-16 08:39:35 UTC (rev 3798) @@ -51,18 +51,35 @@ </dependencies> <build> + <resources> + <resource> + <directory>${project.basedir}/src/main/resources</directory> + </resource> + <resource> + <directory>${project.build.directory}/generated-sources/models</directory> + <includes> + <include>*.objectmodel</include> + <include>*.properties</include> + </includes> + </resource> + </resources> + <plugins> - <!-- Plugin Topia --> <plugin> <groupId>org.nuiton.eugene</groupId> <artifactId>eugene-maven-plugin</artifactId> <executions> <execution> + <id>generate-entities</id> <phase>generate-sources</phase> <configuration> <inputs>zargo</inputs> - <templates>org.nuiton.topia.generator.TopiaMetaTransformer, - org.nuiton.topia.generator.EntityTransformer, + <!-- Corresponding to extracted package from zargo file --> + <fullPackagePath>org.chorem.lima</fullPackagePath> + <defaultPackage>org.chorem.lima.entity</defaultPackage> + <templates> + org.nuiton.topia.templates.TopiaMetaTransformer, + org.nuiton.topia.templates.EntityTransformer, org.nuiton.eugene.java.JavaBeanTransformer </templates> <excludeTemplates> @@ -76,34 +93,13 @@ org.nuiton.topia.generator.EntityInterfaceTransformer </excludeTemplate> </excludeTemplates> - <defaultPackage>org.chorem.lima.entity</defaultPackage> - <fullPackagePath>org.chorem.lima</fullPackagePath> </configuration> <goals> <goal>generate</goal> </goals> </execution> </executions> - <dependencies> - <dependency> - <groupId>org.nuiton.topia</groupId> - <artifactId>topia-persistence</artifactId> - <version>${topiaVersion}</version> - </dependency> - </dependencies> </plugin> - <plugin> - <groupId>org.nuiton.i18n</groupId> - <artifactId>i18n-maven-plugin</artifactId> - <executions> - <execution> - <goals> - <goal>parserJava</goal> - <goal>gen</goal> - </goals> - </execution> - </executions> - </plugin> </plugins> </build> Added: trunk/lima-callao/src/main/java/org/chorem/lima/DefaultServiceContext.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/DefaultServiceContext.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/DefaultServiceContext.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,65 @@ +package org.chorem.lima; + +/* + * #%L + * Lima :: callao + * %% + * Copyright (C) 2008 - 2014 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% + */ + +import com.google.common.base.Supplier; +import org.nuiton.topia.persistence.internal.AbstractTopiaPersistenceContext; + +/** + * Created by davidcosse on 15/05/14. + */ +public class DefaultServiceContext implements ServiceContext { + + protected AbstractTopiaPersistenceContext persistenceContext; + protected Supplier<AbstractTopiaPersistenceContext> transactionSupplier; + + @Override + public void close() { + // try to close non closed persistence context (false to not reopen it) + AbstractTopiaPersistenceContext context = getPersistenceContext(false); + if (context != null) { + context.closeContext(); + } + } + + @Override + public AbstractTopiaPersistenceContext getPersistenceContext() { + AbstractTopiaPersistenceContext result = getTransaction0(true); + return result; + } + + @Override + public AbstractTopiaPersistenceContext getPersistenceContext(boolean create) { + AbstractTopiaPersistenceContext result = getTransaction0(create); + return result; + } + + @Override + public AbstractTopiaPersistenceContext getTransaction0(boolean create) { + if (persistenceContext == null && create) { + persistenceContext = transactionSupplier.get(); + + } + return persistenceContext; + } +} Added: trunk/lima-callao/src/main/java/org/chorem/lima/ServiceContext.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/ServiceContext.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/ServiceContext.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,38 @@ +package org.chorem.lima; + +/* + * #%L + * Lima :: callao + * %% + * Copyright (C) 2008 - 2014 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% + */ + +import org.nuiton.topia.persistence.internal.AbstractTopiaPersistenceContext; + +/** + * Created by davidcosse on 15/05/14. + */ +public interface ServiceContext { + void close(); + + AbstractTopiaPersistenceContext getPersistenceContext(); + + AbstractTopiaPersistenceContext getPersistenceContext(boolean create); + + AbstractTopiaPersistenceContext getTransaction0(boolean create); +} Added: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractAccountTopiaDao.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractAccountTopiaDao.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractAccountTopiaDao.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,192 @@ +/* + * #%L + * Lima callao + * + * $Id: AccountDAOImpl.java 3613 2012-08-20 11:38:22Z mallon $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-callao/src/main/java/org/chorem/li... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.entity; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; + +import com.google.common.collect.Maps; +import org.apache.commons.lang3.StringUtils; +import org.nuiton.topia.persistence.TopiaException; + +public class AbstractAccountTopiaDao<E extends Account> extends GeneratedAccountTopiaDao<E> { + + /** + * Retourne tous les comptes qui n'ont pas eux meme de sous compte. + * + * @return leaf accounts + * @throws TopiaException + */ + public List<Account> findAllLeafAccounts() throws TopiaException { + // FIXME echatellier 20120413 la requete ne fonctionne pas + // et retourne vide + /*String query = "FROM " + Account.class.getName() + " a WHERE a NOT IN (" + + "FROM " + Account.class.getName() + " b where b.accountNumber like concat(a.accountNumber,'%'))"; + List<Account> accounts = find(query);*/ + + // code temporaire non performant en attandant: + List<Account> allAccounts = (List<Account>) findAll(); + Iterator<Account> itAccount = allAccounts.iterator(); + while (itAccount.hasNext()) { + Account acc = itAccount.next(); + Iterator<Account> itAccount2 = allAccounts.iterator(); + while (itAccount2.hasNext()) { + Account acc2 = itAccount2.next(); + if (!acc2.getAccountNumber().equals(acc.getAccountNumber()) && + acc2.getAccountNumber().startsWith(acc.getAccountNumber())) { + itAccount.remove(); + break; + } + } + } + return allAccounts; + } + + /** + * TODO pas compris l'interet de la methode, si on veut un compte feuille + * par son numero, cela revient a avoir un compte par son numero. + */ + @Deprecated + public Account findLeafAccountByNumber(String number) throws TopiaException { + return forAccountNumberEquals(number).findUniqueOrNull(); + } + + /** + * Find account contained into account number interval. + * + * @param accountNumberLow min account number + * @param accountNumberHigh max account number + * @return account list + * @throws TopiaException + */ + protected List<Account> findIntervalAccountByNumber(String accountNumberLow, + String accountNumberHigh) throws TopiaException { + String query = "FROM " + Account.class.getName() + " WHERE :accountNumberLow <= accountNumber AND accountNumber <= :accountNumberHigh"; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("accountNumberLow", accountNumberLow); + args.put("accountNumberHigh", accountNumberHigh); + return findAll(query, args); + } + + /** + * Retourne tous les comptes dont le numero commence par celui specifié. + * + * @param account parent account + * @return + * @throws TopiaException + */ + public List<Account> findAllSubAccounts(Account account) throws TopiaException { + + String query = "FROM " + Account.class.getName() + " a WHERE a.accountNumber LIKE concat(:accountNumber, '_%')"; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("accountNumber", account.getAccountNumber()); + List<Account> accounts = findAll(query, args); + + return accounts; + } + + /** + * @deprecated since 0.6, business method, need to be moved out of dao + */ + @Deprecated + public List<Account> stringToListAccounts(String selectedAccounts, + Boolean leafAccountsMode) throws TopiaException { + Set<Account> accounts = new HashSet<Account>(); + if (selectedAccounts != null) { + //Remove Spaces + String result = StringUtils.deleteWhitespace(selectedAccounts); + + Boolean first = true; + StringTokenizer stStar = new StringTokenizer(result, "-"); + while (stStar.hasMoreTokens()) { + String subString = stStar.nextToken(); + + //Split comma + StringTokenizer stComma = new StringTokenizer(subString, ","); + while (stComma.hasMoreTokens()) { + String s = stComma.nextToken(); + //if intervall account + if (s.contains("..") && !s.endsWith("..")) { + //Split .. + String stringDoubleDot[] = s.split("\\.\\."); + + List<Account> resultIntervall = + findIntervalAccountByNumber(stringDoubleDot[0], stringDoubleDot[1]); + + //if first add accounts, else remove + if (first) { + accounts.addAll(resultIntervall); + } else { + accounts.removeAll(resultIntervall); + } + } + //else one account + else { + Account account; + if (leafAccountsMode) { + account = findLeafAccountByNumber(s); + } else { + account = findByAccountNumber(s); + } + //if exist + if (account != null) { + //if first + if (first) { + accounts.add(account); + } else { + accounts.remove(account); + } + } + //search all account start with accountnumber + else { + String query = "FROM " + Account.class.getName() + " a WHERE a NOT IN (" + + "FROM " + Account.class.getName() + " b where b.accountNumber like a.accountNumber+'%')" + + " AND a.accountNumber LIKE :s"; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("s",s); + List<Account> accountsResult = findAll(query, args); + if (accountsResult != null) { + //if first + if (first) { + accounts.addAll(accountsResult); + } else { + accounts.removeAll(accountsResult); + } + } + } + } + } + first = false; + } + } + return new ArrayList(accounts); + } +} Added: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractClosedPeriodicEntryBookTopiaDao.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractClosedPeriodicEntryBookTopiaDao.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractClosedPeriodicEntryBookTopiaDao.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,225 @@ +/* + * #%L + * Lima callao + * + * $Id: ClosedPeriodicEntryBookDAOImpl.java 3476 2012-06-26 15:48:13Z echatellier $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-callao/src/main/java/org/chorem/lima/e... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.entity; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +import com.google.common.collect.Maps; +import org.hibernate.HibernateException; +import org.nuiton.topia.persistence.TopiaException; + +public class AbstractClosedPeriodicEntryBookTopiaDao<E extends ClosedPeriodicEntryBook> extends GeneratedClosedPeriodicEntryBookTopiaDao<E> { + + /** + * FIXME echatellier, remove this method when implemented in topia + * just overriden to use merge() instead of saveOrUpdate() + */ + public ClosedPeriodicEntryBook merge(ClosedPeriodicEntryBook e) throws TopiaException { + try { +// e = (ClosedPeriodicEntryBook)getContext().getHibernate().merge(e); +// getContext().getFiresSupport().warnOnUpdateEntity(e); +// return e; + // TODO DCossé 15/05/14 don't know how to get hibernate + return null; + } catch (HibernateException ex) { + throw new TopiaException(ex); + } + } + + /** + * Find all ClosedPeriodicEntryBook with common EntryBook. + * + * @param entryBook entry book property + * @return ClosedPeriodicEntryBook list + * @throws TopiaException + */ + public List<ClosedPeriodicEntryBook> findAllByEntryBook(EntryBook entryBook) throws TopiaException { + return findAllByEntryBook(entryBook); + } + + /** + * Return ClosedPeriodicEntryBook by EntryBook and FinancialPeriod. + * + * @param entryBook + * @param financialPeriod + * @return ClosedPeriodicEntryBook + * @throws TopiaException + */ + public ClosedPeriodicEntryBook findByEntryBookAndFinancialPeriod( + EntryBook entryBook, FinancialPeriod financialPeriod) + throws TopiaException { + + List<ClosedPeriodicEntryBook> closedPeriodicEntryBooks; + String query = "FROM " + ClosedPeriodicEntryBook.class.getName(); + + Map<String, Object> args = Maps.newLinkedHashMap(); + + if (entryBook != null) { + args.put("entryBook", entryBook); + query += " WHERE entryBook = :entryBook"; + if (financialPeriod != null) { + args.put("financialPeriod", financialPeriod); + query += " AND financialPeriod = :financialPeriod"; + //find(query, 0, 0, "entryBook", entryBook, "financialPeriod", financialPeriod); + closedPeriodicEntryBooks = findAll(query, args); + } else { + //find(query, 0, 0, "entryBook", entryBook); + closedPeriodicEntryBooks = findAll(query, args); + } + } else { + if (financialPeriod != null) { + args.put("financialPeriod", financialPeriod); + query += " WHERE financialPeriod = :financialPeriod"; + } + + //find(query, 0, 0, "financialPeriod", financialPeriod); + closedPeriodicEntryBooks = findAll(query, args); + } + + // get only first one + ClosedPeriodicEntryBook result = null; + if (!closedPeriodicEntryBooks.isEmpty()) { + result = closedPeriodicEntryBooks.get(0); + } + return result; + } + + /** + * Retourne toutes les ClosedPeriodicEntryBook par interval de date + * sur les periodes sur lequelles elles portent ordonnée par journal. + * + * @param beginDate begin date + * @param endDate end date + * @return all ClosedPeriodicEntryBook between begin and end + * @throws TopiaException + */ + public List<ClosedPeriodicEntryBook> findAllByDates(Date beginDate, + Date endDate) throws TopiaException { + + String query = "FROM " + ClosedPeriodicEntryBook.class.getName() + + " WHERE :beginDate <= financialPeriod.beginDate " + + " AND financialPeriod.beginDate <= :endDate" + + " ORDER BY entryBook.code"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + + return findAll(query, args); + } + + /** + * Retourne toutes les ClosedPeriodicEntryBook par interval de date + * sur les periodes sur lequelles elles portent pour un journal. + * + * @param entryBook entry book + * @param beginDate begin date + * @param endDate end date + * @return all ClosedPeriodicEntryBook between begin and end + * @throws TopiaException + */ + public List<ClosedPeriodicEntryBook> findAllByEntryBookAndDates(EntryBook entryBook, + Date beginDate, Date endDate) throws TopiaException { + + String query = "FROM " + ClosedPeriodicEntryBook.class.getName() + + " WHERE :beginDate <= financialPeriod.beginDate " + + " AND financialPeriod.beginDate <= :endDate" + + " AND entryBook = :entryBook"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + args.put("entryBook", entryBook); + return findAll(query, args); + } + + /** + * Retourne toutes les ClosedPeriodicEntryBook par interval de date + * sur les periodes sur lequelles elles portent pour un journal. + * + * @param entryBook entry book + * @param beginDate begin date + * @param endDate end date + * @return all ClosedPeriodicEntryBook between begin and end + * @throws TopiaException + */ + public List<ClosedPeriodicEntryBook> findAllByEntryBookAndDatesLocked(EntryBook entryBook, + Date beginDate, Date endDate) throws TopiaException { + + String query = "FROM " + ClosedPeriodicEntryBook.class.getName() + + " WHERE :beginDate <= financialPeriod.beginDate " + + " AND financialPeriod.beginDate <= :endDate" + + " AND entryBook = :entryBook" + + " AND locked = true"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + args.put("entryBook", entryBook); + return findAll(query, args); + } + + /** + * Retourne les ClosedPeriodicEntryBook de toutes les exercices encore ouverts. + * + * @return les ClosedPeriodicEntryBook + * @throws TopiaException + */ + public List<ClosedPeriodicEntryBook> findAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod() throws TopiaException { + String query = "SELECT C FROM " + ClosedPeriodicEntryBook.class.getName() + " C" + + ", " + FiscalPeriod.class.getName() + " F" + + " WHERE C.financialPeriod IN ELEMENTS (F.financialPeriod)" + + " AND F.locked = false" + + " ORDER BY C.financialPeriod.beginDate"; + + List<ClosedPeriodicEntryBook> result = findAll(query); + return result; + } + + /** + * Retourne les ClosedPeriodicEntryBook d'un exercice ouvert. + * + * @return les ClosedPeriodicEntryBook + * @throws TopiaException + */ + public List<ClosedPeriodicEntryBook> findAllClosedPeriodicEntryBooksFromFiscalPeriod(FiscalPeriod fiscalPeriod) throws TopiaException { + String query = "SELECT C FROM " + ClosedPeriodicEntryBook.class.getName() + " C" + + ", " + FiscalPeriod.class.getName() + " F" + + " WHERE C.financialPeriod IN ELEMENTS (F.financialPeriod)" + + " AND F = :fiscalPeriod" + + " ORDER BY C.financialPeriod.beginDate"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("fiscalPeriod", fiscalPeriod); + + List<ClosedPeriodicEntryBook> result = findAll(query, args); + + return result; + } + +} Added: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractEntryTopiaDao.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractEntryTopiaDao.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractEntryTopiaDao.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,323 @@ +/* + * #%L + * Lima callao + * * + * $Id: EntryDAOImpl.java 3783 2014-05-06 16:47:18Z dcosse $ + * $HeadURL: http://svn.chorem.org/lima/trunk/lima-callao/src/main/java/org/chorem/lima/e... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.entity; + +import com.google.common.collect.Maps; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.beans.LetteringFilter; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +public class AbstractEntryTopiaDao<E extends Entry> extends GeneratedEntryTopiaDao<E> { + + private static final Log log = LogFactory.getLog(AbstractEntryTopiaDao.class); + + /** + * Requete generique qui recupere les entrees equilibrées portant entre + * deux dates. + * + * @param beginDate begin date + * @param endDate end date + */ + protected String getEquilibredTransactionQuery(Date beginDate, Date endDate) { + String query = "FROM " + Entry.class.getName() + " E" + + // equlibrée (somme des débit = somme des crédit) + " WHERE (select sum(E2.amount) from " + Entry.class.getName() + " E2 where E2.debit = false and E2.financialTransaction = E.financialTransaction) = " + + "(select sum(E2.amount) from " + Entry.class.getName() + " E2 where E2.debit = true and E2.financialTransaction = E.financialTransaction)" + + // entre les 2 dates + " AND :beginDate <= E.financialTransaction.transactionDate" + + " AND E.financialTransaction.transactionDate <= :endDate"; + return query; + } + + /** + * Query for find entries for accountsreports and balancereports + * Just exact and balanced transaction are calculated. + * + * @param account account + * @param beginDate begin date + * @param endDate end date + * @return entries + */ + public List<Entry> findAllEntryOfBalancedTransaction(Account account, + Date beginDate, Date endDate) { + + String query = getEquilibredTransactionQuery(beginDate, endDate) + + // concerne le compte + " AND E.account = :account"; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + args.put("account", account); + + List<Entry> entries = findAll(query, args); + + return entries; + } + + /** + * Retourne la somme des entrées des transaction equilibrées entre + * deux dates pour un compte donné. + * + * @param account account + * @param beginDate bebin date + * @param endDate end date + * @return list boolean,int (une ligne pour le debit true, une ligne pour le credit) + */ + public List<Object[]> getDebitCreditOfBalancedTransaction(Account account, + Date beginDate, Date endDate) { + String query = "SELECT E.debit, sum(E.amount) " + + getEquilibredTransactionQuery(beginDate, endDate) + + // concerne le compte + " AND E.account = :account" + + " GROUP BY E.debit"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + args.put("account", account); + + List<Object[]> result = findAll(query, args); + return result; + } + + /** + * Retourne les entrees des transaction equlibrées entre deux dates pour + * un journal. + * + * @param entryBook entry book + * @param beginDate begin date + * @param endDate end date + */ + public List<Entry> findAllEntryOfBalancedTransaction(EntryBook entryBook, Date beginDate, + Date endDate) { + String query = getEquilibredTransactionQuery(beginDate, endDate) + + // concerne le journal + " AND E.financialTransaction.entryBook = :entryBook" + + // fix order + " ORDER BY E.financialTransaction.transactionDate, E.financialTransaction.topiaId"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + args.put("entryBook", entryBook); + + List<Entry> entries = findAll(query, args); + return entries; + } + + public List<String> findLetters() { + String query = "Select distinct E.lettering FROM " + Entry.class.getName() + " E" + + " where E.lettering <> null" + + " order by E.lettering desc"; + + List<String> result = new ArrayList<String>(this.<String>findAll(query)); + + if (log.isDebugEnabled()) { + log.debug("Size of result : " + result.size()); + } + + return result; + } + + /** + * Retourne la somme des entrées des transaction equilibrées entre + * deux dates pour un journal donné. + * + * @param entryBook entry book + * @param beginDate bebin date + * @param endDate end date + * @return list boolean,int (une ligne pour le debit true, une ligne pour le credit) + */ + public List<Object[]> getDebitCreditOfBalancedTransaction(EntryBook entryBook, + Date beginDate, Date endDate) { + String query = "SELECT E.debit, sum(E.amount) " + + getEquilibredTransactionQuery(beginDate, endDate) + + // concerne le journal + " AND E.financialTransaction.entryBook = :entryBook" + + " GROUP BY E.debit"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + args.put("entryBook", entryBook); + + List<Object[]> result = findAll(query, args); + return result; + } + + /** + * Retourne les entrees des transaction entre deux dates pour + * un journal. + * + * @param entryBook entry book + * @param beginDate begin date + * @param endDate end date + */ + public List<Entry> findAllEntryByDateForEntryBook(EntryBook entryBook, Date beginDate, + Date endDate) { + String query = "FROM " + Entry.class.getName() + " E" + + // entre les 2 dates + " WHERE :beginDate <= E.financialTransaction.transactionDate" + + " AND E.financialTransaction.transactionDate <= :endDate" + + // concerne le journal + " AND E.financialTransaction.entryBook = :entryBook"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + args.put("entryBook", entryBook); + + List<Entry> entries = findAll(query, args); + return entries; + } + + /** + * Retourne toutes les entrées d'une transaction + * pour un compte et la présence d'un lettrage ou (xor) non + * @param filter filtre sur les entrees, selon le compte, les dates de debut et de fin, et le lettrage + * */ + public List<Entry> findAllEntryByFilter(LetteringFilter filter) { + + List<Entry> entries; + Account account = filter.getAccount(); + + if (account != null && account.getTopiaId() == null) { + // case user want to see all accounts + entries = getAllEntryByLetteringAndDateForEntryBook(filter); + } else { + entries = getAllEntryByAccountLetteringAndDateForEntryBook(filter); + } + return entries; + } + + public List<Entry> getAllEntryByAccountLetteringAndDateForEntryBook(LetteringFilter filter) { + List<Entry> entries; + + String query = "Select E from " + Entry.class.getName() + " E " + + " where E.account.accountNumber like :account "; + + + if (!filter.getDisplayLettered() && filter.getDisplayUnlettred()){ + query += " and (E.lettering is null or E.lettering = '') "; + } else if (filter.getDisplayLettered() && !filter.getDisplayUnlettred()){ + query += " and (E.lettering is not null or E.lettering !='') "; + } + + query += " and E.financialTransaction.transactionDate between :beginDate and :endDate " + + " order by E.financialTransaction.transactionDate, E.financialTransaction." + FinancialTransaction.PROPERTY_TOPIA_CREATE_DATE; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", filter.getDateStart()); + args.put("endDate", filter.getDateEnd()); + args.put("account", filter.getAccount().getAccountNumber() + "%"); + entries = findAll(query, args); + + return entries; + } + + public List<Entry> getAllEntryByLetteringAndDateForEntryBook(LetteringFilter filter) { + List<Entry> entries; + + String query = "Select E from " + Entry.class.getName() + " E "; + + query += " WHERE E.financialTransaction.transactionDate BETWEEN :beginDate and :endDate "; + + if (!filter.getDisplayLettered() && filter.getDisplayUnlettred()){ + query += " and (E.lettering is null or E.lettering = '') "; + } else if (filter.getDisplayLettered() && !filter.getDisplayUnlettred()){ + query += " and (E.lettering is not null or E.lettering !='') "; + } + + query += " order by E.financialTransaction.transactionDate, E.financialTransaction." + FinancialTransaction.PROPERTY_TOPIA_CREATE_DATE; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", filter.getDateStart()); + args.put("endDate", filter.getDateEnd()); + + entries = findAll(query, args); + + return entries; + } + + + /** + * Retourne la dernière entrée d'une transaction + * @param financialTransaction transaction sur laquelle la derniere entree est selectionnee + * */ + public Entry getLastEntry(FinancialTransaction financialTransaction) { + List<Entry> entries; + Entry lastEntry = null; + String query = "Select E from " + Entry.class.getName() + " E" + + " where E.financialTransaction.transactionDate = :financialTransactionDate " + + " and E.financialTransaction = :financialTransaction" + + " order by E.topiaCreateDate desc"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("financialTransactionDate", financialTransaction.getTransactionDate()); + args.put("financialTransaction", financialTransaction); + + entries = findAll(query, args); + if (entries.size() > 0) { + lastEntry = entries.get(0); + } + + return lastEntry; + } + + /** + * Retourne la somme des entrées des transaction entre + * deux dates pour un journal donné. + * + * @param entryBook entry book + * @param beginDate bebin date + * @param endDate end date + * @return list boolean,int (une ligne pour le debit true, une ligne pour le credit) + */ + public List<Object[]> getDebitCreditOfTransaction(EntryBook entryBook, + Date beginDate, Date endDate) { + String query = "SELECT E.debit, sum(E.amount) " + + "FROM " + Entry.class.getName() + " E" + + // entre les 2 dates + " WHERE :beginDate <= E.financialTransaction.transactionDate" + + " AND E.financialTransaction.transactionDate <= :endDate" + + // concerne le journal + " AND E.financialTransaction.entryBook = :entryBook" + + " GROUP BY E.debit"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + args.put("entryBook", entryBook); + + List<Object[]> result = findAll(query, args); + return result; + } +} Added: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialPeriodTopiaDao.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialPeriodTopiaDao.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialPeriodTopiaDao.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,112 @@ +/* + * #%L + * Lima callao + * + * $Id: FinancialPeriodDAOImpl.java 3476 2012-06-26 15:48:13Z echatellier $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-callao/src/main/java/org/chorem/li... $ + * %% + * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric + * %% + * 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.entity; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +import com.google.common.collect.Maps; +import org.nuiton.topia.persistence.TopiaException; + +public class AbstractFinancialPeriodTopiaDao<E extends FinancialPeriod> extends GeneratedFinancialPeriodTopiaDao<E> { + + /** + * Return FinancialPeriod by Date. + * Date is include between financialperiod begin and end date. + * + * @param date period middle date + * @return FinancialPeriod for {@code date} + * @throws TopiaException + */ + public FinancialPeriod findByDate(Date date) throws TopiaException { + + String query = "FROM " + FinancialPeriod.class.getName() + + " WHERE beginDate <= :date" + + " AND :date <= endDate"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("date", date); + // add unique result here + FinancialPeriod financialPeriod = (FinancialPeriod)findUnique(query, args); + return financialPeriod; + } + + /** + * Return all FinancialPeriod with begin date between two given dates. + * + * @param beginDate period begin date + * @param endDate period end date + * @return FinancialPeriod for {@code date} + * @throws TopiaException + */ + public List<FinancialPeriod> findByDates(Date beginDate, Date endDate) throws TopiaException { + + String query = "FROM " + FinancialPeriod.class.getName() + + " WHERE :beginDate <= beginDate" + + " AND beginDate <= :endDate" + + " ORDER by beginDate"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate", beginDate); + args.put("endDate", endDate); + // add unique result here + List<FinancialPeriod> financialPeriod = findAll(query, args); + return financialPeriod; + } + + /** + * Retourne toutes les periodes ordonnées par date de debut de periode. + * + * @return all period ordered + * @throws TopiaException + */ + public List<FinancialPeriod> findAllOrderByBeginDate() throws TopiaException { + String query = "FROM " + FinancialPeriod.class.getName() + + " ORDER BY beginDate"; + + // add unique result here + List<FinancialPeriod> financialPeriod = findAll(query); + return financialPeriod; + } + + /** + * Retourne toutes les periodes ordonnées par date de debut de periode. + * + * @return all period ordered + * @throws TopiaException + */ + public List<FinancialPeriod> findAllUnlockedOrderByBeginDate() throws TopiaException { + String query = "FROM " + FinancialPeriod.class.getName() + + " WHERE locked = false" + + " ORDER BY beginDate"; + + // add unique result here + List<FinancialPeriod> financialPeriod = findAll(query); + return financialPeriod; + } + +} Added: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialStatementTopiaDao.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialStatementTopiaDao.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialStatementTopiaDao.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,79 @@ +/* + * #%L + * Lima callao + * + * $Id: FinancialStatementDAOImpl.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-callao/src/main/java/org/chorem/li... $ + * %% + * Copyright (C) 2012 CodeLutin, Chatellier Eric + * %% + * 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.entity; + +import com.google.common.collect.Maps; + +import java.util.List; +import java.util.Map; + + +/** + * Ajout de requetes specifiques aux {@link FinancialStatement} sur le DAO. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class AbstractFinancialStatementTopiaDao<E extends FinancialStatement> extends GeneratedFinancialStatementTopiaDao<E> { + + /** + * Find all {@code FinancialStatement} ordered by topia create date. + */ + public List<FinancialStatement> findAllOrderedByCreateDate() { + String query = "FROM " + FinancialStatement.class.getName() + + " ORDER BY " + FinancialStatement.PROPERTY_TOPIA_CREATE_DATE; + List<FinancialStatement> result = findAll(query); + return result; + } + + /** + * Find all {@code FinancialStatement} ordered by topia create date. + */ + public List<FinancialStatement> findChildrenFinancialStatement(FinancialStatement financialStatement) { + String query = "FROM " + FinancialStatement.class.getName(); + + if (financialStatement == null) { + query += " WHERE masterFinancialStatement = null"; + } else { + query += " WHERE masterFinancialStatement = :masterFinancialStatement"; + } + query += " ORDER BY " + FinancialStatement.TOPIA_CREATE_DATE; + + List<FinancialStatement> result; + if (financialStatement == null) { + result = findAll(query); + } else { + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("masterFinancialStatement", financialStatement); + result = findAll(query, args); + } + return result; + } + +} //FinancialStatementDAO Added: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialTransactionTopiaDao.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialTransactionTopiaDao.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFinancialTransactionTopiaDao.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,329 @@ +/* + * #%L + * Lima callao + * + * $Id: FinancialTransactionDAOImpl.java 3688 2013-06-27 13:12:22Z Bavencoff $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-callao/src/main/java/org/chorem/li... $ + * %% + * Copyright (C) 2012 CodeLutin, Chatellier Eric + * %% + * 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.entity; + +import com.google.common.collect.Maps; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.Filter.Filter; +import org.hibernate.HibernateException; +import org.nuiton.topia.persistence.TopiaException; +import org.nuiton.topia.persistence.event.TopiaContextAdapter; + +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Ajout de requetes specifiques aux financial transaction sur le DAO. + * + * @author chatellier + * @version $Revision: 3688 $ + * + * Last update : $Date: 2013-06-27 15:12:22 +0200 (jeu. 27 juin 2013) $ + * By : $Author: Bavencoff $ + */ +public class AbstractFinancialTransactionTopiaDao<E extends FinancialTransaction> extends GeneratedFinancialTransactionTopiaDao<E> { + + private static final Log log = LogFactory.getLog(AbstractFinancialTransactionTopiaDao.class); + + /** + * FIXME echatellier, remove this method when implemented in topia + * just overriden to use merge() instead of saveOrUpdate() + */ + public FinancialTransaction merge(FinancialTransaction e) { +// try { +// e = (FinancialTransaction) getContext().getHibernate().merge(e); +// getContext().getFiresSupport().warnOnUpdateEntity(e); +// return e; +// } catch (HibernateException ex) { +// throw new TopiaException(ex); +// } + // TODO DCossé 15/05/14 find a way to get hibernate + return null; + } + + /** + * Return how many transaction are found with specified entryBook. + * + * @param entryBook entry book + * @return transaction referencing entry book + */ + public long getCountByEntryBook(EntryBook entryBook) { + String query = "SELECT count(*) FROM " + FinancialTransaction.class.getName() + " t WHERE t.entryBook = :entryBook"; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("entryBook", entryBook); + Number count = (Number)findAll(query, args).get(0); + return count.longValue(); + } + + /** + * Find all transactions between two dates. + * + * @param beginDate begin date + * @param endDate end date + * @return unbalanced transactions + */ + public List<FinancialTransaction> findAllByDates(Date beginDate, Date endDate) { + String query = "FROM " + FinancialTransaction.class.getName() + " T"+ + " WHERE :beginDate <= T.transactionDate" + + " AND T.transactionDate <= :endDate" + + " ORDER BY T.transactionDate, T." + FinancialTransaction.PROPERTY_TOPIA_CREATE_DATE; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate",beginDate); + args.put("endDate", endDate); + List<FinancialTransaction> result = findAll(query,args); + return result; + } + + /** + * Find all transactions between two dates in an entry book. + * + * @param beginDate begin date + * @param endDate end date + * @param entryBook entry book + * @return unbalanced transactions + */ + public List<FinancialTransaction> findAllByDates(Date beginDate, Date endDate, EntryBook entryBook) { + String query = "FROM " + FinancialTransaction.class.getName() + " T"+ + " WHERE :beginDate <= T.transactionDate" + + " AND T.transactionDate <= :endDate" + + " AND T.entryBook = :entryBook" + + " ORDER BY T.transactionDate, T." + FinancialTransaction.PROPERTY_TOPIA_CREATE_DATE; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate",beginDate); + args.put("endDate", endDate); + args.put("entryBook", entryBook); + List<FinancialTransaction> result = findAll(query, args); + return result; + } + + /** + * Find all unbalanced transactions. + * + * @param beginDate beginDate + * @param endDate endDate + * @param entryBook entry book (can be null) + * @return unbalanced transactions + */ + public List<FinancialTransaction> getAllUnbalancedTransaction(Date beginDate, Date endDate, + EntryBook entryBook) { + String query = "FROM " + FinancialTransaction.class.getName() + " T"+ + " WHERE (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = true AND financialTransaction = T) != " + + " (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = false AND financialTransaction = T)" + + " AND :beginDate <= T.transactionDate" + + " AND T.transactionDate <= :endDate"; + List<FinancialTransaction> result; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate",beginDate); + args.put("endDate", endDate); + if (entryBook != null) { + args.put("entryBook", entryBook); + query += " AND T.entryBook = :entryBook"; + result = findAll(query, args); + } else { + result = findAll(query, args); + } + + return result; + } + + /** + * Find all unbalanced transactions. + * + * @param beginDate beginDate + * @param endDate endDate + * @param entryBook entry book (can be null) + * @return unbalanced transactions + */ + public List<FinancialTransaction> getAllBalancedTransaction(Date beginDate, Date endDate, + EntryBook entryBook) { + String query = "FROM " + FinancialTransaction.class.getName() + " T"+ + " WHERE (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = true AND financialTransaction = T) = " + + " (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = false AND financialTransaction = T)" + + " AND :beginDate <= T.transactionDate" + + " AND T.transactionDate <= :endDate"; + List<FinancialTransaction> result; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate",beginDate); + args.put("endDate", endDate); + + if (entryBook != null) { + args.put("entryBook", entryBook); + query += " AND T.entryBook = :entryBook"; + result = findAll(query, args); + } else { + result = findAll(query, args); + } + + return result; + } + + /** + * Find all unbalanced transactions. + * + * @param beginDate beginDate + * @param endDate endDate + * @param entryBook entry book (can be null) + * @return unbalanced transactions + */ + public List<FinancialTransaction> getAllIncorrectTransaction(Date beginDate, Date endDate, + EntryBook entryBook) { + String query = "SELECT distinct T FROM " + FinancialTransaction.class.getName() + " T"+ + " LEFT JOIN T.entry AS E" + + " WHERE ((SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = true AND financialTransaction = T) != " + + " (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = false AND financialTransaction = T)" + + " OR (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = true AND financialTransaction = T) IS NULL" + + " OR (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = false AND financialTransaction = T) IS NULL" + + " OR E.account = null" + + " OR E.voucher = null" + + " OR E.voucher = ''" + + " OR E.description = null" + + " OR E.description = '')" + + " AND :beginDate <= T.transactionDate" + + " AND T.transactionDate <= :endDate"; + List<FinancialTransaction> result; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate",beginDate); + args.put("endDate", endDate); + if (entryBook != null) { + args.put("entryBook", entryBook); + query += " AND T.entryBook = :entryBook"; + result = findAll(query, args); + } else { + result = findAll(query, args); + } + + return result; + } + + /** + * Find all transaction where some field are not filled in. + * + * @param beginDate begin date + * @param endDate end date + * @param entryBook entry book + * @return unfilled transaction + */ + public List<FinancialTransaction> getAllUnfilledTransaction(Date beginDate, + Date endDate, EntryBook entryBook) { + String query = "SELECT T FROM " + FinancialTransaction.class.getName() + " T"+ + " LEFT JOIN T.entry AS E" + + " WHERE ((SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = true AND financialTransaction = T) != " + + " (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = false AND financialTransaction = T) OR E.account = null" + + " OR E.voucher = null OR E.voucher = '' OR E.description = null OR E.description = '')" + + " AND T.entryBook = :entryBook" + + " AND :beginDate <= T.transactionDate" + + " AND T.transactionDate <= :endDate"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate",beginDate); + args.put("endDate", endDate); + args.put("entryBook", entryBook); + List<FinancialTransaction> result = findAll(query, args); + return result; + } + + /** + * Find all transaction without entry book. + * + * @param beginDate begin date + * @param endDate end date + * @return transaction without entry books + */ + public List<FinancialTransaction> getAllTransactionWithoutEntryBook(Date beginDate, + Date endDate) { + + String query = "SELECT T FROM " + FinancialTransaction.class.getName() + " T"+ + " LEFT JOIN T.entry AS E" + + " WHERE ((SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = true AND financialTransaction = T) != " + + " (SELECT sum(amount) FROM " + Entry.class.getName() + + " WHERE debit = false AND financialTransaction = T) OR E.account = null" + + " OR E.voucher = null OR E.voucher = '' OR E.description = null OR E.description = '')" + + " AND entryBook = null" + + " AND :beginDate <= T.transactionDate" + + " AND T.transactionDate <= :endDate"; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("beginDate",beginDate); + args.put("endDate", endDate); + + List<FinancialTransaction> result = findAll(query, args); + + return result; + } + + /** + * Search financial transaction. + * + * + * @param filter filter parameters + * @return financial transaction + */ + public List<FinancialTransaction> searchFinancialTransaction(Filter filter) { + + GeneratorHQuery generator = new GeneratorHQuery(); + filter.accept(generator); + + + String query = generator.getHQuery(); + Map<String,Object> arguments = generator.getParameters(); + + if (log.isDebugEnabled()) { + Set<String> parameters = arguments.keySet(); + for(String param : parameters) { + log.debug("Query : \n" + query + "\nArguments: " + param); + } + } + + // perform query + List<FinancialTransaction> result; + if (arguments.isEmpty()) { + result = findAll(query); + } else { + result = findAll(query, arguments); + } + + if (log.isDebugEnabled()) { + log.debug("Number of founded transactions : " + result.size()); + } + + return result; + } + +} //FinancialTransactionDAO Added: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFiscalPeriodTopiaDao.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFiscalPeriodTopiaDao.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractFiscalPeriodTopiaDao.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,140 @@ +/* + * #%L + * Lima callao + * + * $Id: FiscalPeriodDAOImpl.java 3598 2012-08-10 16:31:26Z mallon $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-callao/src/main/java/org/chorem/li... $ + * %% + * Copyright (C) 2012 CodeLutin, Chatellier Eric + * %% + * 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.entity; + +import java.util.List; +import java.util.Map; + +import com.google.common.collect.Maps; +import org.hibernate.HibernateException; +import org.nuiton.topia.persistence.TopiaException; + +/** + * Fiscal period entity DAO. + * + * @author chatellier + * @version $Revision: 3598 $ + * + * Last update : $Date: 2012-08-10 18:31:26 +0200 (ven. 10 août 2012) $ + * By : $Author: mallon $ + */ +public class AbstractFiscalPeriodTopiaDao<E extends FiscalPeriod> extends GeneratedFiscalPeriodTopiaDao<E> { + + /** + * FIXME echatellier, remove this method when implemented in topia + * just overriden to use merge() instead of saveOrUpdate() + */ + @Override + public FiscalPeriod update(FiscalPeriod e) throws TopiaException { + try { +// getContext().getHibernate().merge(e); +// getContext().getFiresSupport().warnOnUpdateEntity(e); +// return e; + // TODO DCossé 15/05/14 find a way to do it + return null; + } catch (HibernateException ex) { + throw new TopiaException(ex); + } + } + + /** + * Find fiscal period by financial period. + * + * @param financialPeriod financial period + * @return fiscal period containing financial period + * @throws TopiaException + */ + public FiscalPeriod findByFinancialPeriod(FinancialPeriod financialPeriod) throws TopiaException { + String query = "FROM " + FiscalPeriod.class.getName() + + " WHERE :financialPeriod in elements(financialPeriod)"; + + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("financialPeriod", financialPeriod); + + List<FiscalPeriod> fiscalPeriods = findAll(query, args); + FiscalPeriod result = null; + if (!fiscalPeriods.isEmpty()) { + result = fiscalPeriods.get(0); + } + return result; + } + + /** + * Get last fiscal period (higher end date). + * + * @return last fiscal period + * @throws TopiaException + */ + public FiscalPeriod getLastFiscalPeriod() throws TopiaException { + String query = "FROM " + FiscalPeriod.class.getName() + + " ORDER BY endDate desc"; + + List<FiscalPeriod> fiscalPeriods = findAll(query); + FiscalPeriod result = null; + if (!fiscalPeriods.isEmpty()) { + result = fiscalPeriods.get(0); + } + + return result; + } + + /** + * Get first fiscal period (higher end date). + * + * @return last fiscal period + * @throws TopiaException + */ + public FiscalPeriod getFirstFiscalPeriod() throws TopiaException { + String query = "FROM " + FiscalPeriod.class.getName() + + " ORDER BY endDate"; + + List<FiscalPeriod> fiscalPeriods = findAll(query); + FiscalPeriod result = null; + if (!fiscalPeriods.isEmpty()) { + result = fiscalPeriods.get(0); + } + return result; + } + + /** + * Get last non locked fiscal period (higher end date). + * + * @return last fiscal period + * @throws TopiaException + */ + public FiscalPeriod getLastUnlockedFiscalPeriod() throws TopiaException { + String query = "FROM " + FiscalPeriod.class.getName() + + " WHERE locked = false" + + " ORDER BY endDate desc"; + + List<FiscalPeriod> fiscalPeriods = findAll(query); + FiscalPeriod result = null; + if (!fiscalPeriods.isEmpty()) { + result = fiscalPeriods.get(0); + } + return result; + } +} Added: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractVatStatementTopiaDao.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractVatStatementTopiaDao.java (rev 0) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AbstractVatStatementTopiaDao.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,103 @@ +/* + * #%L + * Lima callao + * + * $Id: VatStatementDAOImpl.java 3585 2012-08-08 14:52:14Z tchemit $ + * $HeadURL: http://svn.chorem.org/svn/lima/trunk/lima-callao/src/main/java/org/chorem/li... $ + * %% + * Copyright (C) 2012 CodeLutin, Chatellier Eric + * %% + * 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.entity; + +import com.google.common.collect.Maps; + +import java.util.List; +import java.util.Map; + + +/** + * Ajout de requetes specifiques aux {@code VatStatement} sur le DAO. + * + * @author chatellier + * @version $Revision: 3585 $ + * + * Last update : $Date: 2012-08-08 16:52:14 +0200 (mer. 08 août 2012) $ + * By : $Author: tchemit $ + */ +public class AbstractVatStatementTopiaDao<E extends VatStatement> extends GeneratedVatStatementTopiaDao<E> { + + /** + * Find all {@code VatStatement} ordered by topia create date. + */ + public List<VatStatement> findAllOrderedByCreateDate() { + String query = "FROM " + VatStatement.class.getName() + + " ORDER BY " + VatStatement.TOPIA_CREATE_DATE; + List<VatStatement> result = findAll(query); + return result; + } + + /** + * Get masterVatStatement children statement. + * + * @param masterVatStatement master VatStatement + * @return children VatStatement + */ + public List<VatStatement> getChildrenVatStatement(VatStatement masterVatStatement) { + String query = "FROM " + VatStatement.class.getName(); + + if (masterVatStatement == null) { + query += " WHERE masterVatStatement = null"; + } else { + query += " WHERE masterVatStatement = :masterVatStatement"; + } + + query += " ORDER BY " + VatStatement.TOPIA_CREATE_DATE; + List<VatStatement> result; + if (masterVatStatement == null) { + result = findAll(query); + } else { + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("masterVatStatement", masterVatStatement); + result = findAll(query, args); + } + return result; + } + + /** + * Recherche un statement par equivalence de label. + * + * TODO voir a quoi ca sert vraiment. + * + * @param label label + * @return statement like label + */ + public VatStatement findVatStatementByLabel(String label) { + String query = "FROM " + VatStatement.class.getName() + + " WHERE label LIKE :label"; + Map<String, Object> args = Maps.newLinkedHashMap(); + args.put("label", "%" + label + "%"); + List<VatStatement> statements = findAll(query, args); + VatStatement result = null; + if (!statements.isEmpty()) { + result = statements.get(0); + } + return result; + } + +} //VatStatementDAO Deleted: trunk/lima-callao/src/main/java/org/chorem/lima/entity/AccountDAOImpl.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/AccountDAOImpl.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/AccountDAOImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,184 +0,0 @@ -/* - * #%L - * Lima callao - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric - * %% - * 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.entity; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.StringTokenizer; - -import org.apache.commons.lang3.StringUtils; -import org.nuiton.topia.TopiaException; - -public class AccountDAOImpl<E extends Account> extends AccountDAOAbstract<Account> { - - /** - * Retourne tous les comptes qui n'ont pas eux meme de sous compte. - * - * @return leaf accounts - * @throws TopiaException - */ - public List<Account> findAllLeafAccounts() throws TopiaException { - // FIXME echatellier 20120413 la requete ne fonctionne pas - // et retourne vide - /*String query = "FROM " + Account.class.getName() + " a WHERE a NOT IN (" + - "FROM " + Account.class.getName() + " b where b.accountNumber like concat(a.accountNumber,'%'))"; - List<Account> accounts = context.find(query);*/ - - // code temporaire non performant en attandant: - List<Account> allAccounts = findAll(); - Iterator<Account> itAccount = allAccounts.iterator(); - while (itAccount.hasNext()) { - Account acc = itAccount.next(); - Iterator<Account> itAccount2 = allAccounts.iterator(); - while (itAccount2.hasNext()) { - Account acc2 = itAccount2.next(); - if (!acc2.getAccountNumber().equals(acc.getAccountNumber()) && - acc2.getAccountNumber().startsWith(acc.getAccountNumber())) { - itAccount.remove(); - break; - } - } - } - return allAccounts; - } - - /** - * TODO pas compris l'interet de la methode, si on veut un compte feuille - * par son numero, cela revient a avoir un compte par son numero. - */ - @Deprecated - public Account findLeafAccountByNumber(String number) throws TopiaException { - return findByAccountNumber(number); - } - - /** - * Find account contained into account number interval. - * - * @param accountNumberLow min account number - * @param accountNumberHigh max account number - * @return account list - * @throws TopiaException - */ - protected List<Account> findIntervalAccountByNumber(String accountNumberLow, - String accountNumberHigh) throws TopiaException { - String query = "FROM " + Account.class.getName() + " WHERE :accountNumberLow <= accountNumber AND accountNumber <= :accountNumberHigh"; - return (List<Account>) context.findAll(query, "accountNumberLow", - accountNumberLow, "accountNumberHigh", accountNumberHigh); - } - - /** - * Retourne tous les comptes dont le numero commence par celui specifié. - * - * @param account parent account - * @return - * @throws TopiaException - */ - public List<Account> findAllSubAccounts(Account account) throws TopiaException { - - String query = "FROM " + Account.class.getName() + " a WHERE a.accountNumber LIKE concat(:accountNumber, '_%')"; - List<Account> accounts = context.findAll(query, "accountNumber", account.getAccountNumber()); - - return accounts; - } - - /** - * @deprecated since 0.6, business method, need to be moved out of dao - */ - @Deprecated - public List<Account> stringToListAccounts(String selectedAccounts, - Boolean leafAccountsMode) throws TopiaException { - Set<Account> accounts = new HashSet<Account>(); - if (selectedAccounts != null) { - //Remove Spaces - String result = StringUtils.deleteWhitespace(selectedAccounts); - - Boolean first = true; - StringTokenizer stStar = new StringTokenizer(result, "-"); - while (stStar.hasMoreTokens()) { - String subString = stStar.nextToken(); - - //Split comma - StringTokenizer stComma = new StringTokenizer(subString, ","); - while (stComma.hasMoreTokens()) { - String s = stComma.nextToken(); - //if intervall account - if (s.contains("..") && !s.endsWith("..")) { - //Split .. - String stringDoubleDot[] = s.split("\\.\\."); - - List<Account> resultIntervall = - findIntervalAccountByNumber(stringDoubleDot[0], stringDoubleDot[1]); - - //if first add accounts, else remove - if (first) { - accounts.addAll(resultIntervall); - } else { - accounts.removeAll(resultIntervall); - } - } - //else one account - else { - Account account = null; - if (leafAccountsMode) { - account = findLeafAccountByNumber(s); - } else { - account = findByAccountNumber(s); - } - //if exist - if (account != null) { - //if first - if (first) { - accounts.add(account); - } else { - accounts.remove(account); - } - } - //search all account start with accountnumber - else { - String query = "FROM " + Account.class.getName() + " a WHERE a NOT IN (" + - "FROM " + Account.class.getName() + " b where b.accountNumber like a.accountNumber+'%')" + - " AND a.accountNumber LIKE :s"; - List<Account> accountsResult = getContext().findAll(query, "s",s); - if (accountsResult != null) { - //if first - if (first) { - accounts.addAll(accountsResult); - } else { - accounts.removeAll(accountsResult); - } - } - } - } - } - first = false; - } - } - return new ArrayList(accounts); - } -} Deleted: trunk/lima-callao/src/main/java/org/chorem/lima/entity/ClosedPeriodicEntryBookDAOImpl.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/ClosedPeriodicEntryBookDAOImpl.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/ClosedPeriodicEntryBookDAOImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,197 +0,0 @@ -/* - * #%L - * Lima callao - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric - * %% - * 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.entity; - -import java.util.Date; -import java.util.List; - -import org.hibernate.HibernateException; -import org.nuiton.topia.TopiaException; - -public class ClosedPeriodicEntryBookDAOImpl<E extends ClosedPeriodicEntryBook> extends ClosedPeriodicEntryBookDAOAbstract<ClosedPeriodicEntryBook> { - - /** - * FIXME echatellier, remove this method when implemented in topia - * just overriden to use merge() instead of saveOrUpdate() - */ - public ClosedPeriodicEntryBook merge(ClosedPeriodicEntryBook e) throws TopiaException { - try { - e = (ClosedPeriodicEntryBook)getContext().getHibernate().merge(e); - getContext().getFiresSupport().warnOnUpdateEntity(e); - return e; - } catch (HibernateException ex) { - throw new TopiaException(ex); - } - } - - /** - * Find all ClosedPeriodicEntryBook with common EntryBook. - * - * @param entryBook entry book property - * @return ClosedPeriodicEntryBook list - * @throws TopiaException - */ - public List<ClosedPeriodicEntryBook> findAllByEntryBook(EntryBook entryBook) throws TopiaException { - return findAllByProperties(ClosedPeriodicEntryBook.PROPERTY_ENTRY_BOOK, entryBook); - } - - /** - * Return ClosedPeriodicEntryBook by EntryBook and FinancialPeriod. - * - * @param entryBook - * @param financialPeriod - * @return ClosedPeriodicEntryBook - * @throws TopiaException - */ - public ClosedPeriodicEntryBook findByEntryBookAndFinancialPeriod( - EntryBook entryBook, FinancialPeriod financialPeriod) - throws TopiaException { - - List<ClosedPeriodicEntryBook> closedPeriodicEntryBooks; - String query = "FROM " + ClosedPeriodicEntryBook.class.getName(); - if (entryBook != null) { - query += " WHERE entryBook = :entryBook"; - if (financialPeriod != null) { - query += " AND financialPeriod = :financialPeriod"; - //context.find(query, 0, 0, "entryBook", entryBook, "financialPeriod", financialPeriod); - closedPeriodicEntryBooks = context.findAll(query, "entryBook", entryBook, "financialPeriod", financialPeriod); - } else { - //context.find(query, 0, 0, "entryBook", entryBook); - closedPeriodicEntryBooks = context.findAll(query, "entryBook", entryBook); - } - } else { - if (financialPeriod != null) { - query += " WHERE financialPeriod = :financialPeriod"; - } - - //context.find(query, 0, 0, "financialPeriod", financialPeriod); - closedPeriodicEntryBooks = context.findAll(query, "financialPeriod", financialPeriod); - } - - // get only first one - ClosedPeriodicEntryBook result = null; - if (!closedPeriodicEntryBooks.isEmpty()) { - result = closedPeriodicEntryBooks.get(0); - } - return result; - } - - /** - * Retourne toutes les ClosedPeriodicEntryBook par interval de date - * sur les periodes sur lequelles elles portent ordonnée par journal. - * - * @param beginDate begin date - * @param endDate end date - * @return all ClosedPeriodicEntryBook between begin and end - * @throws TopiaException - */ - public List<ClosedPeriodicEntryBook> findAllByDates(Date beginDate, - Date endDate) throws TopiaException { - - String query = "FROM " + ClosedPeriodicEntryBook.class.getName() + - " WHERE :beginDate <= financialPeriod.beginDate " + - " AND financialPeriod.beginDate <= :endDate" + - " ORDER BY entryBook.code"; - return context.findAll(query, "beginDate", beginDate, "endDate", endDate); - } - - /** - * Retourne toutes les ClosedPeriodicEntryBook par interval de date - * sur les periodes sur lequelles elles portent pour un journal. - * - * @param entryBook entry book - * @param beginDate begin date - * @param endDate end date - * @return all ClosedPeriodicEntryBook between begin and end - * @throws TopiaException - */ - public List<ClosedPeriodicEntryBook> findAllByEntryBookAndDates(EntryBook entryBook, - Date beginDate, Date endDate) throws TopiaException { - - String query = "FROM " + ClosedPeriodicEntryBook.class.getName() + - " WHERE :beginDate <= financialPeriod.beginDate " + - " AND financialPeriod.beginDate <= :endDate" + - " AND entryBook = :entryBook"; - return context.findAll(query, "beginDate", beginDate, "endDate", endDate, "entryBook", entryBook); - } - - /** - * Retourne toutes les ClosedPeriodicEntryBook par interval de date - * sur les periodes sur lequelles elles portent pour un journal. - * - * @param entryBook entry book - * @param beginDate begin date - * @param endDate end date - * @return all ClosedPeriodicEntryBook between begin and end - * @throws TopiaException - */ - public List<ClosedPeriodicEntryBook> findAllByEntryBookAndDatesLocked(EntryBook entryBook, - Date beginDate, Date endDate) throws TopiaException { - - String query = "FROM " + ClosedPeriodicEntryBook.class.getName() + - " WHERE :beginDate <= financialPeriod.beginDate " + - " AND financialPeriod.beginDate <= :endDate" + - " AND entryBook = :entryBook" + - " AND locked = true"; - return context.findAll(query, "beginDate", beginDate, "endDate", endDate, "entryBook", entryBook); - } - - /** - * Retourne les ClosedPeriodicEntryBook de toutes les exercices encore ouverts. - * - * @return les ClosedPeriodicEntryBook - * @throws TopiaException - */ - public List<ClosedPeriodicEntryBook> findAllClosedPeriodicEntryBooksFromUnblockedFiscalPeriod() throws TopiaException { - String query = "SELECT C FROM " + ClosedPeriodicEntryBook.class.getName() + " C" + - ", " + FiscalPeriod.class.getName() + " F" + - " WHERE C.financialPeriod IN ELEMENTS (F.financialPeriod)" + - " AND F.locked = false" + - " ORDER BY C.financialPeriod.beginDate"; - - List<ClosedPeriodicEntryBook> result = context.findAll(query); - return result; - } - - /** - * Retourne les ClosedPeriodicEntryBook d'un exercice ouvert. - * - * @return les ClosedPeriodicEntryBook - * @throws TopiaException - */ - public List<ClosedPeriodicEntryBook> findAllClosedPeriodicEntryBooksFromFiscalPeriod(FiscalPeriod fiscalPeriod) throws TopiaException { - String query = "SELECT C FROM " + ClosedPeriodicEntryBook.class.getName() + " C" + - ", " + FiscalPeriod.class.getName() + " F" + - " WHERE C.financialPeriod IN ELEMENTS (F.financialPeriod)" + - " AND F = :fiscalPeriod" + - " ORDER BY C.financialPeriod.beginDate"; - - List<ClosedPeriodicEntryBook> result = context.findAll(query, "fiscalPeriod", fiscalPeriod); - - return result; - } - -} Deleted: trunk/lima-callao/src/main/java/org/chorem/lima/entity/EntryDAOImpl.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/EntryDAOImpl.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/EntryDAOImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,296 +0,0 @@ -/* - * #%L - * Lima callao - * * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric - * %% - * 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.entity; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.beans.LetteringFilter; -import org.nuiton.topia.TopiaException; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -public class EntryDAOImpl<E extends Entry> extends EntryDAOAbstract<Entry> { - - private static final Log log = LogFactory.getLog(EntryDAOImpl.class); - - /** - * Requete generique qui recupere les entrees equilibrées portant entre - * deux dates. - * - * @param beginDate begin date - * @param endDate end date - */ - protected String getEquilibredTransactionQuery(Date beginDate, Date endDate) { - String query = "FROM " + Entry.class.getName() + " E" + - // equlibrée (somme des débit = somme des crédit) - " WHERE (select sum(E2.amount) from " + Entry.class.getName() + " E2 where E2.debit = false and E2.financialTransaction = E.financialTransaction) = " + - "(select sum(E2.amount) from " + Entry.class.getName() + " E2 where E2.debit = true and E2.financialTransaction = E.financialTransaction)" + - // entre les 2 dates - " AND :beginDate <= E.financialTransaction.transactionDate" + - " AND E.financialTransaction.transactionDate <= :endDate"; - return query; - } - - /** - * Query for find entries for accountsreports and balancereports - * Just exact and balanced transaction are calculated. - * - * @param account account - * @param beginDate begin date - * @param endDate end date - * @return entries - * @throws TopiaException - */ - public List<Entry> findAllEntryOfBalancedTransaction(Account account, - Date beginDate, Date endDate) throws TopiaException { - - String query = getEquilibredTransactionQuery(beginDate, endDate) + - // concerne le compte - " AND E.account = :account"; - - List<Entry> entries = context.findAll(query, "beginDate", beginDate, - "endDate", endDate, "account", account); - - return entries; - } - - /** - * Retourne la somme des entrées des transaction equilibrées entre - * deux dates pour un compte donné. - * - * @param account account - * @param beginDate bebin date - * @param endDate end date - * @return list boolean,int (une ligne pour le debit true, une ligne pour le credit) - * @throws TopiaException - */ - public List<Object[]> getDebitCreditOfBalancedTransaction(Account account, - Date beginDate, Date endDate) throws TopiaException { - String query = "SELECT E.debit, sum(E.amount) " + - getEquilibredTransactionQuery(beginDate, endDate) + - // concerne le compte - " AND E.account = :account" + - " GROUP BY E.debit"; - - List<Object[]> result = context.findAll(query, "beginDate", beginDate, - "endDate", endDate, "account", account); - return result; - } - - /** - * Retourne les entrees des transaction equlibrées entre deux dates pour - * un journal. - * - * @param entryBook entry book - * @param beginDate begin date - * @param endDate end date - * @throws TopiaException - */ - public List<Entry> findAllEntryOfBalancedTransaction(EntryBook entryBook, Date beginDate, - Date endDate) throws TopiaException { - String query = getEquilibredTransactionQuery(beginDate, endDate) + - // concerne le journal - " AND E.financialTransaction.entryBook = :entryBook" + - // fix order - " ORDER BY E.financialTransaction.transactionDate, E.financialTransaction.topiaId"; - - List<Entry> entries = context.findAll(query, "beginDate", beginDate, - "endDate", endDate, "entryBook", entryBook); - return entries; - } - - public List<String> findLetters() throws TopiaException{ - String query = "Select distinct E.lettering FROM " + Entry.class.getName() + " E" + - " where E.lettering <> null" + - " order by E.lettering desc"; - - List<String> result = new ArrayList<String>(context.findAll(query)); - - if (log.isDebugEnabled()) { - log.debug("Size of result : " + result.size()); - } - - return result; - } - - /** - * Retourne la somme des entrées des transaction equilibrées entre - * deux dates pour un journal donné. - * - * @param entryBook entry book - * @param beginDate bebin date - * @param endDate end date - * @return list boolean,int (une ligne pour le debit true, une ligne pour le credit) - * @throws TopiaException - */ - public List<Object[]> getDebitCreditOfBalancedTransaction(EntryBook entryBook, - Date beginDate, Date endDate) throws TopiaException { - String query = "SELECT E.debit, sum(E.amount) " + - getEquilibredTransactionQuery(beginDate, endDate) + - // concerne le journal - " AND E.financialTransaction.entryBook = :entryBook" + - " GROUP BY E.debit"; - - List<Object[]> result = context.findAll(query, "beginDate", beginDate, - "endDate", endDate, "entryBook", entryBook); - return result; - } - - /** - * Retourne les entrees des transaction entre deux dates pour - * un journal. - * - * @param entryBook entry book - * @param beginDate begin date - * @param endDate end date - * @throws TopiaException - */ - public List<Entry> findAllEntryByDateForEntryBook(EntryBook entryBook, Date beginDate, - Date endDate) throws TopiaException { - String query = "FROM " + Entry.class.getName() + " E" + - // entre les 2 dates - " WHERE :beginDate <= E.financialTransaction.transactionDate" + - " AND E.financialTransaction.transactionDate <= :endDate" + - // concerne le journal - " AND E.financialTransaction.entryBook = :entryBook"; - - List<Entry> entries = context.findAll(query, "beginDate", beginDate, - "endDate", endDate, "entryBook", entryBook); - return entries; - } - - /** - * Retourne toutes les entrées d'une transaction - * pour un compte et la présence d'un lettrage ou (xor) non - * @param filter filtre sur les entrees, selon le compte, les dates de debut et de fin, et le lettrage - * @throws TopiaException - * */ - public List<Entry> findAllEntryByFilter(LetteringFilter filter) throws TopiaException { - - List<Entry> entries; - Account account = filter.getAccount(); - - if (account != null && account.getTopiaId() == null) { - // case user want to see all accounts - entries = getAllEntryByLetteringAndDateForEntryBook(filter); - } else { - entries = getAllEntryByAccountLetteringAndDateForEntryBook(filter); - } - return entries; - } - - public List<Entry> getAllEntryByAccountLetteringAndDateForEntryBook(LetteringFilter filter) throws TopiaException { - List<Entry> entries; - - String query = "Select E from " + Entry.class.getName() + " E " + - " where E.account.accountNumber like :account "; - - - if (!filter.getDisplayLettered() && filter.getDisplayUnlettred()){ - query += " and (E.lettering is null or E.lettering = '') "; - } else if (filter.getDisplayLettered() && !filter.getDisplayUnlettred()){ - query += " and (E.lettering is not null or E.lettering !='') "; - } - - query += " and E.financialTransaction.transactionDate between :beginDate and :endDate " + - " order by E.financialTransaction.transactionDate, E.financialTransaction." + FinancialTransaction.TOPIA_CREATE_DATE; - - - entries = context.findAll(query, "account", filter.getAccount().getAccountNumber() + "%", "beginDate", filter.getDateStart(), "endDate", filter.getDateEnd()); - - return entries; - } - - public List<Entry> getAllEntryByLetteringAndDateForEntryBook(LetteringFilter filter) throws TopiaException { - List<Entry> entries; - - String query = "Select E from " + Entry.class.getName() + " E "; - - query += " WHERE E.financialTransaction.transactionDate BETWEEN :beginDate and :endDate "; - - if (!filter.getDisplayLettered() && filter.getDisplayUnlettred()){ - query += " and (E.lettering is null or E.lettering = '') "; - } else if (filter.getDisplayLettered() && !filter.getDisplayUnlettred()){ - query += " and (E.lettering is not null or E.lettering !='') "; - } - - query += " order by E.financialTransaction.transactionDate, E.financialTransaction." + FinancialTransaction.TOPIA_CREATE_DATE; - - entries = context.findAll(query, "beginDate", filter.getDateStart(), "endDate", filter.getDateEnd()); - - return entries; - } - - - /** - * Retourne la dernière entrée d'une transaction - * @param financialTransaction transaction sur laquelle la derniere entree est selectionnee - * */ - public Entry getLastEntry(FinancialTransaction financialTransaction) throws TopiaException { - List<Entry> entries; - Entry lastEntry = null; - String query = "Select E from " + Entry.class.getName() + " E" + - " where E.financialTransaction.transactionDate = :financialTransactionDate " + - " and E.financialTransaction = :financialTransaction" + - " order by E.topiaCreateDate desc"; - - entries = context.findAll(query, "financialTransactionDate", financialTransaction.getTransactionDate(), "financialTransaction", financialTransaction); - - if (entries.size() > 0) { - lastEntry = entries.get(0); - } - - return lastEntry; - } - - /** - * Retourne la somme des entrées des transaction entre - * deux dates pour un journal donné. - * - * @param entryBook entry book - * @param beginDate bebin date - * @param endDate end date - * @return list boolean,int (une ligne pour le debit true, une ligne pour le credit) - * @throws TopiaException - */ - public List<Object[]> getDebitCreditOfTransaction(EntryBook entryBook, - Date beginDate, Date endDate) throws TopiaException { - String query = "SELECT E.debit, sum(E.amount) " + - "FROM " + Entry.class.getName() + " E" + - // entre les 2 dates - " WHERE :beginDate <= E.financialTransaction.transactionDate" + - " AND E.financialTransaction.transactionDate <= :endDate" + - // concerne le journal - " AND E.financialTransaction.entryBook = :entryBook" + - " GROUP BY E.debit"; - - List<Object[]> result = context.findAll(query, "beginDate", beginDate, - "endDate", endDate, "entryBook", entryBook); - return result; - } -} Deleted: trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialPeriodDAOImpl.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialPeriodDAOImpl.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialPeriodDAOImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,105 +0,0 @@ -/* - * #%L - * Lima callao - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric - * %% - * 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.entity; - -import java.util.Date; -import java.util.List; - -import org.nuiton.topia.TopiaException; - -public class FinancialPeriodDAOImpl<E extends FinancialPeriod> extends FinancialPeriodDAOAbstract<FinancialPeriod> { - - /** - * Return FinancialPeriod by Date. - * Date is include between financialperiod begin and end date. - * - * @param date period middle date - * @return FinancialPeriod for {@code date} - * @throws TopiaException - */ - public FinancialPeriod findByDate(Date date) throws TopiaException { - - String query = "FROM " + FinancialPeriod.class.getName() + - " WHERE beginDate <= :date" + - " AND :date <= endDate"; - - // add unique result here - FinancialPeriod financialPeriod = (FinancialPeriod)context.findUnique(query, "date", date); - return financialPeriod; - } - - /** - * Return all FinancialPeriod with begin date between two given dates. - * - * @param beginDate period begin date - * @param endDate period end date - * @return FinancialPeriod for {@code date} - * @throws TopiaException - */ - public List<FinancialPeriod> findByDates(Date beginDate, Date endDate) throws TopiaException { - - String query = "FROM " + FinancialPeriod.class.getName() + - " WHERE :beginDate <= beginDate" + - " AND beginDate <= :endDate" + - " ORDER by beginDate"; - - // add unique result here - List<FinancialPeriod> financialPeriod = context.findAll(query, "beginDate", beginDate, "endDate", endDate); - return financialPeriod; - } - - /** - * Retourne toutes les periodes ordonnées par date de debut de periode. - * - * @return all period ordered - * @throws TopiaException - */ - public List<FinancialPeriod> findAllOrderByBeginDate() throws TopiaException { - String query = "FROM " + FinancialPeriod.class.getName() + - " ORDER BY beginDate"; - - // add unique result here - List<FinancialPeriod> financialPeriod = context.findAll(query); - return financialPeriod; - } - - /** - * Retourne toutes les periodes ordonnées par date de debut de periode. - * - * @return all period ordered - * @throws TopiaException - */ - public List<FinancialPeriod> findAllUnlockedOrderByBeginDate() throws TopiaException { - String query = "FROM " + FinancialPeriod.class.getName() + - " WHERE locked = false" + - " ORDER BY beginDate"; - - // add unique result here - List<FinancialPeriod> financialPeriod = context.findAll(query); - return financialPeriod; - } - -} Deleted: trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialStatementDAOImpl.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialStatementDAOImpl.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialStatementDAOImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,77 +0,0 @@ -/* - * #%L - * Lima callao - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 CodeLutin, Chatellier Eric - * %% - * 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.entity; - -import java.util.List; - -import org.nuiton.topia.TopiaException; - -/** - * Ajout de requetes specifiques aux {@link FinancialStatement} sur le DAO. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class FinancialStatementDAOImpl<E extends FinancialStatement> extends FinancialStatementDAOAbstract<FinancialStatement> { - - /** - * Find all {@code FinancialStatement} ordered by topia create date. - * @throws TopiaException - */ - public List<FinancialStatement> findAllOrderedByCreateDate() throws TopiaException { - String query = "FROM " + FinancialStatement.class.getName() + - " ORDER BY " + FinancialStatement.TOPIA_CREATE_DATE; - List<FinancialStatement> result = context.findAll(query); - return result; - } - - /** - * Find all {@code FinancialStatement} ordered by topia create date. - * @throws TopiaException - */ - public List<FinancialStatement> findChildrenFinancialStatement(FinancialStatement financialStatement) throws TopiaException { - String query = "FROM " + FinancialStatement.class.getName(); - - if (financialStatement == null) { - query += " WHERE masterFinancialStatement = null"; - } else { - query += " WHERE masterFinancialStatement = :masterFinancialStatement"; - } - query += " ORDER BY " + FinancialStatement.TOPIA_CREATE_DATE; - - List<FinancialStatement> result; - if (financialStatement == null) { - result = context.findAll(query); - } else { - result = context.findAll(query, "masterFinancialStatement", financialStatement); - } - return result; - } - -} //FinancialStatementDAO Deleted: trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialTransactionDAOImpl.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialTransactionDAOImpl.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/FinancialTransactionDAOImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,301 +0,0 @@ -/* - * #%L - * Lima callao - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 CodeLutin, Chatellier Eric - * %% - * 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.entity; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.Filter.Filter; -import org.hibernate.HibernateException; -import org.nuiton.topia.TopiaException; - -import java.util.Date; -import java.util.List; - -/** - * Ajout de requetes specifiques aux financial transaction sur le DAO. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class FinancialTransactionDAOImpl<E extends FinancialTransaction> extends FinancialTransactionDAOAbstract<FinancialTransaction> { - - private static final Log log = LogFactory.getLog(FinancialTransactionDAOImpl.class); - - /** - * FIXME echatellier, remove this method when implemented in topia - * just overriden to use merge() instead of saveOrUpdate() - */ - public FinancialTransaction merge(FinancialTransaction e) throws TopiaException { - try { - e = (FinancialTransaction)getContext().getHibernate().merge(e); - getContext().getFiresSupport().warnOnUpdateEntity(e); - return e; - } catch (HibernateException ex) { - throw new TopiaException(ex); - } - } - - /** - * Return how many transaction are found with specified entryBook. - * - * @param entryBook entry book - * @return transaction referencing entry book - * @throws TopiaException - */ - public long getCountByEntryBook(EntryBook entryBook) throws TopiaException { - String query = "SELECT count(*) FROM " + FinancialTransaction.class.getName() + " t WHERE t.entryBook = :entryBook"; - Number count = (Number)context.findAll(query, "entryBook", entryBook).get(0); - return count.longValue(); - } - - /** - * Find all transactions between two dates. - * - * @param beginDate begin date - * @param endDate end date - * @return unbalanced transactions - * @throws TopiaException - */ - public List<FinancialTransaction> findAllByDates(Date beginDate, Date endDate) throws TopiaException { - String query = "FROM " + FinancialTransaction.class.getName() + " T"+ - " WHERE :beginDate <= T.transactionDate" + - " AND T.transactionDate <= :endDate" + - " ORDER BY T.transactionDate, T." + FinancialTransaction.TOPIA_CREATE_DATE; - List<FinancialTransaction> result = context.findAll(query, "beginDate", - beginDate, "endDate", endDate); - return result; - } - - /** - * Find all transactions between two dates in an entry book. - * - * @param beginDate begin date - * @param endDate end date - * @param entryBook entry book - * @return unbalanced transactions - * @throws TopiaException - */ - public List<FinancialTransaction> findAllByDates(Date beginDate, Date endDate, EntryBook entryBook) throws TopiaException { - String query = "FROM " + FinancialTransaction.class.getName() + " T"+ - " WHERE :beginDate <= T.transactionDate" + - " AND T.transactionDate <= :endDate" + - " AND T.entryBook = :entryBook" + - " ORDER BY T.transactionDate, T." + FinancialTransaction.TOPIA_CREATE_DATE; - List<FinancialTransaction> result = context.findAll(query, "beginDate", - beginDate, "endDate", endDate, "entryBook", entryBook); - return result; - } - - /** - * Find all unbalanced transactions. - * - * @param beginDate beginDate - * @param endDate endDate - * @param entryBook entry book (can be null) - * @return unbalanced transactions - * @throws TopiaException - */ - public List<FinancialTransaction> getAllUnbalancedTransaction(Date beginDate, Date endDate, - EntryBook entryBook) throws TopiaException { - String query = "FROM " + FinancialTransaction.class.getName() + " T"+ - " WHERE (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = true AND financialTransaction = T) != " + - " (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = false AND financialTransaction = T)" + - " AND :beginDate <= T.transactionDate" + - " AND T.transactionDate <= :endDate"; - List<FinancialTransaction> result = null; - if (entryBook != null) { - query += " AND T.entryBook = :entryBook"; - result = context.findAll(query, "beginDate", beginDate, "endDate", endDate, "entryBook", entryBook); - } else { - result = context.findAll(query, "beginDate", beginDate, "endDate", endDate); - } - - return result; - } - - /** - * Find all unbalanced transactions. - * - * @param beginDate beginDate - * @param endDate endDate - * @param entryBook entry book (can be null) - * @return unbalanced transactions - * @throws TopiaException - */ - public List<FinancialTransaction> getAllBalancedTransaction(Date beginDate, Date endDate, - EntryBook entryBook) throws TopiaException { - String query = "FROM " + FinancialTransaction.class.getName() + " T"+ - " WHERE (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = true AND financialTransaction = T) = " + - " (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = false AND financialTransaction = T)" + - " AND :beginDate <= T.transactionDate" + - " AND T.transactionDate <= :endDate"; - List<FinancialTransaction> result = null; - if (entryBook != null) { - query += " AND T.entryBook = :entryBook"; - result = context.findAll(query, "beginDate", beginDate, "endDate", endDate, "entryBook", entryBook); - } else { - result = context.findAll(query, "beginDate", beginDate, "endDate", endDate); - } - - return result; - } - - /** - * Find all unbalanced transactions. - * - * @param beginDate beginDate - * @param endDate endDate - * @param entryBook entry book (can be null) - * @return unbalanced transactions - * @throws TopiaException - */ - public List<FinancialTransaction> getAllIncorrectTransaction(Date beginDate, Date endDate, - EntryBook entryBook) throws TopiaException { - String query = "SELECT distinct T FROM " + FinancialTransaction.class.getName() + " T"+ - " LEFT JOIN T.entry AS E" + - " WHERE ((SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = true AND financialTransaction = T) != " + - " (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = false AND financialTransaction = T)" + - " OR (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = true AND financialTransaction = T) IS NULL" + - " OR (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = false AND financialTransaction = T) IS NULL" + - " OR E.account = null" + - " OR E.voucher = null" + - " OR E.voucher = ''" + - " OR E.description = null" + - " OR E.description = '')" + - " AND :beginDate <= T.transactionDate" + - " AND T.transactionDate <= :endDate"; - List<FinancialTransaction> result = null; - if (entryBook != null) { - query += " AND T.entryBook = :entryBook"; - result = context.findAll(query, "beginDate", beginDate, "endDate", endDate, "entryBook", entryBook); - } else { - result = context.findAll(query, "beginDate", beginDate, "endDate", endDate); - } - - return result; - } - - /** - * Find all transaction where some field are not filled in. - * - * @param beginDate begin date - * @param endDate end date - * @param entryBook entry book - * @return unfilled transaction - * @throws TopiaException - */ - public List<FinancialTransaction> getAllUnfilledTransaction(Date beginDate, - Date endDate, EntryBook entryBook) throws TopiaException { - String query = "SELECT T FROM " + FinancialTransaction.class.getName() + " T"+ - " LEFT JOIN T.entry AS E" + - " WHERE ((SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = true AND financialTransaction = T) != " + - " (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = false AND financialTransaction = T) OR E.account = null" + - " OR E.voucher = null OR E.voucher = '' OR E.description = null OR E.description = '')" + - " AND T.entryBook = :entryBook" + - " AND :beginDate <= T.transactionDate" + - " AND T.transactionDate <= :endDate"; - List<FinancialTransaction> result = context.findAll(query, "beginDate", beginDate, - "endDate", endDate, "entryBook", entryBook); - return result; - } - - /** - * Find all transaction without entry book. - * - * @param beginDate begin date - * @param endDate end date - * @return transaction without entry books - * @throws TopiaException - */ - public List<FinancialTransaction> getAllTransactionWithoutEntryBook(Date beginDate, - Date endDate) throws TopiaException { - - String query = "SELECT T FROM " + FinancialTransaction.class.getName() + " T"+ - " LEFT JOIN T.entry AS E" + - " WHERE ((SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = true AND financialTransaction = T) != " + - " (SELECT sum(amount) FROM " + Entry.class.getName() + - " WHERE debit = false AND financialTransaction = T) OR E.account = null" + - " OR E.voucher = null OR E.voucher = '' OR E.description = null OR E.description = '')" + - " AND entryBook = null" + - " AND :beginDate <= T.transactionDate" + - " AND T.transactionDate <= :endDate"; - List<FinancialTransaction> result = context.findAll(query, "beginDate", - beginDate, "endDate", endDate); - - return result; - } - - /** - * Search financial transaction. - * - * - * @param filter filter parameters - * @return financial transaction - * @throws TopiaException - */ - public List<FinancialTransaction> searchFinancialTransaction(Filter filter) throws TopiaException { - - GeneratorHQuery generator = new GeneratorHQuery(); - filter.accept(generator); - - - String query = generator.getHQuery(); - List<Object> arguments = generator.getArguments(); - - if (log.isDebugEnabled()) { - log.debug("Query : \n" + query + "\nArguments: " + arguments); - } - - // perform query - List<FinancialTransaction> result; - if (arguments.isEmpty()) { - result = context.findAll(query); - } else { - result = context.findAll(query, arguments.toArray()); - } - - if (log.isDebugEnabled()) { - log.debug("Number of founded transactions : " + result.size()); - } - - return result; - } - -} //FinancialTransactionDAO Deleted: trunk/lima-callao/src/main/java/org/chorem/lima/entity/FiscalPeriodDAOImpl.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/FiscalPeriodDAOImpl.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/FiscalPeriodDAOImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,133 +0,0 @@ -/* - * #%L - * Lima callao - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 CodeLutin, Chatellier Eric - * %% - * 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.entity; - -import java.util.List; - -import org.hibernate.HibernateException; -import org.nuiton.topia.TopiaException; - -/** - * Fiscal period entity DAO. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class FiscalPeriodDAOImpl <E extends FiscalPeriod> extends FiscalPeriodDAOAbstract<FiscalPeriod> { - - /** - * FIXME echatellier, remove this method when implemented in topia - * just overriden to use merge() instead of saveOrUpdate() - */ - @Override - public FiscalPeriod update(FiscalPeriod e) throws TopiaException { - try { - getContext().getHibernate().merge(e); - getContext().getFiresSupport().warnOnUpdateEntity(e); - return e; - } catch (HibernateException ex) { - throw new TopiaException(ex); - } - } - - /** - * Find fiscal period by financial period. - * - * @param financialPeriod financial period - * @return fiscal period containing financial period - * @throws TopiaException - */ - public FiscalPeriod findByFinancialPeriod(FinancialPeriod financialPeriod) throws TopiaException { - String query = "FROM " + FiscalPeriod.class.getName() + - " WHERE :financialPeriod in elements(financialPeriod)"; - - List<FiscalPeriod> fiscalPeriods = context.findAll(query, "financialPeriod", financialPeriod); - FiscalPeriod result = null; - if (!fiscalPeriods.isEmpty()) { - result = fiscalPeriods.get(0); - } - return result; - } - - /** - * Get last fiscal period (higher end date). - * - * @return last fiscal period - * @throws TopiaException - */ - public FiscalPeriod getLastFiscalPeriod() throws TopiaException { - String query = "FROM " + FiscalPeriod.class.getName() + - " ORDER BY endDate desc"; - - List<FiscalPeriod> fiscalPeriods = context.findAll(query); - FiscalPeriod result = null; - if (!fiscalPeriods.isEmpty()) { - result = fiscalPeriods.get(0); - } - - return result; - } - - /** - * Get first fiscal period (higher end date). - * - * @return last fiscal period - * @throws TopiaException - */ - public FiscalPeriod getFirstFiscalPeriod() throws TopiaException { - String query = "FROM " + FiscalPeriod.class.getName() + - " ORDER BY endDate"; - - List<FiscalPeriod> fiscalPeriods = context.findAll(query); - FiscalPeriod result = null; - if (!fiscalPeriods.isEmpty()) { - result = fiscalPeriods.get(0); - } - return result; - } - - /** - * Get last non locked fiscal period (higher end date). - * - * @return last fiscal period - * @throws TopiaException - */ - public FiscalPeriod getLastUnlockedFiscalPeriod() throws TopiaException { - String query = "FROM " + FiscalPeriod.class.getName() + - " WHERE locked = false" + - " ORDER BY endDate desc"; - - List<FiscalPeriod> fiscalPeriods = context.findAll(query); - FiscalPeriod result = null; - if (!fiscalPeriods.isEmpty()) { - result = fiscalPeriods.get(0); - } - return result; - } -} Modified: trunk/lima-callao/src/main/java/org/chorem/lima/entity/GeneratorHQuery.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/GeneratorHQuery.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/GeneratorHQuery.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -114,6 +114,10 @@ return alias; } + public Map<String, Object> getParameters() { + return parameters; + } + public List<Object> getArguments() { List<Object> result = new ArrayList<Object>(); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Deleted: trunk/lima-callao/src/main/java/org/chorem/lima/entity/VatStatementDAOImpl.java =================================================================== --- trunk/lima-callao/src/main/java/org/chorem/lima/entity/VatStatementDAOImpl.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-callao/src/main/java/org/chorem/lima/entity/VatStatementDAOImpl.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -1,101 +0,0 @@ -/* - * #%L - * Lima callao - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 CodeLutin, Chatellier Eric - * %% - * 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.entity; - -import java.util.List; - -import org.nuiton.topia.TopiaException; - - -/** - * Ajout de requetes specifiques aux {@code VatStatement} sur le DAO. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class VatStatementDAOImpl<E extends VatStatement> extends VatStatementDAOAbstract<VatStatement> { - - /** - * Find all {@code VatStatement} ordered by topia create date. - * @throws TopiaException - */ - public List<VatStatement> findAllOrderedByCreateDate() throws TopiaException { - String query = "FROM " + VatStatement.class.getName() + - " ORDER BY " + VatStatement.TOPIA_CREATE_DATE; - List<VatStatement> result = context.findAll(query); - return result; - } - - /** - * Get masterVatStatement children statement. - * - * @param masterVatStatement master VatStatement - * @return children VatStatement - * @throws TopiaException - */ - public List<VatStatement> getChildrenVatStatement(VatStatement masterVatStatement) throws TopiaException { - String query = "FROM " + VatStatement.class.getName(); - - if (masterVatStatement == null) { - query += " WHERE masterVatStatement = null"; - } else { - query += " WHERE masterVatStatement = :masterVatStatement"; - } - - query += " ORDER BY " + VatStatement.TOPIA_CREATE_DATE; - List<VatStatement> result; - if (masterVatStatement == null) { - result = context.findAll(query); - } else { - result = context.findAll(query, "masterVatStatement", masterVatStatement); - } - return result; - } - - /** - * Recherche un statement par equivalence de label. - * - * TODO voir a quoi ca sert vraiment. - * - * @param label label - * @return statement like label - * @throws TopiaException - */ - public VatStatement findVatStatementByLabel(String label) throws TopiaException { - String query = "FROM " + VatStatement.class.getName() + - " WHERE label LIKE :label"; - List<VatStatement> statements = context.findAll(query, "label", "%" + label + "%"); - VatStatement result = null; - if (!statements.isEmpty()) { - result = statements.get(0); - } - return result; - } - -} //VatStatementDAO Added: trunk/lima-callao/src/main/xmi/accounting-model.properties =================================================================== --- trunk/lima-callao/src/main/xmi/accounting-model.properties (rev 0) +++ trunk/lima-callao/src/main/xmi/accounting-model.properties 2014-05-16 08:39:35 UTC (rev 3798) @@ -0,0 +1,62 @@ +### +# #%L +# Lima callao +# +# $Id$ +# $HeadURL$ +# %% +# Copyright (C) 2008 - 2012 CodeLutin, Chatellier Eric +# %% +# 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% +### +# Precise l'entete de l'ensemble des fichiers generes +model.tagvalue.copyright=/*\n Copyright (C) 2009-2012 Lima Callao\n */ +model.tagvalue.version=0.6 +model.tagvalue.constantPrefix=PROPERTY_ +model.tagValue.notGenerateToString=true +model.tagvalue.String=text + +# natural id +org.chorem.lima.entity.Account.class.tagvalue.naturalIdMutable=false +org.chorem.lima.entity.Account.attribute.accountNumber.tagvalue.naturalId=true +org.chorem.lima.entity.Account.attribute.accountNumber.tagvalue.notNull=true + +org.chorem.lima.entity.FinancialPeriod.class.tagvalue.naturalIdMutable=false +org.chorem.lima.entity.FinancialPeriod.attribute.beginDate.tagvalue.naturalId=true +org.chorem.lima.entity.FinancialPeriod.attribute.beginDate.tagvalue.notNull=true +org.chorem.lima.entity.FinancialPeriod.attribute.endDate.tagvalue.naturalId=true +org.chorem.lima.entity.FinancialPeriod.attribute.endDate.tagvalue.notNull=true + +org.chorem.lima.entity.FiscalPeriod.class.tagvalue.naturalIdMutable=true +org.chorem.lima.entity.FiscalPeriod.attribute.beginDate.tagvalue.naturalId=true +org.chorem.lima.entity.FiscalPeriod.attribute.beginDate.tagvalue.notNull=true +org.chorem.lima.entity.FiscalPeriod.attribute.endDate.tagvalue.naturalId=true +org.chorem.lima.entity.FiscalPeriod.attribute.endDate.tagvalue.notNull=true + +# lazy +org.chorem.lima.entity.ClosedPeriodicEntryBook.attribute.entryBook.tagvalue.lazy=false +org.chorem.lima.entity.ClosedPeriodicEntryBook.attribute.financialPeriod.tagvalue.lazy=false + +org.chorem.lima.entity.Entry.attribute.account.tagvalue.lazy=false +org.chorem.lima.entity.Entry.attribute.financialTransaction.tagvalue.lazy=false + +org.chorem.lima.entity.FinancialTransaction.attribute.entry.tagvalue.lazy=false +org.chorem.lima.entity.FinancialTransaction.attribute.entryBook.tagvalue.lazy=false +org.chorem.lima.entity.FinancialStatement.attribute.subFinancialStatements.tagvalue.lazy=false +org.chorem.lima.entity.FinancialStatement.attribute.masterFinancialStatement.tagvalue.lazy=false + +org.chorem.lima.entity.VatStatement.attribute.subVatStatements.tagvalue.lazy=false +org.chorem.lima.entity.VatStatement.attribute.masterVatStatement.tagvalue.lazy=false Property changes on: trunk/lima-callao/src/main/xmi/accounting-model.properties ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Added: svn:eol-style + native Added: trunk/lima-callao/src/main/xmi/accounting-model.zargo =================================================================== (Binary files differ) Property changes on: trunk/lima-callao/src/main/xmi/accounting-model.zargo ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: svn:keywords + Author Date Id Revision HeadURL Modified: trunk/lima-neogia/src/main/java/org/chorem/lima/service/neogia/NeogiaEntryService.java =================================================================== --- trunk/lima-neogia/src/main/java/org/chorem/lima/service/neogia/NeogiaEntryService.java 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-neogia/src/main/java/org/chorem/lima/service/neogia/NeogiaEntryService.java 2014-05-16 08:39:35 UTC (rev 3798) @@ -34,22 +34,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.chorem.lima.dto.AccountDTO; -import org.chorem.lima.dto.EntryDTO; -import org.chorem.lima.dto.StatusDTO; -import org.chorem.lima.dto.TransactionDTO; -import org.chorem.lima.dto.util.DTOHelper; -import org.chorem.lima.service.EntryService; import org.chorem.lima.service.neogia.util.NeogiaUtil; -import org.chorem.lima.service.util.ServiceHelper; -import org.ofbiz.webservice.proxies.*; -import org.ofbiz.webservice.proxies.AddEntryDocument.AddEntry; -import org.ofbiz.webservice.proxies.RemoveEntryDocument.RemoveEntry; -import org.ofbiz.webservice.proxies.UpdateEntryDocument.UpdateEntry; -import org.ofbiz.webservice.wrappers.xsd.AddEntryResult; -import org.ofbiz.webservice.wrappers.xsd.GenericValueGlEntry; -import org.ofbiz.webservice.wrappers.xsd.GenericValueGlEntryAndGlEntryAccount; +import sun.rmi.runtime.Log; +import org.chorem.lima.service.EntryService; + import java.rmi.RemoteException; import java.util.LinkedList; import java.util.List; Modified: trunk/lima-swing/src/main/resources/log4j.properties =================================================================== --- trunk/lima-swing/src/main/resources/log4j.properties 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/lima-swing/src/main/resources/log4j.properties 2014-05-16 08:39:35 UTC (rev 3798) @@ -67,7 +67,7 @@ log4j.logger.org.chorem.lima.business.ui.financialtransaction.FinancialTransactionTableModel=DEBUG log4j.logger.org.chorem.lima.entity.EntryDAOImpl=DEBUG log4j.logger.org.chorem.lima.ui.financialtransaction.FinancialTransactionViewHandler=DEBUG -log4j.logger.org.chorem.lima.entity.FinancialTransactionDAOImpl=DEBUG +log4j.logger.org.chorem.lima.entity.AbstractFinancialTransactionTopiaDao=DEBUG log4j.logger.org.chorem.lima.ui.combobox.FiscalPeriodComboBoxModel=DEBUG log4j.logger.org.chorem.lima.ui.financialtransactionsearch.FinancialTransactionPeriodSearchPanel=DEBUG log4j.logger.org.chorem.lima.ui.financialtransactionsearch.FinancialTransactionSearchViewHandler=DEBUG Modified: trunk/pom.xml =================================================================== --- trunk/pom.xml 2014-05-14 11:51:21 UTC (rev 3797) +++ trunk/pom.xml 2014-05-16 08:39:35 UTC (rev 3798) @@ -167,9 +167,9 @@ <nuitonConfigVersion>3.0-alpha-2</nuitonConfigVersion> <nuitonDecoratorVersion>3.0-alpha-3</nuitonDecoratorVersion> <nuitonProfilingVersion>2.7.1</nuitonProfilingVersion> - <eugenePluginVersion>2.7.4</eugenePluginVersion> + <eugeneVersion>2.8</eugeneVersion> <nuitonI18nVersion>3.1</nuitonI18nVersion> - <topiaVersion>2.9-rc-1</topiaVersion> + <topiaVersion>3.0-beta-3</topiaVersion> <swinglabsVersion>3.0.4</swinglabsVersion> <h2Version>1.3.176</h2Version> @@ -481,7 +481,22 @@ <plugin> <groupId>org.nuiton.eugene</groupId> <artifactId>eugene-maven-plugin</artifactId> - <version>${eugenePluginVersion}</version> + <version>${eugeneVersion}</version> + <configuration> + <resolver>org.nuiton.util.FasterCachedResourceResolver</resolver> + </configuration> + <dependencies> + <!--<dependency>--> + <!--<groupId>org.nuiton.topia</groupId>--> + <!--<artifactId>topia-persistence</artifactId>--> + <!--<version>${topiaVersion}</version>--> + <!--</dependency>--> + <dependency> + <groupId>org.nuiton.topia</groupId> + <artifactId>topia-templates</artifactId> + <version>${topiaVersion}</version> + </dependency> + </dependencies> </plugin> <!-- plugin i18n -->
participants (1)
-
dcosse@users.chorem.org