Author: echatellier Date: 2010-03-23 16:26:54 +0100 (Tue, 23 Mar 2010) New Revision: 2811 Log: Move service implementation into subfolder. Added: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AccountServiceImpl.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/FilesServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/JournalServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/LogServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/PeriodServiceImpl.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/TimeSpanServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/TransactionServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/UserServiceImpl.java Removed: trunk/lima-business/src/main/java/org/chorem/lima/business/AccountServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/EntryServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/FilesServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/JournalServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/LogServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/PeriodServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/ReportServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/TimeSpanServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/TransactionServiceImpl.java trunk/lima-business/src/main/java/org/chorem/lima/business/UserServiceImpl.java Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/AccountService.java trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/AccountService.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/AccountService.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/AccountService.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -18,10 +18,12 @@ package org.chorem.lima.business; +import java.util.List; + import org.chorem.lima.entity.Account; /** - * TODO add comment here. + * Account service. * * @author chatellier * @version $Revision$ @@ -31,5 +33,19 @@ */ public interface AccountService { - public void createAccount(Account account) throws LimaException; + List<Account> getAllAccounts() throws LimaException; + + /** + * Create new account. If {@code masterAccount} is not null, {@code account} + * is added in {@code masterAccount}'s subAccounts. + * + * @param masterAccount master account (can be null) + * @param account account + * @throws LimaException + */ + void createAccount(Account masterAccount, Account account) throws LimaException; + + void updateAccount(Account account) throws LimaException; + + void removeAccount(Account account) throws LimaException; } Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/AccountServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/AccountServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/AccountServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,802 +0,0 @@ -/* - * *##% Callao AccountServiceImpl - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import static org.nuiton.i18n.I18n._; - -import java.util.ArrayList; -import java.util.List; - -import javax.ejb.Stateless; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.entity.Account; -import org.chorem.lima.entity.AccountDAO; -import org.chorem.lima.entity.Entry; -import org.chorem.lima.entity.EntryDAO; -import org.chorem.lima.entity.LimaCallaoDAOHelper; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; - -/** - * 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 - * renseigné si il appartient à un compte père avec le numéro de compte père. - * - * @author Rémi Chapelet - */ -@Stateless -public class AccountServiceImpl implements AccountService { - - private static final Log log = LogFactory.getLog(AccountServiceImpl.class); - - private TopiaContext rootContext; - - //private ConvertAccount convertAccount = new ConvertAccount(); - - public AccountServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - } - - /** - * Permet de créer un nouveau compte dans le PCG de l'application. - * Il ne peut exister deux numéros identiques. Pour chaque nouveau compte, - * il est vérifié si il n'existe pas un compte avec le numéro donné. Dans ce - * cas présent, le compte n'est pas créé. - * ATTENTION : le compte masterAccount, c'est à dire le compte père, doit - * exister, sinon le compte n'est pas créé. Si le compte n'a pas de père, alors - * mettre masterAccount à null. - * - * @param account account to create - * @throws LimaException - */ - public void createAccount(Account account) throws LimaException { - - // test la validite du numero de compte - if (StringUtils.isBlank(account.getAccountNumber())) { - throw new LimaBusinessException("Invalid AccountNumber : " + account.getAccountNumber()); - } - - TopiaContext transaction = null; - try { - // basic check done, make check in database - // TODO move it into JTA - transaction = rootContext.beginTransaction(); - - // test si le numero de compte existe deja - AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(transaction); - List<Account> existingAccounts = accountDAO.findAllByAccountNumber(account.getAccountNumber()); - if (CollectionUtils.isNotEmpty(existingAccounts)) { - throw new LimaBusinessException(_("An account already exists with this number : %s", account.getAccountNumber())); - } - - // test si le compte parent existe - Account masterAcount = account.getMasterAccount(); - if (masterAcount != null) { - accountDAO.update(masterAcount); - } - else { - accountDAO.create(account); - } - - // commit - transaction.commitTransaction(); - } - catch (TopiaException ex) { - if (transaction != null) { - try { - transaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't create account", ex); - } - finally { - if (transaction != null) { - try { - transaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't create account", ex); - } - } - } - } - /*public String createAccount (String accountNumber, String label,Account masterAccount,String type) - { - String result = ServiceHelper.RESPOND_ERROR; - // Détermine si le compte existe déjà ou non - boolean existAccount = existAccount(accountNumber); - // Si le numéro de compte existe - if (existAccount) - { - if (log.isWarnEnabled()) { - log.warn("Le compte numéro "+accountNumber+" existe deja !"); - } - result = ServiceHelper.ACCOUNT_DOUBLE; - } else { - // Création du compte - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(topiaContext); - - //Le compte a un père - - if ( masterAccount != null ) - { - // Vérification que le compte père existe dans la base de données - boolean existMasterAccount = existAccount(masterAccount.getAccountNumber()); - // Si le compte père n'existe pas - if (!existMasterAccount) - { - if (log.isWarnEnabled()) { - log.warn("Le compte père numéro "+accountNumber+" n'existe pas !"); - } - result = ServiceHelper.ACCOUNT_NOT_MASTER; - } else { - // Creation du compte - Account newAccount = accountDAO.create(); - newAccount.setAccountNumber(accountNumber); - newAccount.setLabel(label); - newAccount.setMasterAccount(masterAccount); - newAccount.setType(type); - // Création BDD - topiaContext.commitTransaction(); - result = ServiceHelper.RESPOND_SUCCESS; - } - } else { - // Le compte n'a pas de père - // Creation du compte - Account newAccount = accountDAO.create(); - newAccount.setAccountNumber(accountNumber); - newAccount.setLabel(label); - newAccount.setType(type); - // Création BDD - topiaContext.commitTransaction(); - result = ServiceHelper.RESPOND_SUCCESS; - } - // Fermeture BDD - topiaContext.closeContext(); - }catch (TopiaException e) { - log.error(e); - } - } - return result; - }*/ - - - /* - * Permet de créer un compte à partir du numéro de compte père. Il appelle - * ensuite createAccount avec le compte père. - * @param accountNumber numéro du compte à créer - * @param label label pour le compte - * @param maserAccountNumber numéro du compte père, si il en a pas, mettre 0. - * @return - * - public String createAccount(String accountNumber, String label, - String masterAccountNumber, String type) { - String result = ServiceHelper.RESPOND_ERROR; - // Recherche le compte Master - Account masterAccount = searchAccount(masterAccountNumber); - // Si le compte père n'existe pas - if (masterAccount == null && !masterAccountNumber.equals("0")) { - if (log.isWarnEnabled()) { - log.warn("Le compte père numéro " + masterAccountNumber - + " n'existe pas !"); - } - result = ServiceHelper.ACCOUNT_NOT_MASTER; - } else { - // Création du compte - result = createAccount(accountNumber, label, masterAccount, type); - } - return result; - }*/ - - /* - * Permet de creer un compte à partir d'un objet DTO - * @param accountDTO compte au format DTO - * @return - * - public String createAccount(AccountDTO accountDTO) { - String result; - String result_final; - boolean error = false; // Si il y a eu une erreur pour créer les enfants - - // Création du compte père - result = createAccount(accountDTO.getAccountNumber(), accountDTO - .getLabel(), accountDTO.getMasterAccount(), accountDTO - .getType()); - // Création des comptes enfants - - // Pour chaque enfant - for (AccountDTO accountChildDTO : accountDTO.getAccountChildDTO()) { - // Création de l'enfant - result = createAccount(accountChildDTO); - // Si il y a eu une erreur - if (!result.equals(ServiceHelper.RESPOND_SUCCESS)) { - if (log.isWarnEnabled()) { - log.warn("Le compte numéro " + accountChildDTO.getLabel() - + " n'a pu être créé !"); - } - error = true; - result_final = result; - } - } - // Si il y a eu une erreur lors de la création d'un enfant, il est envoyé une erreur. - if (error) { - result = ServiceHelper.RESPOND_ERROR; - } - return result; - }*/ - - /* - * Recherche un compte DTO. Il est recherché dans la base de données et est - * converti avec ConvertAccount. ConvertAccount recherche dans la liste de - * ses enfants pour les convertir également, et ainsi de suite. - * @param accountNumber numéro du compte qu'on souhait rechercher - * @return - * - public AccountDTO searchAccountDTO(String accountNumber) { - AccountDTO accountDTO = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper - .getAccountDAO(topiaContext); - // Recherche du compte - Account account = accountDAO.findByAccountNumber(accountNumber); - // Converti entity en DTO - convertAccount.setTransaction(topiaContext); - accountDTO = convertAccount.accountEntityToDto(account, null); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return accountDTO; - }*/ - - /* - * Permet de rechercher un compte à partir d'un numéro de compte. - * @param accountNumber numéro du compte à rechercher - * @return - * - public Account searchAccount(String accountNumber) { - Account accountResult = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper - .getAccountDAO(topiaContext); - // Recherche du compte - accountResult = accountDAO.findByAccountNumber(accountNumber); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return accountResult; - }*/ - - /* - * Permet de renvoyer tous les enfants du compte. - * Cette fonction permet de renvoyer les enfants, mais PAS les enfants des - * enfants (et ainsi de suite). Cette méthode descend donc uniquement d'un - * niveau sur la hiérarchie. - * @param account compte dont on souhaite obtenir ses enfants. - * @return - * - public List<Account> searchListChildAccount(Account account) { - List<Account> ListAccount = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper - .getAccountDAO(topiaContext); - // Recherche des comptes enfants - ListAccount = accountDAO.findAllByMasterAccount(account); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return ListAccount; - }*/ - - /* - * Permet de renvoyer tous les enfants du compte. Elle se base sur la fonction - * searchListChildAccount(Account account). - * Cette fonction permet de renvoyer les enfants, mais PAS les enfants des - * enfants (et ainsi de suite). Cette méthode descend donc uniquement d'un - * niveau sur la hiérarchie. - * @param account numéro de compte dont on souhaite obtenir ses enfants. - * @return - * - public List<Account> searchListChildAccount(String accountNumber) { - List<Account> ListAccount = null; - // Recherche le compte - Account account = searchAccount(accountNumber); - // Si le compte n'existe pas - if (account == null) { - if (log.isWarnEnabled()) { - log.warn("Le compte numéro " + accountNumber - + " n'existe pas !"); - } - } else { - // Recherche des comptes enfants - ListAccount = searchListChildAccount(account); - } - return ListAccount; - }*/ - - /** - * Permet de convertir tous les comptes en DTO. Il recherche dans un premier - * temps tous les comptes "master". - * - * @return - * @throws LimaException - */ - public List<Account> getAllAccount() throws LimaException { - /*ArrayList<AccountDTO> listAccountDTO = new ArrayList<AccountDTO>(); - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper - .getAccountDAO(topiaContext); - // Recherche des comptes enfants - List<Account> listAccount = accountDAO.findAll(); - // Pour chaque compte - // Converti entity en DTO - convertAccount.setTransaction(topiaContext); - for (Account account : listAccount) { - // Pour les comptes sans père - if (account.getMasterAccount() == null) { - AccountDTO accountDTO = convertAccount.accountEntityToDto( - account, null); - listAccountDTO.add(accountDTO); - } - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return listAccountDTO;*/ - - List<Account> accountsList = new ArrayList<Account>(); - - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(transaction); - List<Account> accounts = accountDAO.findAll(); - accountsList.addAll(accounts); - - transaction.closeContext(); - } - catch (TopiaException ex) { - if (transaction != null) { - try { - transaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't create account", ex); - } - finally { - if (transaction != null) { - try { - transaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't create account", ex); - } - } - } - - return accountsList; - } - - /* - * Renvoie vrai si le compte avec son numéro existe déjà dans la base de - * données. - * @param accountNumber numéro du compte recherché - * @return - * - public boolean existAccount(String accountNumber) { - // Recherche du compte - Account accountSearch = searchAccount(accountNumber); - boolean result = false; - // Si le compte est trouvé - if (accountSearch != null) { - result = true; - } - return result; - }*/ - - /** - * Permet d'effacer un compte dans la base de données. - * - * Il est vérifié dans un premier temps si le compte existe bien. - * ATTENTION : si il existe une entrée comptable associée au numéro de - * compte, il est alors impossible de supprimer le compte. - * - * @param account - * @throws LimaException - */ - public void removeAccount(Account account) throws LimaException { - /*String result = ServiceHelper.RESPOND_ERROR; - Account deleteAccount = searchAccount(accountNumber); - // Si le compte n'existe pas - if (deleteAccount == null) { - if (log.isWarnEnabled()) { - log.warn("Le compte numéro " + accountNumber - + " n'existe pas !"); - } - result = ServiceHelper.ACCOUNT_NOT_EXIST; - } else // Sinon on efface le compte - { - // Vérifie si une entrée ne possède pas ce numéro de compte. - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryDAO entryDAO = LimaCallaoDAOHelper - .getEntryDAO(topiaContext); - // Recherche au moins une entry avec ce compte. - Entry entry = entryDAO.findByAccount(deleteAccount); - // Il existe au moins une entrée - if (entry != null) { - if (log.isWarnEnabled()) { - log.warn("Le compte numéro " + accountNumber - + " possède des entrées comptable !"); - } - result = ServiceHelper.ACCOUNT_WITH_ENTRIES; - } else { - // On efface tous les comptes enfants - List<Account> listAccountChild = searchListChildAccount(deleteAccount); - boolean ErrorRemoveChild = false; - for (Account accountChild : listAccountChild) { - // Si on souhaite supprimer les comptes enfants - result = removeAccount(accountChild.getAccountNumber()); - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - ErrorRemoveChild = true; - if (log.isErrorEnabled()) { - log.error("Le compte fils numéro " - + accountChild.getAccountNumber() - + " n'a pas été supprimé !"); - } - } - // - // Si on ne souhaite pas supprimer les comptes enfants, tous les - // comptes enfants se retrouvent sans père. Commenter removeAccountChildTest - // dans le fichier AccountServiceImplTest dans ce cas. - - //modifyAccount(accountChild.getAccountNumber(),accountChild.getLabel(),null); - } - // Si il n'a jamais eu d'erreur pour supprimer ses fils - if (!ErrorRemoveChild) { - - //// Efface le compte père - - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper - .getAccountDAO(topiaContext); - // Supprime le compte - accountDAO.delete(deleteAccount); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - result = ServiceHelper.RESPOND_SUCCESS; - if (log.isInfoEnabled()) { - log.info("Le compte numéro " + accountNumber - + " a ete supprimé avec succès."); - } - } - } - } catch (TopiaException e) { - log.error(e); - } - } - return result;*/ - - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - // Vérifie si une entrée ne possède pas ce numéro de compte. - // FIXME !IMPORTANT! check that subaccounts have no entries too - EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(transaction); - Entry firstEntry = entryDAO.findByAccount(account); - - if (firstEntry != null) { - throw new LimaBusinessException("Can't delete account with entries"); - } - - // remove account - // FIXME !IMPORTANT! check that subaccounts are also deleted - AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(transaction); - accountDAO.delete(account); - - transaction.closeContext(); - } - catch (TopiaException ex) { - if (transaction != null) { - try { - transaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't delete account", ex); - } - finally { - if (transaction != null) { - try { - transaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't delete account", ex); - } - } - } - } - - /* - * Permet d'effacer un compte à partir d'un compte DTO. Il appelle la - * méthode removeAccount, qui effacera également les enfants (et ainsi de - * suite dans la hiérarchie du compte). - * @param accountDTO Compte au format DTO qu'on souhaite supprimer. - * @return - * - public String removeAccount(AccountDTO accountDTO) { - String result; - result = removeAccount(accountDTO.getAccountNumber()); - return result; - }*/ - - /** - * Permet de modifier un compte sur son label et son compte père. - * - * 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 accountNumber numéro de compte à modifier - * @param label label à modifier - * @param masterAccountNumber compte père à modifier - - * @throws LimaException - */ - public void modifyAccount(Account account) throws LimaException { - /*String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper - .getAccountDAO(topiaContext); - // Recherche du compte - Account modifyAccount = accountDAO - .findByAccountNumber(accountNumber); - // Si le compte n'existe pas - if (modifyAccount == null) { - if (log.isWarnEnabled()) { - log.warn("Le compte numéro " + accountNumber - + " n'existe pas !"); - } - result = ServiceHelper.ACCOUNT_NOT_EXIST; - } else { - - // Modifie le compte - modifyAccount.setLabel(label); - modifyAccount.setType(type); - // Recherche du compte père - // Si il possède un compte père - if (masterAccount != null) { - modifyAccount.setMasterAccount(masterAccount); - } - modifyAccount.update(); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - result = ServiceHelper.RESPOND_SUCCESS; - } - } catch (TopiaException e) { - log.error(e); - } - return result;*/ - - TopiaContext transaction = null; - try { - transaction = rootContext.beginTransaction(); - - // update account - AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(transaction); - accountDAO.update(account); - - transaction.closeContext(); - } - catch (TopiaException ex) { - if (transaction != null) { - try { - transaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't update account", ex); - } - finally { - if (transaction != null) { - try { - transaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't update account", ex); - } - } - } - } - - /* - * Permet de modifier un compte sur son label et son compte père. - * Il recherche le compte père avec le numéro de compte fourni. Appel ensuite - * la méthode modifyAccount avec pour paramètre le compte père trouvé. - * @param accountNumber numéro de compte à modifier - * @param label label à modifier - * @param masterAccountNumber le numéro du compte père - * @return - * - public String modifyAccount(String accountNumber, String label, - String type, String masterAccountNumber) { - String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper - .getAccountDAO(topiaContext); - - // Modifie le compte - // Recherche du compte père - Account masterAccount = accountDAO - .findByAccountNumber(masterAccountNumber); - result = modifyAccount(accountNumber, label, type, masterAccount); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result; - }*/ - - /* - * Permet de modifier un compte à partir d'un compte DTO. - * @param accountDTO compte au format DTO qu'on souhaire modifier. - * @return - * - public String modifyAccount(AccountDTO accountDTO) { - String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - AccountDAO accountDAO = LimaCallaoDAOHelper - .getAccountDAO(topiaContext); - // Recherche du compte père - Account masterAccount = accountDAO.findByAccountNumber(accountDTO - .getMasterAccount()); - result = modifyAccount(accountDTO.getAccountNumber(), accountDTO - .getLabel(), accountDTO.getType(), masterAccount); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result; - }*/ - - /* - * Permet de mettre à jour le compte DTO ainsi que tous ses fils. - * Cette méthode permet d'ajouter, modifier, et supprimer un compte et - * ses enfants (et ainsi de suite). - * @param accountDTO - * @return - * - public String updateDTO(AccountDTO accountDTO) { - String result; - // Si le compte DTO père existe - if (existAccount(accountDTO.getAccountNumber())) { - // Modification du compte père - result = modifyAccount(accountDTO); - } else { - // Création du compte père - result = createAccount(accountDTO); - } - // Pour chaque enfant on lance l'update - for (AccountDTO accountChildDTO : accountDTO.getAccountChildDTO()) { - updateDTO(accountChildDTO); - } - - // On recherche les comptes DTO effacés - List<Account> listAccountChild = searchListChildAccount(accountDTO - .getAccountNumber()); - for (Account account : listAccountChild) { - // Si le compte n'est pas dans la liste, alors on efface - if (!accountDTO.existAccountChild(account.getAccountNumber())) { - result = removeAccount(account.getAccountNumber()); - } - } - return result; - }*/ - -} \ No newline at end of file Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/EntryServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/EntryServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/EntryServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,381 +0,0 @@ -/* - * *##% Callao EntryServiceImpl - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.entity.Entry; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaNotFoundException; - -/** - * Cette classe permet de contrôler les différentes saisies possibles dans - * Callao. Ces saisies sont transmises à la base de données par la classe - * Entry. Chaque action sur une entrée déclenche une création d'un log. - * Chaque opération comptable doit faire appel également au contrôl de la - * période comptable sur laquelle l'entry repose. Ainsi il n'est possible - * d'ajouter/modifier/supprimer une entrée si la période est bloquée. - * - * @author Rémi Chapelet - */ -public class EntryServiceImpl { // implements EntryService { - - private static final Log log = LogFactory.getLog(EntryServiceImpl.class); - - private TopiaContext rootContext; - - private LogServiceImpl logServiceImpl = new LogServiceImpl(); - - // TODO A revoir car transaction a besoin de entry et vice versa - private static TransactionServiceImpl transactionServiceImpl = new TransactionServiceImpl(); - - private AccountServiceImpl accountServiceImpl = new AccountServiceImpl(); - - public EntryServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - } - - /** - * Création d'une entrée comptable. - * La période ne doit PAS être bloquée. - * - * @return - */ - public void createEntry(Entry entry /*String description, String amount, boolean debit, - String lettering, String detail, Transaction transaction, - Account account*/) { - /*String result = isCorrectEntry(transaction, account); - if (result.equals(ServiceHelper.RESPOND_SUCCESS)) { - result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryDAO entryDAO = LimaCallaoDAOHelper - .getEntryDAO(topiaContext); - // Creation de l'entrée comptable - Entry newEntry = entryDAO.create(); - newEntry.setDescription(description); - // On formate le nombre - newEntry.setAmount(numberUtil.format(amount)); - newEntry.setDebit(debit); - newEntry.setLettering(lettering); - newEntry.setDetail(detail); - newEntry.setTransaction(transaction); - newEntry.setAccount(account); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - if (log.isInfoEnabled()) { - log.info("Ajout avec succes de l'entrée comptable."); - } - // Création du log - Date logDate = new Date(); - logServiceImpl.addLog(logDate, transaction.getTransDate(), - ServiceHelper.LOG_ADD, transaction.getVoucherRef(), - transaction.getDescription(), detail, amount, debit, - lettering); - - // Il renvoie soit l'identifiant topiaId ou SUCCESS. - result = newEntry.getTopiaId(); - //result = ServiceHelper.RESPOND_SUCCESS; - } catch (TopiaException e) { - log.error(e); - } - } - return result;*/ - } - - /* - * Permet de créer une entrée comptable à partir de son DTO. - * @param entryDTO - * @return - * - public String createEntry(EntryDTO entryDTO) { - // Recherche TransactionDTO - TransactionDTO transactonDTO = entryDTO.getTransactionDTO(); - Transaction transaction = transactionServiceImpl - .searchTransactionWithTopiaId(transactonDTO); - // Recherche AccountDTO - AccountDTO accountDTO = entryDTO.getAccountDTO(); - Account account = accountServiceImpl.searchAccount(accountDTO - .getAccountNumber()); - // Création entry - String result = createEntry(entryDTO.getDescription(), entryDTO - .getAmount(), entryDTO.isDebit(), entryDTO.getLettering(), - entryDTO.getDetail(), transaction, account); - return result; - }*/ - - /* - * Vérifie que les objets transaction et account ne sont pas nulls. - * @param transaction - * @param account - * @return - * - public String isCorrectEntry(Transaction transaction, Account account) { - String result = ServiceHelper.RESPOND_SUCCESS; - // Vérification si timeSpan et Journal existe bien - if (account == null) { - if (log.isErrorEnabled()) { - log.error("Création entry : Le account n'existe pas."); - } - result = ServiceHelper.ACCOUNT_NOT_EXIST; - } - if (transaction == null) { - if (log.isErrorEnabled()) { - log.error("Création entry : La transaction n'existe pas."); - } - result = ServiceHelper.TRANSACTION_NOT_EXIST; - } - return result; - }*/ - - /* - * Recherche toutes les entrées comptables d'une transaction. - * @param transaction - * @return - * - public List<Entry> searchEntryWithTransaction(Transaction transaction) { - List<Entry> listEntry = null; - if (transaction != null) { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryDAO entryDAO = LimaCallaoDAOHelper - .getEntryDAO(topiaContext); - // Recherche - listEntry = entryDAO.findAllByTransaction(transaction); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - } - return listEntry; - }*/ - - /* - * Recherche toutes les entrées comptables d'une transaction, et renvoie - * au format DTO. - * @param transaction - * @return - * - public List<EntryDTO> searchEntryDTOWithTransaction(Transaction transaction) { - List<EntryDTO> listEntryDTO = new ArrayList<EntryDTO>(); - // Si la transaction est trouvée - if (transaction != null) { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryDAO entryDAO = LimaCallaoDAOHelper - .getEntryDAO(topiaContext); - // Recherche toutes les entrées comptables de la transaction - List<Entry> listEntry = entryDAO - .findAllByTransaction(transaction); - // Pour chaque entry, on fait appel au convertisseur pour avoir en DTO - convertEntry.setTransaction(topiaContext); - for (Entry entry : listEntry) { - EntryDTO entryDTO = convertEntry.entryEntityToDto(entry); - // On ajoute le nouvel DTO - listEntryDTO.add(entryDTO); - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - } - return listEntryDTO; - }*/ - - /* - * Recherche les entrées comptables pour une transaction donnée au format DTO. - * @param transactionTopiaId identifiant de la transaction - * @return - * - public List<EntryDTO> searchEntryDTOWithTransaction( - String transactionTopiaId) { - List<EntryDTO> listEntryDTO = new ArrayList<EntryDTO>(); - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); - // Recherche de la transaction - Transaction transaction = transactionServiceImpl - .searchTransactionWithTopiaId(transactionTopiaId); - // Si la transaction est trouvée - if (transaction != null) { - // Recherche toutes les entrées comptables de la transaction - List<Entry> listEntry = entryDAO - .findAllByTransaction(transaction); - // Pour chaque entry, on fait appel au convertisseur pour avoir en DTO - convertEntry.setTransaction(topiaContext); - for (Entry entry : listEntry) { - EntryDTO entryDTO = convertEntry.entryEntityToDto(entry); - // On ajoute l'entrée DTO - listEntryDTO.add(entryDTO); - } - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return listEntryDTO; - }*/ - - /* - * Recherche les entrées comptables pour une transaction donnée au format DTO. - * @param transactionDTO - * @return - * - public List<EntryDTO> searchEntryDTOWithTransaction( - TransactionDTO transactionDTO) { - List<EntryDTO> listEntryOfTransaction = searchEntryDTOWithTransaction(transactionDTO - .getId()); - return listEntryOfTransaction; - }*/ - - /* - * Permet d'effacer une entrée comptable à partir de son identifiant topia. - * @param topiaId - * @return - * - public String removeEntry(String topiaId) { - String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); - // Recherche de l'entry - Entry entryDelete = entryDAO.findByTopiaId(topiaId); - // Si l'entry existe alors on supprime - if (entryDelete != null) { - // Supprime - entryDAO.delete(entryDelete); - // Création BDD - topiaContext.commitTransaction(); - result = ServiceHelper.RESPOND_SUCCESS; - } else { - result = ServiceHelper.ENTRY_NOT_EXIST; - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result; - }*/ - - /* - * Permet d'effacer une entrée comptable au format DTO. - * @param entryDTO - * @return - * - public String removeEntry(EntryDTO entryDTO) { - String result = removeEntry(entryDTO.getId()); - return result; - }*/ - - /* - * Modification d'une entrée comptable. - * @param topiaId - * @param description - * @param amount - * @param debit - * @param lettering - * @param detail - * @param transaction - * @param account - * @return - * - public String modifyEntry(String topiaId, String description, - String amount, boolean debit, String lettering, String detail, - Account account) { - String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); - // Recherche Entry - Entry entry = entryDAO.findByTopiaId(topiaId); - entry.setDescription(description); - // On formate le nombre - entry.setAmount(numberUtil.format(amount)); - entry.setDebit(debit); - entry.setLettering(lettering); - entry.setDetail(detail); - entry.setAccount(account); - entry.update(); - // Création BDD - topiaContext.commitTransaction(); - // Chargement DAO transaction - Transaction transaction = entry.getTransaction(); - if (log.isInfoEnabled()) { - log.info("Edit avec succes de l'entrée comptable."); - } - // Création du log - Date logDate = new Date(); - logServiceImpl.addLog(logDate, transaction.getTransDate(), - ServiceHelper.LOG_MODIFY, transaction.getVoucherRef(), - transaction.getDescription(), detail, amount, debit, - lettering); - result = ServiceHelper.RESPOND_SUCCESS; - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result; - }*/ - - /* - * Permet de modifier une entrée comptable. - * @param entryDTO - * @return - * - public String modifyEntry(EntryDTO entryDTO) { - // Recherche AccountDTO - AccountDTO accountDTO = entryDTO.getAccountDTO(); - Account account = accountServiceImpl.searchAccount(accountDTO - .getAccountNumber()); - // Modification entry - String result = modifyEntry(entryDTO.getId(), - entryDTO.getDescription(), entryDTO.getAmount(), entryDTO - .isDebit(), entryDTO.getLettering(), entryDTO - .getDetail(), account); - return result; - }*/ -} Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/FilesServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/FilesServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/FilesServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,667 +0,0 @@ -/* - * *##% Callao FilesServiceImpl - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.business.dto.AccountDTO; -import org.chorem.lima.business.dto.EntryDTO; -import org.chorem.lima.business.dto.JournalDTO; -import org.chorem.lima.business.dto.PeriodDTO; -import org.chorem.lima.business.dto.TimeSpanDTO; -import org.chorem.lima.business.dto.TransactionDTO; -import org.chorem.lima.business.utils.DateUtil; -import org.chorem.lima.business.utils.ServiceHelper; -import org.jdom.Attribute; -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jdom.input.SAXBuilder; -import org.jdom.output.Format; -import org.jdom.output.XMLOutputter; -import org.jdom.xpath.XPath; -import org.nuiton.topia.TopiaContext; - -/** - * Cette classe permet d'importer et exporter des données comptables. Ces données - * sont au format xml. - * - * @author Rémi Chapelet - */ -public class FilesServiceImpl { // implements FilesService { - - /** - * log - */ - private static final Log log = LogFactory.getLog(FilesServiceImpl.class); - - static Element racine = new Element("Callao"); - - static org.jdom.Document document = new Document(racine); - - private static DateUtil dateUtil = new DateUtil(); - - private AccountServiceImpl accountServiceImpl = new AccountServiceImpl(); - - private EntryServiceImpl entryServiceImpl = new EntryServiceImpl(); - - private JournalServiceImpl journalServiceImpl = new JournalServiceImpl(); - - private PeriodServiceImpl periodServiceImpl = new PeriodServiceImpl(); - - private TimeSpanServiceImpl timeSpanServiceImpl = new TimeSpanServiceImpl(); - - private TransactionServiceImpl transactionServiceImpl = new TransactionServiceImpl(); - - /** - * Cete méthode permet d'exporter des données de Callao vers un fichier au - * format xml. - * - * @param nameFile - */ - public void exportDatas(String nameFile) { - /*if (log.isDebugEnabled()) { - log.debug("Save file XML : "); - } - - // Partie Informations - Element info = new Element("informations"); - racine.addContent(info); - Attribute date = new Attribute("date", new Date().toString()); - info.setAttribute(date); - Attribute user = new Attribute("user", "Name user"); - info.setAttribute(user); - Attribute company = new Attribute("company", "Name company"); - info.setAttribute(company); - - // Partie Save - - // Création Element save - Element save = new Element("save"); - racine.addContent(save); - - // Period - - // Création élément liste de périods - Element periods = new Element("periods"); - // Création élément liste de timespans - Element timeSpans = new Element("timespans"); - save.addContent(periods); - save.addContent(timeSpans); - // Recherche de la liste de toutes les périodes et leurs timeSpans en DTO - List<PeriodDTO> listPeriodDTO = periodServiceImpl.getAllPeriod(); - // Pour chaque période - for (PeriodDTO periodDTO : listPeriodDTO) { - // Création élément périod - Element period = new Element("period"); - periods.addContent(period); - // Identifiant période - Attribute id = new Attribute("id", periodDTO.getId()); - period.setAttribute(id); - // BeginPeriod - // Découpage date - String dateTab[] = dateUtil.arrayDate(periodDTO.getBeginPeriod()); - Attribute beginYear = new Attribute("beginYear", dateTab[0]); - period.setAttribute(beginYear); - Attribute beginMonth = new Attribute("beginMonth", dateTab[1]); - period.setAttribute(beginMonth); - Attribute beginDay = new Attribute("beginDay", dateTab[2]); - period.setAttribute(beginDay); - // EndPeriod - dateTab = dateUtil.arrayDate(periodDTO.getEndPeriod()); - Attribute endYear = new Attribute("endYear", dateTab[0]); - period.setAttribute(endYear); - Attribute endMonth = new Attribute("endMonth", dateTab[1]); - period.setAttribute(endMonth); - Attribute endDay = new Attribute("endDay", dateTab[2]); - period.setAttribute(endDay); - // Locked Period - if (periodDTO.isLocked()) { - Attribute locked = new Attribute("locked", "true"); - period.setAttribute(locked); - } else { - Attribute locked = new Attribute("locked", "false"); - period.setAttribute(locked); - } - - // TimeSpan - - // Recherche des timeSpans de la période - List<TimeSpanDTO> listTimeSpanDTO = periodDTO.getListTimeSpan(); - // Pour chaque timeSpan - for (TimeSpanDTO timeSpanDTO : listTimeSpanDTO) { - Element timeSpan = new Element("timespan"); - timeSpans.addContent(timeSpan); - // Identifiant timeSpan - Attribute idTimeSpan = new Attribute("id", timeSpanDTO.getId()); - timeSpan.setAttribute(idTimeSpan); - Attribute idPeriod = new Attribute("idPeriod", periodDTO - .getId()); - timeSpan.setAttribute(idPeriod); - // Begin TimeSpan - // Découpage date - dateTab = dateUtil.arrayDate(timeSpanDTO.getBeginTimeSpan()); - Attribute beginYearTimeSpan = new Attribute("beginYear", - dateTab[0]); - timeSpan.setAttribute(beginYearTimeSpan); - Attribute beginMonthTimeSpan = new Attribute("beginMonth", - dateTab[1]); - timeSpan.setAttribute(beginMonthTimeSpan); - Attribute beginDayTimeSpan = new Attribute("beginDay", - dateTab[2]); - timeSpan.setAttribute(beginDayTimeSpan); - // End TimeSpan - dateTab = dateUtil.arrayDate(timeSpanDTO.getEndTimeSpan()); - Attribute endYearTimeSpan = new Attribute("endYear", dateTab[0]); - timeSpan.setAttribute(endYearTimeSpan); - Attribute endMonthTimeSpan = new Attribute("endMonth", - dateTab[1]); - timeSpan.setAttribute(endMonthTimeSpan); - Attribute endDayTimeSpan = new Attribute("endDay", dateTab[2]); - timeSpan.setAttribute(endDayTimeSpan); - // Lock timeSpan - if (timeSpanDTO.isLocked()) { - Attribute locked = new Attribute("locked", "true"); - timeSpan.setAttribute(locked); - } else { - Attribute locked = new Attribute("locked", "false"); - timeSpan.setAttribute(locked); - } - } - } - - // Journal - - Element journals = new Element("journals"); - save.addContent(journals); - List<JournalDTO> listJournalDTO = journalServiceImpl.getAllJournal(); - for (JournalDTO journalDTO : listJournalDTO) { - Element journal = new Element("journal"); - journals.addContent(journal); - // Identification du journal - Attribute idJournal = new Attribute("id", journalDTO.getId()); - journal.setAttribute(idJournal); - // Label - Attribute label = new Attribute("label", journalDTO.getLabel()); - journal.setAttribute(label); - // Prefix - Attribute prefix = new Attribute("prefix", journalDTO.getPrefix()); - journal.setAttribute(prefix); - // Description - Attribute description = new Attribute("description", journalDTO - .getDescription()); - journal.setAttribute(description); - } - - // Account - - Element accounts = new Element("accounts"); - save.addContent(accounts); - List<AccountDTO> listAccountDTO = accountServiceImpl.getAllAccount(); - // Appel une fonction récursive pour parcourir l'arborescence des comptes - accountXML(listAccountDTO, accounts); - - // Transaction - Element transactions = new Element("transactions"); - save.addContent(transactions); - Element entries = new Element("entries"); - save.addContent(entries); - // Recherche de toutes les transactions - List<TransactionDTO> listTransactionDTO = transactionServiceImpl - .getAllTransactionDTO(); - // Pour chaque transaction - for (TransactionDTO transactionDTO : listTransactionDTO) { - Element transaction = new Element("transaction"); - transactions.addContent(transaction); - // Identification de la transaction - Attribute idTransaction = new Attribute("id", transactionDTO - .getId()); - transaction.setAttribute(idTransaction); - // EntryDate - String dateTab[] = dateUtil - .arrayDate(transactionDTO.getEntryDate()); - Attribute entryDateYear = new Attribute("entryDateYear", dateTab[0]); - transaction.setAttribute(entryDateYear); - Attribute entryDateMonth = new Attribute("entryDateMonth", - dateTab[1]); - transaction.setAttribute(entryDateMonth); - Attribute entryDateDay = new Attribute("entryDateDay", dateTab[2]); - transaction.setAttribute(entryDateDay); - // VoucherRef - Attribute voucherRef = new Attribute("voucherRef", transactionDTO - .getVoucherRef()); - transaction.setAttribute(voucherRef); - // Description - Attribute description = new Attribute("description", transactionDTO - .getDescription()); - transaction.setAttribute(description); - // Id journal - Attribute IdJournal = new Attribute("idJournal", transactionDTO - .getJournalDTO().getId()); - transaction.setAttribute(IdJournal); - // Id timeSpan - Attribute IdTimeSpan = new Attribute("idTimeSpan", transactionDTO - .getTimeSpanDTO().getId()); - transaction.setAttribute(IdTimeSpan); - - // Entry - List<EntryDTO> listEntryDTO = entryServiceImpl - .searchEntryDTOWithTransaction(transactionDTO); - for (EntryDTO entryDTO : listEntryDTO) { - Element entry = new Element("entry"); - entries.addContent(entry); - // Identification du entry - Attribute idEntry = new Attribute("id", entryDTO.getId()); - entry.setAttribute(idEntry); - // Description - Attribute descriptionEntry = new Attribute("description", - entryDTO.getDescription()); - entry.setAttribute(descriptionEntry); - // Amount - Attribute amount = new Attribute("amount", entryDTO.getAmount()); - entry.setAttribute(amount); - // Lettering - Attribute lettering = new Attribute("lettering", entryDTO - .getLettering()); - entry.setAttribute(lettering); - // Detail - Attribute detail = new Attribute("detail", entryDTO.getDetail()); - entry.setAttribute(detail); - // Debit / crédit - if (entryDTO.isDebit()) { - Attribute debit = new Attribute("debit", "true"); - entry.setAttribute(debit); - } else { - Attribute debit = new Attribute("debit", "false"); - entry.setAttribute(debit); - } - // Transaction - Attribute idrefTransaction = new Attribute("idTransaction", - transactionDTO.getId()); - entry.setAttribute(idrefTransaction); - // Account - Attribute idAccount = new Attribute("idAccount", entryDTO - .getAccountDTO().getId()); - entry.setAttribute(idAccount); - } - } - //affiche(); - enregistre(nameFile); - return ServiceHelper.RESPOND_SUCCESS;*/ - } - - /** - * Converti la liste des comptes pour être ajouté au document xml. - * @param listAccountDTO - * @param accounts - */ - protected void accountXML(List<AccountDTO> listAccountDTO, Element accounts) { - /*for (AccountDTO accountDTO : listAccountDTO) { - Element account = new Element("account"); - accounts.addContent(account); - // Identification du account - Attribute idAccount = new Attribute("id", accountDTO.getId()); - account.setAttribute(idAccount); - // Label - Attribute label = new Attribute("label", accountDTO.getLabel()); - account.setAttribute(label); - // Type - Attribute type = new Attribute("type", accountDTO.getType()); - account.setAttribute(type); - // AccountNumber - Attribute accountNumber = new Attribute("accountNumber", accountDTO - .getAccountNumber()); - account.setAttribute(accountNumber); - // MasterAccountNumber - Attribute masterAccountNumber = new Attribute("masterAccount", - accountDTO.getMasterAccount()); - account.setAttribute(masterAccountNumber); - // Ajoute les comptes enfants à la liste - accountXML(accountDTO.getAccountChildDTO(), accounts); - }*/ - } - - // Affiche le fichier xml - /*static void affiche() { - try { - XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); - sortie.output(document, System.out); - } catch (java.io.IOException e) { - } - }*/ - - /** - * Permet d'enregistrer le fichier xml. - * @param fichier - */ - /*static void enregistre(String fichier) { - try { - XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); - sortie.output(document, new FileOutputStream(fichier)); - } catch (java.io.IOException e) { - } - }*/ - - /** - * Permet d'importer un fichier de données au format xml dans Callao. Si le - * fichier n'est pas disponible, il est alors renvoyé un message d'erreur. - * @param file - * @return - */ - public void importDatas(String file) { - /*if (log.isDebugEnabled()) { - log.debug("Load file XML : "); - } - String result = ServiceHelper.RESPOND_ERROR; - boolean existError = false; - - - // Chargement du fichier et construction du Dom - try { - // On crée une instance de SAXBuilder - SAXBuilder sxb = new SAXBuilder(); - document = sxb.build(file); - } catch (IOException e) { - log.error("Erreur lors de la lecture du fichier " + e.getMessage()); - e.printStackTrace(); - } catch (JDOMException e) { - log.error("Erreur lors de la construction du fichier JDOM " - + e.getMessage()); - e.printStackTrace(); - } - - - // Ecriture dans la base de données - try { - // Recherche de la racine - Element racine = document.getRootElement(); - - // Journal - XPath requeteXpath = XPath.newInstance("//journal"); - List results = requeteXpath.selectNodes(racine); - - Iterator iter = results.iterator(); - // Pour tous les journaux - while (iter.hasNext()) { - Element noeudCourant = (Element) iter.next(); - // Recherche attributs - String label = noeudCourant.getAttribute("label").getValue(); - String prefix = noeudCourant.getAttribute("prefix").getValue(); - String description = noeudCourant.getAttribute("description") - .getValue(); - // Création bdd - result = journalServiceImpl.createJournal(label, prefix, - description); - // Control erreur - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - existError = true; - } - } - - // Account - requeteXpath = XPath.newInstance("//account"); - results = requeteXpath.selectNodes(racine); - - iter = results.iterator(); - // Pour tous les accounts - while (iter.hasNext()) { - Element noeudCourant = (Element) iter.next(); - // Recherche attributs - String label = noeudCourant.getAttribute("label").getValue(); - String accountNumber = noeudCourant.getAttribute( - "accountNumber").getValue(); - String masterAccount = noeudCourant.getAttribute( - "masterAccount").getValue(); - String typeAccount = noeudCourant.getAttribute("type") - .getValue(); - // Création bdd - result = accountServiceImpl.createAccount(accountNumber, label, - masterAccount, typeAccount); - // Control erreur - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - existError = true; - } - } - - // Period - requeteXpath = XPath.newInstance("//period"); - results = requeteXpath.selectNodes(racine); - - iter = results.iterator(); - // Pour tous les periods - while (iter.hasNext()) { - Element noeudCourant = (Element) iter.next(); - // Recherche attributs - String idPeriod = noeudCourant.getAttribute("id").getValue(); - int year = Integer.parseInt(noeudCourant.getAttribute( - "beginYear").getValue()); - int month = Integer.parseInt(noeudCourant.getAttribute( - "beginMonth").getValue()); - int day = Integer.parseInt(noeudCourant - .getAttribute("beginDay").getValue()); - Date beginPeriod = new Date(year - 1900, month, day); - year = Integer.parseInt(noeudCourant.getAttribute("endYear") - .getValue()); - month = Integer.parseInt(noeudCourant.getAttribute("endMonth") - .getValue()); - day = Integer.parseInt(noeudCourant.getAttribute("endDay") - .getValue()); - Date endPeriod = new Date(year - 1900, month, day); - // Création bdd - result = periodServiceImpl.createPeriod(beginPeriod, endPeriod, - false); - // Control erreur - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - existError = true; - } - - // Transaction - requeteXpath = XPath - .newInstance("//transaction[@idTimeSpan=//timespan[@idPeriod='" - + idPeriod + "']/@id]"); - List resultsTransaction = requeteXpath.selectNodes(racine); - Iterator iterTrans = resultsTransaction.iterator(); - // Pour tous les transactions - while (iterTrans.hasNext()) { - Element noeudCourantTrans = (Element) iterTrans.next(); - - // Recherche attributs - - // Id transaction XMl - String idTransactionXML = noeudCourantTrans.getAttribute( - "id").getValue(); - // Recherche du journal en DTO - String idJournal = noeudCourantTrans.getAttribute( - "idJournal").getValue(); - requeteXpath = XPath.newInstance("//journal[@id='" - + idJournal + "']/@label"); - String label = requeteXpath.valueOf(racine); - JournalDTO journalDTO = journalServiceImpl - .searchJournalDTOWithLabel(label); - // Recherche du timeSpan en DTO - String idtimeSpan = noeudCourantTrans.getAttribute( - "idTimeSpan").getValue(); - requeteXpath = XPath.newInstance("//timespan[@id='" - + idtimeSpan + "']/@beginYear"); - year = Integer.parseInt(requeteXpath.valueOf(racine)); - requeteXpath = XPath.newInstance("//timespan[@id='" - + idtimeSpan + "']/@beginMonth"); - month = Integer.parseInt(requeteXpath.valueOf(racine)); - requeteXpath = XPath.newInstance("//timespan[@id='" - + idtimeSpan + "']/@beginDay"); - day = Integer.parseInt(requeteXpath.valueOf(racine)); - Date beginTimeSpan = new Date(year - 1900, month, day); - TimeSpanDTO timeSpanDTO = timeSpanServiceImpl - .searchTimeSpanDTOByDate(beginTimeSpan); - - // Création de transaction DTO - TransactionDTO transactionDTO = new TransactionDTO(); - transactionDTO.setJournalDTO(journalDTO); - transactionDTO.setTimeSpanDTO(timeSpanDTO); - // entryDate - year = Integer.parseInt(noeudCourantTrans.getAttribute( - "entryDateYear").getValue()); - month = Integer.parseInt(noeudCourantTrans.getAttribute( - "entryDateMonth").getValue()); - day = Integer.parseInt(noeudCourantTrans.getAttribute( - "entryDateDay").getValue()); - Date entryDate = new Date(year - 1900, month, day); - transactionDTO.setEntryDate(entryDate); - // voucherRef - String voucherRef = noeudCourantTrans.getAttribute( - "voucherRef").getValue(); - transactionDTO.setVoucherRef(voucherRef); - // description - String description = noeudCourantTrans.getAttribute( - "description").getValue(); - transactionDTO.setDescription(description); - - // Création bdd - String idTransactionCallao = transactionServiceImpl - .createTransaction(transactionDTO); - - // Entry - requeteXpath = XPath.newInstance("//entry[@idTransaction='" - + idTransactionXML + "']"); - List resultsEntry = requeteXpath.selectNodes(racine); - - Iterator iterEntry = resultsEntry.iterator(); - // Pour tous les entries - while (iterEntry.hasNext()) { - Element noeudEntry = (Element) iterEntry.next(); - - // Recherche attributs - - // Transaction DTO - transactionDTO = transactionServiceImpl - .searchTransactionDTO(idTransactionCallao); - // Account DTO - String idAccount = noeudEntry.getAttribute("idAccount") - .getValue(); - requeteXpath = XPath.newInstance("//account[@id='" - + idAccount + "']/@accountNumber"); - String accountNumber = requeteXpath.valueOf(racine); - AccountDTO accountDTO = accountServiceImpl - .searchAccountDTO(accountNumber); - // Entry DTO - EntryDTO entryDTO = new EntryDTO(); - entryDTO.setAccountDTO(accountDTO); - entryDTO.setTransactionDTO(transactionDTO); - // Description - description = noeudEntry.getAttribute("description") - .getValue(); - entryDTO.setDescription(description); - // Amount - String amount = noeudEntry.getAttribute("amount") - .getValue(); - entryDTO.setAmount(amount); - // Debit - boolean debit = noeudEntry.getAttribute("debit") - .getValue().equals("true"); - entryDTO.setDebit(debit); - // Lettering - String lettering = noeudEntry.getAttribute("lettering") - .getValue(); - entryDTO.setLettering(lettering); - // Detail - String detail = noeudEntry.getAttribute("detail") - .getValue(); - entryDTO.setDetail(detail); - // Création bdd - result = transactionServiceImpl.addEntry(entryDTO); - // Control erreur - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - existError = true; - } - } - } - - - // Bloquer Period - boolean lock = noeudCourant.getAttribute("locked").getValue() - .equals("true"); - // Si la période est bloquée - if (lock) { - // Bloque tous ses timeSpans - result = periodServiceImpl - .blockAllTimeSpanOfPeriod(periodServiceImpl - .searchPeriodWithDate(beginPeriod)); - // Control erreur - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - existError = true; - } - // bloque la période - result = periodServiceImpl.blockPeriod(periodServiceImpl - .searchPeriodWithDate(beginPeriod)); - - } else { - // On regarde si il y a besoin de bloquer les timeSpans - requeteXpath = XPath.newInstance("//timespan[@idPeriod = '" - + idPeriod + "']"); - List resultsTimeSpan = requeteXpath.selectNodes(racine); - Iterator iterTimeSpan = resultsTimeSpan.iterator(); - // Pour tous les timeSpans - while (iterTimeSpan.hasNext()) { - Element noeudCourantTimeSpan = (Element) iterTimeSpan - .next(); - // Recherche attributs - year = Integer.parseInt(noeudCourantTimeSpan - .getAttribute("beginYear").getValue()); - month = Integer.parseInt(noeudCourantTimeSpan - .getAttribute("beginMonth").getValue()); - day = Integer.parseInt(noeudCourantTimeSpan - .getAttribute("beginDay").getValue()); - Date beginTimeSpan = new Date(year - 1900, month, day); - lock = noeudCourantTimeSpan.getAttribute("locked") - .getValue().equals("true"); - // Bloque le timeSpan - if (lock) { - timeSpanServiceImpl - .blockTimeSpan(timeSpanServiceImpl - .searchTimeSpanByDate(beginTimeSpan)); - } - // Control erreur - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - existError = true; - } - } - } - - } - - } catch (JDOMException e) { - log.error("Erreur JDOM " + e.getMessage()); - e.printStackTrace(); - } - - // Détection des erreurs - if (!existError) { - result = ServiceHelper.RESPOND_SUCCESS; - } - return result;*/ - } - -} Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/JournalServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/JournalServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/JournalServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,470 +0,0 @@ -/* - * *##% Callao JournalServiceImpl - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import static org.nuiton.i18n.I18n._; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.entity.Journal; -import org.chorem.lima.entity.JournalDAO; -import org.chorem.lima.entity.LimaCallaoDAOHelper; -import org.chorem.lima.entity.Transaction; -import org.chorem.lima.entity.TransactionDAO; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; - -/** - * Implémente la fonction multi-journal. Il est possible de créer ici le - * journal des ventes, le journal des achats, etc. - * - * @author Rémi Chapelet - */ -public class JournalServiceImpl { - - private static final Log log = LogFactory.getLog(JournalServiceImpl.class); - - private TopiaContext rootContext; - - //private ConvertJournal convertJournal = new ConvertJournal(); - - public JournalServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - } - - /** - * Création d'un journal. Il peut être unique sur son label (au choix). - * - * @param journal journal - * @throws LimaException - */ - public void createJournal(Journal journal) throws LimaException { - /*String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - JournalDAO journalDAO = LimaCallaoDAOHelper - .getJournalDAO(topiaContext); - - // Si on souhaite avoir un journal unique avec son label - - Journal journal = searchJournalWithLabel(label); - // Si un journal existe déjà avec ce label - if (journal != null) { - if (log.isWarnEnabled()) { - log.warn("Un journal avec le label " + label - + " existe déjà !"); - } - result = ServiceHelper.JOURNAL_DOUBLE; - } else { - // Creation du journal - Journal newJournal = journalDAO.create(); - newJournal.setLabel(label); - newJournal.setPrefix(prefix); - newJournal.setDescription(description); - // Création BDD - topiaContext.commitTransaction(); - result = ServiceHelper.RESPOND_SUCCESS; - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result;*/ - - TopiaContext transaction = null; - try { - // basic check done, make check in database - // TODO move it into JTA - transaction = rootContext.beginTransaction(); - - // test si un journal de ce nom existe deja - JournalDAO journalDAO = LimaCallaoDAOHelper.getJournalDAO(transaction); - Journal existingJournal = journalDAO.findByLabel(journal.getLabel()); - if (existingJournal != null) { - throw new LimaBusinessException(_("An journal already exists with this label : %s", journal.getLabel())); - } - - // creation du journal - journalDAO.create(journal); - - // commit - transaction.commitTransaction(); - } - catch (TopiaException ex) { - if (transaction != null) { - try { - transaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't create journal", ex); - } - finally { - if (transaction != null) { - try { - transaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't create journal", ex); - } - } - } - } - - /* - * Création d'un journal à partir de son DTO. - * @param journalDTO Journal au format DTO. - * @return - * - public String createJournal(JournalDTO journalDTO) { - String result; - result = createJournal(journalDTO.getLabel(), journalDTO.getPrefix(), - journalDTO.getDescription()); - return result; - }*/ - - public List<Journal> getAllJournal() throws LimaException { - /*List<JournalDTO> listJournalDTO = new ArrayList<JournalDTO>(); - - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - JournalDAO journalDAO = LimaCallaoDAOHelper - .getJournalDAO(topiaContext); - // Creation du journal - List<Journal> listJournal = journalDAO.findAll(); - // Pour chaque journal, on le transforme en DTO - for (Journal journal : listJournal) { - // Converti en DTO - JournalDTO journalDTO = convertJournal - .journalEntityToDto(journal); - // Ajoute à la liste - listJournalDTO.add(journalDTO); - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return listJournalDTO;*/ - - List<Journal> journalsList = new ArrayList<Journal>(); - TopiaContext transaction = null; - try { - // basic check done, make check in database - // TODO move it into JTA - transaction = rootContext.beginTransaction(); - - // test si un journal de ce nom existe deja - JournalDAO journalDAO = LimaCallaoDAOHelper.getJournalDAO(transaction); - List<Journal> journals = journalDAO.findAll(); - journalsList.addAll(journals); - - // commit - transaction.commitTransaction(); - } - catch (TopiaException ex) { - if (transaction != null) { - try { - transaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't create journal", ex); - } - finally { - if (transaction != null) { - try { - transaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't create journal", ex); - } - } - } - - return journalsList; - } - - /* - * Permet de rechercher un journal existant à partir de son label. - * ATTENTION : il est possible que plusieurs journaux existent avec ce - * même label. La méthode renvoie le premier trouvé. - * @param prefix préfixe du journal recherché - * @return - * - public Journal searchJournalWithLabel(String label) { - Journal journalResult = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - JournalDAO journalDAO = LimaCallaoDAOHelper - .getJournalDAO(topiaContext); - // Creation du journal - journalResult = journalDAO.findByLabel(label); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return journalResult; - }*/ - - /* - * Permet de rechercher un journal existant à partir du label. - * Le journal recherché est converti automatiquement en format DTO. - * @param prefix préfixe du journal recherché - * @return - * - public JournalDTO searchJournalDTOWithLabel(String label) { - Journal journal = searchJournalWithLabel(label); - JournalDTO journalDTO = convertJournal.journalEntityToDto(journal); - return journalDTO; - }*/ - - /* - * Permet de rechercher un journal unique identifé par son topiaId. - * @param topiaId identifiant du journal recherché - * @return - * - public Journal searchJournalWithTopiaId(String topiaId) { - Journal journalResult = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - JournalDAO journalDAO = LimaCallaoDAOHelper - .getJournalDAO(topiaContext); - // Creation du journal - journalResult = journalDAO.findByTopiaId(topiaId); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return journalResult; - }*/ - - /* - * Permet de rechercher un journal existant à partir du topiaId. - * Le journal recherché est converti automatiquement en format DTO. - * @param prefix préfixe du journal recherché - * @return - * - public JournalDTO searchJournalDTOWithTopiaId(String topiaId) { - Journal journal = searchJournalWithTopiaId(topiaId); - JournalDTO journalDTO = convertJournal.journalEntityToDto(journal); - return journalDTO; - }*/ - - /* - * Permet de modifier un journal. - * @param label - * @param prefix - * @return - * - public String modifyJournal(String topiaId, String label, String prefix, - String description) { - String result = ServiceHelper.RESPOND_ERROR; - Journal journalModify = searchJournalWithTopiaId(topiaId); - // Si le journal n'existe pas - if (journalModify == null) { - if (log.isWarnEnabled()) { - log.warn("Le journal " + label + " n'existe pas !"); - } - result = ServiceHelper.JOURNAL_NOT_EXIST; - } else // Sinon on modifie le journal - { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - JournalDAO journalDAO = LimaCallaoDAOHelper - .getJournalDAO(topiaContext); - // Modifie le journal - journalModify.setPrefix(prefix); - journalModify.setDescription(description); - journalDAO.update(journalModify); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - result = ServiceHelper.RESPOND_SUCCESS; - } catch (TopiaException e) { - log.error(e); - } - } - return result; - }*/ - - /** - * Permet d'effacer un journal dans la base de données. - * - * ATTENTION : si un journal est associé avec des transactions, il est alors - * impossible de supprimer celui-ci. - * - * @param prefix préfixe du journal à supprimer - * @return - * @throws LimaException - */ - public void removeJournal(Journal journal) throws LimaException { - /*String result = ServiceHelper.RESPOND_ERROR; - Journal journalDelete = searchJournalWithTopiaId(topiaId); - // Si le journal n'existe pas - if (journalDelete == null) { - if (log.isWarnEnabled()) { - log.warn("Le journal " + topiaId + " n'existe pas !"); - } - result = ServiceHelper.JOURNAL_NOT_EXIST; - } else // Sinon on efface le journal - { - - // Vérifie si une transaction n'appartient pas à ce journal. - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche au moins une transaction avec ce journal. - Transaction transaction = transactionDAO - .findByJournal(journalDelete); - // Il existe au moins une transaction - if (transaction != null) { - if (log.isWarnEnabled()) { - log.warn("Le journal " + topiaId - + " possède des transactions comptables !"); - } - result = ServiceHelper.JOURNAL_WITH_TRANSACTIONS; - } else { - - // Efface le journal - // Chargement du DAO - JournalDAO journalDAO = LimaCallaoDAOHelper - .getJournalDAO(topiaContext); - // Supprime le journal - journalDAO.delete(journalDelete); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - result = ServiceHelper.RESPOND_SUCCESS; - } - } catch (TopiaException e) { - log.error(e); - } - } - return result;*/ - - TopiaContext topiaTransaction = null; - try { - // basic check done, make check in database - // TODO move it into JTA - topiaTransaction = rootContext.beginTransaction(); - - // Vérifie si une transaction n'appartient pas à ce journal. - TransactionDAO transactionDAO = LimaCallaoDAOHelper.getTransactionDAO(topiaTransaction); - Transaction transaction = transactionDAO.findByJournal(journal); - if (transaction != null) { - throw new LimaBusinessException("Can't delete journal with transactions"); - } - - // test si un journal de ce nom existe deja - JournalDAO journalDAO = LimaCallaoDAOHelper.getJournalDAO(topiaTransaction); - journalDAO.delete(journal); - - // commit - topiaTransaction.commitTransaction(); - } - catch (TopiaException ex) { - if (topiaTransaction != null) { - try { - topiaTransaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't create journal", ex); - } - finally { - if (topiaTransaction != null) { - try { - topiaTransaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't create journal", ex); - } - } - } - } - - /* - * Permet d'effacer un journal dans la base de données. - * ATTENTION : si un journal est associé avec des transactions, il est alors - * impossible de supprimer celui-ci. - * @param journalDTO journal au format DTO à supprimer - * @return - * - public String removeJournal(JournalDTO journalDTO) { - String result = removeJournal(journalDTO.getId()); - return result; - }*/ - -} Modified: trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/LimaConfig.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -20,6 +20,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.chorem.lima.entity.LimaCallaoDAOHelper; import org.nuiton.util.ApplicationConfig; import org.nuiton.util.ArgumentsParserException; @@ -53,6 +54,9 @@ log.error("Can't read configuration", ex); } } + + // FIXME put this in another place + instance.setOption("topia.persistence.classes", LimaCallaoDAOHelper.getImplementationClassesAsString()); } return instance; Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/LogServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/LogServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/LogServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,364 +0,0 @@ -/* - * *##% Callao LogServiceImpl - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.entity.EntryLog; -import org.chorem.lima.entity.EntryLogDAO; -import org.chorem.lima.entity.LimaCallaoDAOHelper; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; - -/** - * Permet d'ajouter des logs au systeme. - * - * ATTENTION on ne peut supprimer un log. - * - * @author Rémi Chapelet - */ -public class LogServiceImpl { //implements LogService { - - /** log */ - private static final org.apache.commons.logging.Log log = LogFactory - .getLog(LogServiceImpl.class); - - private TopiaContext rootContext; - - - public LogServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - } - - /** - * Création d'un log dans le systeme. - * - * @param entryLog date de creation du log - * @throws LimaException - */ - public void addLog(EntryLog entryLog) throws LimaException { - /*String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryLogDAO logDAO = LimaCallaoDAOHelper.getEntryLogDAO(topiaContext); - // Creation du log - EntryLog newlog = logDAO.create(); - newlog.setLogDate(logDate); - newlog.setTransDate(transDate); - newlog.setVoucherRef(voucherRef); - newlog.setType(type); - newlog.setTransDesc(transDesc); - newlog.setEntryDesc(entryDesc); - newlog.setAmount(amount); - newlog.setDebit(debit); - newlog.setLettering(lettering); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - // Affichage pour les logs - String topiaId = newlog.getTopiaId(); - if (log.isInfoEnabled()) { - log.info("Log created: "+ topiaId); - } - result = ServiceHelper.RESPOND_SUCCESS; - }catch (TopiaException e) { - log.error(e); - } - return result;*/ - - TopiaContext transaction = null; - try { - // basic check done, make check in database - // TODO move it into JTA - transaction = rootContext.beginTransaction(); - - // creation - EntryLogDAO entryLogDAO = LimaCallaoDAOHelper - .getEntryLogDAO(transaction); - entryLogDAO.create(entryLog); - - // commit - transaction.commitTransaction(); - } catch (TopiaException ex) { - if (transaction != null) { - try { - transaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't create entry log", ex); - } finally { - if (transaction != null) { - try { - transaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't create entry log", ex); - } - } - } - } - - /* - * Création d'un log à partir d'un log DTO. - * @param logDTO log en format DTO qu'on souhaite créer - * @return - * - public String addLog (LogDTO logDTO) { - String result = ServiceHelper.RESPOND_ERROR; - // Vérifie si logDTO existe - if (logDTO != null) - { - result = addLog(logDTO.getLogDate(),logDTO.getTransDate(),logDTO.getType(), - logDTO.getVoucherRef(),logDTO.getTransDesc(),logDTO.getEntryDesc(), - logDTO.getAmount(),logDTO.isDebit(),logDTO.getLettering()); - } - return result; - }*/ - - /** - * Recherche tous les logs dans la base de donnees. - * - * @return la liste des logs - * @throws LimaException - */ - public List<EntryLog> listeAllLog() throws LimaException { - /*List<EntryLog> listelog = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryLogDAO logDAO = LimaCallaoDAOHelper - .getEntryLogDAO(topiaContext); - // recherche des log - listelog = logDAO.findAll(); - // Fermeture BDD - topiaContext.closeContext(); - if (log.isInfoEnabled()) { - log.info("Search all logs"); - } - } catch (TopiaException e) { - log.error(e); - } - return listelog;*/ - - List<EntryLog> entryLogsList = new ArrayList<EntryLog>(); - TopiaContext transaction = null; - try { - // basic check done, make check in database - // TODO move it into JTA - transaction = rootContext.beginTransaction(); - - // creation - EntryLogDAO entryLogDAO = LimaCallaoDAOHelper - .getEntryLogDAO(transaction); - List<EntryLog> entryLogs = entryLogDAO.findAll(); - entryLogsList.addAll(entryLogs); - - // commit - transaction.commitTransaction(); - } catch (TopiaException ex) { - if (transaction != null) { - try { - transaction.rollbackTransaction(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - } - } - if (log.isErrorEnabled()) { - log.error("Error during create account", ex); - } - throw new LimaException("Can't create entry log", ex); - } finally { - if (transaction != null) { - try { - transaction.closeContext(); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Error during rollback context", ex); - } - throw new LimaException("Can't create entry log", ex); - } - } - } - - return entryLogsList; - } - - /* - * Permet de renvoyer tous les logs au format DTO. - * @return - * - public List<LogDTO> listeAllLogDTO() { - List<LogDTO> listLogDTO = new ArrayList<LogDTO>(); - // On recherche tous les logs. - List<EntryLog> listLog = listeAllLog(); - // Pour chaque log, on le converti en logDTO et on l'ajoute à la nouvelle liste de DTO - for (EntryLog log : listLog) { - // conerti de l'entity en DTO - LogDTO logDTO = convertLog.logEntityToDto(log); - // Ajoute à la liste des logs DTO - listLogDTO.add(logDTO); - } - return listLogDTO; - }*/ - - /* - * Renvoie une liste de tous les logs suivant la date de creation - * @param datecreate date de creation des logs recherchés - * @return une liste des logs trouves - * - public List<EntryLog> searchLogWithDateCreate(Date dateCreate) { - List<EntryLog> listelog = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryLogDAO logDAO = LimaCallaoDAOHelper - .getEntryLogDAO(topiaContext); - // recherche des log - listelog = logDAO.findAllByLogDate(dateCreate); - // Fermeture BDD - topiaContext.closeContext(); - if (log.isInfoEnabled()) { - log.info("Log(s) find : " + listelog.size() + "log(s)"); - } - } catch (TopiaException e) { - log.error(e); - } - return listelog; - }*/ - - /* - * Permet de rechercher tous les logs suivant la date de création, c'est à - * dire de l'opération effectuée sur une entry à un jour précis, et qui a - * déclenchée automatiquement une création de log. - * La méthode renvoie sous forme de liste, en convertissant les objets - * entitys en DTO. - * @param dateCreate date de création des logs recherchés - * @return - * - public List<LogDTO> searchLogDTOWithDateCreate(Date dateCreate) { - List<LogDTO> listLogDTO = new ArrayList<LogDTO>(); - // On recherche tous les logs suivant la date de création. - List<EntryLog> listLog = searchLogWithDateCreate(dateCreate); - // Pour chaque log, on le converti en logDTO et on l'ajoute à la nouvelle liste de DTO - for (EntryLog log : listLog) { - // conerti de l'entity en DTO - LogDTO logDTO = convertLog.logEntityToDto(log); - // Ajoute à la liste des logs DTO - listLogDTO.add(logDTO); - } - return listLogDTO; - }*/ - - /* - * Recherche un log avec son identifiant topiaId. - * @param topiaId identifiant d'un log - * @return - * - public EntryLog searchLogWithTopiaId(String topiaId) { - EntryLog logSearch = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryLogDAO logDAO = LimaCallaoDAOHelper - .getEntryLogDAO(topiaContext); - // Creation du journal - logSearch = logDAO.findByTopiaId(topiaId); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return logSearch; - }*/ - - /* - * Efface un log : uniquement utilisé pour supprimer les logs dans les tests - * unitaires. - * @param topiaId identifiant du log à supprimer - * @return - * - public String removeLog(String topiaId) { - String result = ServiceHelper.RESPOND_ERROR; - EntryLog logDelete = searchLogWithTopiaId(topiaId); - // Si le log n'existe pas - if (logDelete == null) { - if (log.isWarnEnabled()) { - log.warn("Le log " + topiaId + " n'existe pas !"); - } - } else // Sinon on efface le log - { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryLogDAO logDAO = LimaCallaoDAOHelper - .getEntryLogDAO(topiaContext); - // Supprime le log - logDAO.delete(logDelete); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - result = ServiceHelper.RESPOND_SUCCESS; - } catch (TopiaException e) { - log.error(e); - } - } - return result; - }*/ - - /* - * Permet de supprimer un log à partir de son DTO. - * @param logDTO log à supprimer - * @return - * - public String removeLog(LogDTO logDTO) { - String result = removeLog(logDTO.getId()); - return result; - }*/ -} Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/PeriodServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/PeriodServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/PeriodServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,504 +0,0 @@ -/* - * *##% Callao PeriodServiceImpl - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.entity.Period; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaNotFoundException; - -/** - * Gestion des périodes. - * Chaque période doit posséder 12 timespans mensuels. - * Une période ne peut être supprimée et débloquée. - * - * @author Rémi Chapelet - */ -public class PeriodServiceImpl { //implements PeriodService { - - private static final Log log = LogFactory.getLog(PeriodServiceImpl.class); - - private TopiaContext rootContext; - - private TimeSpanServiceImpl timeSpanServiceImpl = new TimeSpanServiceImpl(); - - public PeriodServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - } - - /** - * Permet de créer une période principale. Elle a une durée de un an, - * composées de 12 périodes mensuelles. Elle correspond à l'exercice - * comptable. Pour créer une nouvelle période, la précédente doit être - * obligatoirement clôturée. - * @param beginTimeSpan date début de période - * @param endTimeSpan date fin de période - * @param lock Vrai si la période est bloquée - * @return - */ - public void createPeriod(Period period /*Date beginTimeSpan, Date endTimeSpan, boolean lock*/) { - /*// Par défaut lock est à false - lock = false; - String result = ServiceHelper.RESPOND_ERROR; - - try { - boolean correctPeriod = false; - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - PeriodDAO periodDAO = LimaCallaoDAOHelper - .getPeriodDAO(topiaContext); - // Creation de la periodDate - PeriodDates newPeriod = new PeriodDates(beginTimeSpan, endTimeSpan); - - // Creation de la période - Period period = periodDAO.create(); - period.setBeginPeriod(newPeriod.getFromDate()); - period.setEndPeriod(newPeriod.getThruDate()); - period.setLocked(lock); - // Vérification si la période est correcte - correctPeriod = isCorrectPeriod(period); - if (correctPeriod) { - // Si elle est correcte : Création BDD - topiaContext.commitTransaction(); - if (log.isInfoEnabled()) { - log.info("Ajout exercice du " + beginTimeSpan.toString() - + " au " + endTimeSpan.toString()); - } - - //Ajout des timeSpans mensuels - //Par défaut, il prend seulement la date beginTimeSpan, et calcule - //la date de fin, c'est pourquoi il est laissé deux fois "beginTimeSpan" - TimeSpanServiceImpl timeSpanImpl = new TimeSpanServiceImpl(); - boolean stop = false; // En cas d'erreur lors de la création d'un timeSpan. - - List<Date> monthList = newPeriod.getMonths(); - - int max = monthList.size(); - log.debug("la periode fait:" + max); - for (int i = 0; i < max; i++) { - // Création timeSpan - result = timeSpanImpl.createTimeSpan(monthList.get(i), - monthList.get(i), period, false); - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - stop = true; - if (log.isErrorEnabled()) { - log.error("Erreur lors de la création des " + max - + " timeSpans"); - } - result = ServiceHelper.PERIOD_CREATE_TIMESPANS; - } - // Supprimer la periode si stop = true - } - if (stop == false) { - result = ServiceHelper.RESPOND_SUCCESS; - } - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result; */ - } - - /* - * Permet de créer une période à partir d'une période DTO. - * @param periodDTO période à créer au format DTO. - * @return - * - public String createPeriod(PeriodDTO periodDTO) { - String result = createPeriod(periodDTO.getBeginPeriod(), periodDTO - .getEndPeriod(), false); - // Tous les timeSpans sont automatiquement créés avec la méthode createPeriod - return result; - }*/ - - /* - * Permet de vérifier si la période est correcte (aucun chevauchement avec - * les autres périodes, période(s) précédente(s) bloquée(s), formée de 1 à 24 - * mois). - * @param period période à tester si elle est correcte - * @return - * - private boolean isCorrectPeriod(Period period) { - // Calcul du nombre de mois pour que la période soit valide (12 mois) - int number_months = dateUtil.numberOfMonths(period.getBeginPeriod(), - period.getEndPeriod()); - boolean result = true; - - if (number_months == 0 && number_months >= 24) // Periode de 1mois a 24 mois - { - if (log.isErrorEnabled()) { - log.error("Période du " - + period.getBeginPeriod() - + " au " - + period.getEndPeriod() - + " : L'exercice doit faire au minimum 1 mois et au maximum 24 mois"); - } - result = false; - } else { - // Période(s) précédente(s) bloquée(s). - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - PeriodDAO periodDAO = LimaCallaoDAOHelper - .getPeriodDAO(topiaContext); - // Recherche les périodes qui ne sont pas bloquées. - List<Period> listePeriod = periodDAO.findAllByLocked(false); - // Recherche la dernière période, les dates doivent se suivre - Date date_search = period.getBeginPeriod(); - Period previousPeriod = periodDAO.findByEndPeriod(dateUtil - .previousDay(date_search)); - // Nombre de périodes dans la base - int number_period = periodDAO.findAll().size(); - // Fermeture BDD - topiaContext.closeContext(); - // Si il y a au moins une période trouvée - if (!(listePeriod.isEmpty())) { - if (log.isErrorEnabled()) { - log.error("Il existe au moins une période précédente non bloquée !"); - } - result = false; - } - // Si la période précédente correspond au jour précédent - // et vérifie si ce n'est pas la première période - if (previousPeriod == null && number_period != 0) { - if (log.isErrorEnabled()) { - log.error("Votre période doit être collée " - + "aux autres périodes !" - + date_search.toString() + " PPP " - + dateUtil.previousDay(date_search).toString()); - } - result = false; - } - } catch (TopiaException e) { - log.error(e); - } - } - return result; - }*/ - - /* - * Cette méthode permet de bloquer une période. Elle doit vérifier que - * tous les timeSpans mensuels sont bloqués. - * @param - * @return - * - public String blockPeriod(Period period) { - String result = ServiceHelper.RESPOND_ERROR; - // La période ne doit pas être nulle - if (period != null) { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Recherche tous les timeSpans de la période non bloquées - List<TimeSpan> listeTimeSpan = timeSpanDAO - .findAllByPeriod(period); - boolean existTimeSpanNotBlock = false; - for (TimeSpan timeSpan : listeTimeSpan) { - // Si timeSpan non bloqué - if (!timeSpan.getLocked()) { - existTimeSpanNotBlock = true; - if (log.isErrorEnabled()) { - log.error("Le timeSpan du " - + timeSpan.getBeginTimeSpan().toString() - + " au " - + timeSpan.getEndTimeSpan().toString() - + " non bloqué !"); - } - result = ServiceHelper.PERIOD_TIMESPAN_NOT_BLOCK; - } - } - // Si il n'existe pas de timeSpan non bloqué - if (!(existTimeSpanNotBlock)) { - // Bloque la période - period.setLocked(true); - // Chargement du DAO - PeriodDAO periodDAO = LimaCallaoDAOHelper - .getPeriodDAO(topiaContext); - periodDAO.update(period); - // Création BDD - topiaContext.commitTransaction(); - result = ServiceHelper.RESPOND_SUCCESS; - if (log.isInfoEnabled()) { - log.info("Période " - + period.getBeginPeriod().toString() + " au " - + period.getEndPeriod().toString() - + " bloquée avec succès."); - } - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - } - return result; - }*/ - - /* - * Permet de bloquer une période. Avec la périodeDTO passée en paramètre, on - * effectue une recherche avec la date de début pour récupérer la période - * dans la base de données. Il est possible de l'identifier avec son topiaId, - * mais il y a plus de risque que cette mentien ne soit pas renseignée dans - * l'objet periodDTO. - * @param periodDTO - * @return - * - public String blockPeriod(PeriodDTO periodDTO) { - // Recherche de la période - Period period = searchPeriodWithDate(periodDTO.getBeginPeriod()); - String result = blockPeriod(period); - return result; - }*/ - - /* - * Permet de bloquer TOUS les timeSpans de la période - * @param period - * @return - * - public String blockAllTimeSpanOfPeriod(Period period) { - String result = ServiceHelper.RESPOND_ERROR; - if (period == null) { - if (log.isErrorEnabled()) { - log.error("La période ne peut bloquer ses périodes mensuelles, " - + "il faut une période en entrée."); - } - } else { - // On bloque chaque timeSpan - boolean ErrorBlockTimeSpan = false; - List<TimeSpanDTO> listTimeSpanDTO = timeSpanServiceImpl - .searchListTimeSpanDTO(period); - // tri la liste des timeSpans dans l'ordre croissant des dates - Collections.sort(listTimeSpanDTO); - for (TimeSpanDTO timeSpanDTO : listTimeSpanDTO) { - result = timeSpanServiceImpl.blockTimeSpan(timeSpanDTO); - if (result.equals(ServiceHelper.RESPOND_ERROR)) { - ErrorBlockTimeSpan = true; - } - } - // Si il n'y a pas eu d'erreurs pour bloquer les timespans - if (!ErrorBlockTimeSpan) { - result = ServiceHelper.RESPOND_SUCCESS; - } else { - if (log.isErrorEnabled()) { - log.error("Impossible de bloquer tous les timeSpans."); - } - result = ServiceHelper.PERIOD_ALL_TIMESPAN; - } - } - return result; - }*/ - - /* - * Cette méthode est semblable à searchPeriodWithDateFirst. Elle permet - * de rechercher une période sans forcément connaître la date de départ. On - * donne une date quelconque, et elle retourne la période correspondante. - * @param d - * @return - * - public Period searchPeriodWithDate(Date d) { - Period period = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - PeriodDAO periodDAO = LimaCallaoDAOHelper - .getPeriodDAO(topiaContext); - // Recherche de toutes les périodes - List<Period> listePeriod = periodDAO.findAll(); - // Fermeture BDD - topiaContext.closeContext(); - // Recherche de la période - for (Period periodSearch : listePeriod) { - // Recherche si la date d est entre la date de début et fin de la période - boolean periodBetweenDate = dateUtil.betweenDate(d, - periodSearch.getBeginPeriod(), periodSearch - .getEndPeriod()); - // Si la date est comprise dans les limites de la période - if (periodBetweenDate) { - period = periodSearch; - } - } - } catch (TopiaException e) { - log.error(e); - } - return period; - }*/ - - /* - * Permet de rechercher une période au format DTO avec une date. Cette date - * peut être quelconque (pas obligatoire d'être le premier jour de la période - * par exemple). - * @param d date comprise dans la période qu'on souhaite rechercher - * @return - * - public PeriodDTO searchPeriodDTOWithDate(Date d) { - Period period = searchPeriodWithDate(d); - // Converti la période en PeriodDTO - PeriodDTO periodDTO = convertPeriod.periodEntityToDto(period); - return periodDTO; - }*/ - - /* - * Permet de renvoyer tous les périodes en format DTO, avec tous les timeSpans - * en format DTO également. - * @return - * - public List<PeriodDTO> getAllPeriod() { - ArrayList<PeriodDTO> listAllPeriodDTO = new ArrayList<PeriodDTO>(); - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - PeriodDAO periodDAO = LimaCallaoDAOHelper - .getPeriodDAO(topiaContext); - // Recherche de toutes les périodes - List<Period> listePeriod = periodDAO.findAll(); - // Transforme les périodes en DTO - for (Period period : listePeriod) { - PeriodDTO periodDTO = convertPeriod.periodEntityToDto(period); - listAllPeriodDTO.add(periodDTO); - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return listAllPeriodDTO; - }*/ - - /* - * Recherche une période précise, avec son identifiant topiaId. - * @param topiaId identifiant de la période - * @return - * - public Period searchPeriodWithTopiaId(String topiaId) { - Period periodSearch = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - PeriodDAO periodDAO = LimaCallaoDAOHelper - .getPeriodDAO(topiaContext); - // Creation du journal - periodSearch = periodDAO.findByTopiaId(topiaId); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return periodSearch; - }*/ - - - /* - * Efface une période dans la base de données. Tous les timeSpans sont - * également effacés. Cette méthode est uniquement utilisée pour les tests - * unitaires. - * @param period - * @return - * - public String removePeriod(String topiaId) { - String result = ServiceHelper.RESPOND_ERROR; - Period periodDelete = searchPeriodWithTopiaId(topiaId); - // Si la période n'existe pas - if (periodDelete == null) { - if (log.isWarnEnabled()) { - log.warn("La période " + topiaId + " n'existe pas !"); - } - result = ServiceHelper.PERIOD_NOT_EXIST; - } else // Sinon on efface la période - { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - PeriodDAO periodDAO = LimaCallaoDAOHelper - .getPeriodDAO(topiaContext); - // Débloque la période - periodDelete.setLocked(false); - // Mise à jour dans la bdd - periodDAO.update(periodDelete); - // Création BDD - topiaContext.commitTransaction(); - - // Supprime les timeSpans de la période - List<TimeSpanDTO> listTimeSpanDTO = timeSpanServiceImpl - .searchListTimeSpanDTO(periodDelete); - // tri la liste des timeSpans dans l'ordre décroissant des dates - Collections.sort(listTimeSpanDTO, Collections.reverseOrder()); - // Débloque les timeSpans - for (TimeSpanDTO timeSpanDTO : listTimeSpanDTO) { - TimeSpan timeSpan = timeSpanServiceImpl - .searchTimeSpanByDate(timeSpanDTO); - // Si le timeSpan est bloqué - if (timeSpanDTO.isLocked()) { - // débloque le timeSpan - timeSpanServiceImpl.unblockTimeSpan(timeSpan); - } - } - // Efface les timeSpans - for (TimeSpanDTO timeSpanDTO : listTimeSpanDTO) { - TimeSpan timeSpan = timeSpanServiceImpl - .searchTimeSpanByDate(timeSpanDTO); - // efface le timeSpan - timeSpanServiceImpl.removeTimeSpan(timeSpan); - } - - - //Supprime la période - periodDAO.delete(periodDelete); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - result = ServiceHelper.RESPOND_SUCCESS; - } catch (TopiaException e) { - log.error(e); - } - } - return result; - }*/ - - /* - * Permet d'effacer une période au format DTO. - * @param periodDTO la période à supprimer - * @return - * - public String removePeriod(PeriodDTO periodDTO) { - String result = removePeriod(periodDTO.getId()); - return result; - }*/ -} Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/ReportServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ReportServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ReportServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,61 +0,0 @@ -package org.chorem.lima.business; - -import org.nuiton.topia.TopiaContext; - -public class ReportServiceImpl { //implements ReportService { - - //@Override - public String generateAccount(String number, String amount, String label) { - // TODO Auto-generated method stub - return null; - } - - //@Override - public String generateBalanceSheet(String period) { - // TODO Auto-generated method stub - return null; - } - - //@Override - public String generateCashFlowStatement(String period) { - // TODO Auto-generated method stub - return null; - } - - //@Override - public String generateGeneralLedger(String period) { - // TODO Auto-generated method stub - return null; - } - - //@Override - public String generateIncomeStatement(String period) { - // TODO Auto-generated method stub - return null; - } - - //@Override - public String generateJournal(String type, String period) { - // TODO Auto-generated method stub - return null; - } - - //@Override - public String[] getMethods() { - // TODO Auto-generated method stub - return null; - } - - //@Override - public void destroy() { - // TODO Auto-generated method stub - - } - - //@Override - public void init(TopiaContext arg0) { - // TODO Auto-generated method stub - - } - -} Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/TimeSpanServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/TimeSpanServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/TimeSpanServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,533 +0,0 @@ -/* - * *##% Callao TimeSpanServiceImpl - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.entity.TimeSpan; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaNotFoundException; - -/** - * Gestion des périodes intermédiaires durant l'exercice. - * Chaque timeSpan sera fixe, et devra correspondre à un mois complet. - * - * @author Rémi Chapelet - */ -public class TimeSpanServiceImpl { //implements TimeSpanService { - - /** log */ - private static final Log log = LogFactory.getLog(TimeSpanServiceImpl.class); - - private TopiaContext rootContext; - - private static TransactionServiceImpl transactionServiceImpl = new TransactionServiceImpl(); - - public TimeSpanServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - } - - /** - * 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. - * @param beginTimeSpan date de début de période - * @param endTimeSpan date de fin de période - * @param locked est à vrai si la période doit être bloquée. - * @return - */ - public void createTimeSpan(TimeSpan timeSpan /*Date beginTimeSpan, Date endTimeSpan, - Period period, boolean locked*/) { -/* - // timeSpan correspond à une période mensuelle. - // La fonction va donc prendre seulement pour date de référence la - // date beginTimeSpan. Elle calcule automatiquement la date de fin - // suivant le mois. - DateUtil dateutil = new DateUtil(); - // Initialise la date de début au premier du mois - beginTimeSpan = dateutil.InitDateFirstDayMonth(beginTimeSpan); - // Initialise la date de fin au dernier du mois - endTimeSpan = dateutil.InitDateEndDayMonth(beginTimeSpan); - if (log.isInfoEnabled()) { - log.info("Nouveau timeSpan du " + beginTimeSpan.toString() + " au " - + endTimeSpan.toString()); - } - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Creation du timespan - TimeSpan newtimeSpan = timeSpanDAO.create(); - newtimeSpan.setBeginTimeSpan(beginTimeSpan); - newtimeSpan.setEndTimeSpan(endTimeSpan); - newtimeSpan.setLocked(locked); - newtimeSpan.setPeriod(period); - // Création BDD - topiaContext.commitTransaction(); - // Fermeture BDD - topiaContext.closeContext(); - if (log.isInfoEnabled()) { - log.info("Ajout avec succes du timeSpan"); - } - return ServiceHelper.RESPOND_SUCCESS; - } catch (TopiaException e) { - log.error(e); - return ServiceHelper.RESPOND_ERROR; - }*/ - } - - /* - * Permet de trouver un timespan directement avec une date. La date peut - * être quelconque. Exemple : d = 17 sept 2000, renvoie la période du - * 1 sept au 30 sept 2000. - * @param d - * @return - * - public TimeSpan searchTimeSpanByDate(Date d) { - TimeSpan timeSpan = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Par précaution, on initialise la date au debut du mois - DateUtil dateutil = new DateUtil(); - // Recherche du timeSpan - Date searchDate = dateutil.InitDateFirstDayMonth(d); - timeSpan = timeSpanDAO.findByBeginTimeSpan(searchDate); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return timeSpan; - }*/ - - /* - * Recherche un timeSpan précis, avec sa date de création. - * @param timeSpanDTO timeSpan au format DTO qu'on recherche - * @return - * - public TimeSpan searchTimeSpanByDate(TimeSpanDTO timeSpanDTO) { - TimeSpan timeSpan = searchTimeSpanByDate(timeSpanDTO.getBeginTimeSpan()); - return timeSpan; - }*/ - - /* - * Recherche un timeSpan UNIQUE. Celui est identifié par son topiaId. - * @param topiaId Identifiant du timeSpan recherché - * @return - * - public TimeSpan searchTimeSpanWithTopiaId(String topiaId) { - TimeSpan timeSpan = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Recherche du timeSpan - timeSpan = timeSpanDAO.findByTopiaId(topiaId); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return timeSpan; - }*/ - - /* - * Permet de rechercher un timeSpan à l'aide d'une date. Il fait appel - * à la méthode searchTimeSpanByDate. - * La méthode renvoie un objet DTO. - * @param d - * @return - * - public TimeSpanDTO searchTimeSpanDTOByDate(Date d) { - TimeSpan timeSpan = searchTimeSpanByDate(d); - TimeSpanDTO timeSpanDTO = convertTimeSpan.timeSpanEntityToDto(timeSpan); - return timeSpanDTO; - }*/ - - /* - * Permet de faire une recherche de tous les timeSpans d'une période. - * @param period - * @return - * - public List<TimeSpan> searchListTimeSpan(Period period) { - List<TimeSpan> listTimeSpan = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Recherche les timeSpans avec cette période - listTimeSpan = timeSpanDAO.findAllByPeriod(period); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return listTimeSpan; - }*/ - - /* - * Permet de rechercher tous les timeSpans suivant une période donnée. - * Chaque timeSpan est converti ensuite en DTO. - * @param period - * @return - * - public List<TimeSpanDTO> searchListTimeSpanDTO(Period period) { - List<TimeSpanDTO> listTimeSpanDTO = new ArrayList<TimeSpanDTO>(); - List<TimeSpan> listTimeSpan = searchListTimeSpan(period); - for (TimeSpan timeSpan : listTimeSpan) { - TimeSpanDTO timeSpanDTO = convertTimeSpan - .timeSpanEntityToDto(timeSpan); - listTimeSpanDTO.add(timeSpanDTO); - } - return listTimeSpanDTO; - }*/ - - /* - * Permet de bloquer un timespan, celle-ci ne doit pas être bloquée. - * La fonction doit s'assurer que les timeSpans précédents doivent être - * bloqués. - * Les transactions doivent être équilibrées - * @param timespan période qui doit être fermée - * @param period période (12 smois) - * - public String blockTimeSpan(TimeSpan timespan) { - String result = ServiceHelper.RESPOND_ERROR; - // Si la période n'est pas déjà fermée. - if (timespan.getLocked()) { - if (log.isInfoEnabled()) { - log.info("Timespan deja bloqué !"); - } - } else { - Period period = getPeriodWithTimeSpan(timespan); - if (period.getLocked()) { - if (log.isErrorEnabled()) { - log.error("La période du timespan est bloquée !"); - } - } else { - // Vérifie si tous les timeSpans précédents sont bloqués - boolean AllTimeSpanBlock = alltimeSpanBlocked(timespan, period); - if (AllTimeSpanBlock) { - // Enregistrement dans la base de données - try { - // Acces BDD - TopiaContext topiaContext = rootContext - .beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - - // Vérifie si les transactons sont équilibrées - List<Transaction> listTransaction = transactionServiceImpl - .searchListTransactionWithTimeSpan(timespan); - boolean isTransactionBalanced = true; - boolean existTransactionNotBalanced = false; - for (Transaction transaction : listTransaction) { - isTransactionBalanced = transactionServiceImpl - .isTransactionBalanced(transaction); - if (!isTransactionBalanced) { - if (log.isInfoEnabled()) { - log.info("La transaction n'est pas bloquée."); - } - existTransactionNotBalanced = true; - } - } - if (!existTransactionNotBalanced) { - // Bloque la période - timespan.setLocked(true); - // Mise à jour de timespan dans la BDD - timeSpanDAO.update(timespan); - // Création BDD - topiaContext.commitTransaction(); - if (log.isInfoEnabled()) { - log.info("Timespan bloqué avec succès"); - } - result = ServiceHelper.RESPOND_SUCCESS; - } else { - result = ServiceHelper.TRANSACTION_NOT_BALANCED; - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - } else { - if (log.isErrorEnabled()) { - log.error("Il existe un ou plusieurs timespans précédents" - + " non bloqués."); - } - result = ServiceHelper.TIMESPAN_PREC_NOT_BLOCK; - } - } - } - return result; - }*/ - - /* - * Permet de bloquer une période au format DTO. - * - * @param timespanDTO - * @return - * - public String blockTimeSpan(TimeSpanDTO timespanDTO) { - return blockTimeSpan(searchTimeSpanByDate(timespanDTO)); - }*/ - - /* - * Permet de débloquer un timespan, à condition que les timespans suivants - * celui-ci soient bien débloqués. - * @param timespan - * @param period - * @return - * - public String unblockTimeSpan(TimeSpan timespan) { - String result = ServiceHelper.RESPOND_ERROR; - // Si le timspan n'est pas bloqué - if (!timespan.getLocked()) { - if (log.isWarnEnabled()) { - log.warn("Timespan non bloqué !"); - } - } else { - Period period = getPeriodWithTimeSpan(timespan); - if (period.getLocked()) { - if (log.isErrorEnabled()) { - log.error("La période du timespan est bloquée !"); - } - } else { - boolean NextTimeSpanUnblock = nextTimeSpanUnblock(timespan, - period); - // Si aucun timespan suivant bloqué - if (NextTimeSpanUnblock) { - try { - // Acces BDD - TopiaContext topiaContext = rootContext - .beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // débloque la période - timespan.setLocked(false); - // Mise à jour de timespan dans la BDD - timeSpanDAO.update(timespan); - // Création BDD - topiaContext.commitTransaction(); - if (log.isInfoEnabled()) { - log.info("Timespan débloqué avec succès"); - } - result = ServiceHelper.RESPOND_SUCCESS; - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - } else { - result = ServiceHelper.TIMESPAN_NEXT_NOT_BLOCK; - } - } - } - return result; - }*/ - - /* - * Permet de bloquer une période au format DTO. - * - * @param timespanDTO - * @return - * - public String unblockTimeSpan(TimeSpanDTO timespanDTO) { - return unblockTimeSpan(searchTimeSpanByDate(timespanDTO)); - }*/ - - /* - * Cette méthode va rechercher tous les timeSpans non bloqués après - * le timeSpan renseigné en paramètre. - * Si elle trouve au moins un timeSpan NON bloqué, elle renvoie alors faux. - * Cette méthode permet essentiellement de définir si il est possible - * ou non de bloquer un timeSpan. A savoir, un timeSpan ne peut être bloqué, - * si il existe des timeSpans suivant (dans le calendrier) qui sont non - * bloqués. - * @param timespan - * @param period - * @return - * - private boolean nextTimeSpanUnblock(TimeSpan timespan, Period period) { - boolean NextTimeSpanUnblock = false; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Recherche des TimeSpans avec la même période. - // (on doit récupérer normalement 12 timeSpans) - List<TimeSpan> listeTimeSpanOfPeriod = timeSpanDAO - .findAllByPeriod(period); - NextTimeSpanUnblock = true; - for (TimeSpan timeSpanNext : listeTimeSpanOfPeriod) { - // Si le timespan est après celui qu'on souhaite bloquer ET est non bloqué - if (timeSpanNext.getBeginTimeSpan().compareTo( - timespan.getBeginTimeSpan()) == 1 - && timeSpanNext.getLocked()) { - NextTimeSpanUnblock = false; - if (log.isInfoEnabled()) { - log.info("Timespan " + timeSpanNext.toString() - + " est bloqué"); - } - } - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return NextTimeSpanUnblock; - }*/ - - /* - * Permet de renvoyer une période dont appartient le timeSpan. - * @param timeSpan timeSpan dont on souhaite retourner la période - * @return - * - private Period getPeriodWithTimeSpan(TimeSpan timeSpan) { - PeriodServiceImpl periodServiceImpl = new PeriodServiceImpl(); - Date beginTimeSpan = timeSpan.getBeginTimeSpan(); - Period period = periodServiceImpl.searchPeriodWithDate(beginTimeSpan); - return period; - }*/ - - /* - * Cette méthode renvoie vrai lorsque tous les timespans de la période - * précédent au timespan en paramètre sont bloqués. - * @param timespan - * @param period le paramètre period est important, en effet un timespan ne - * peut être indépendant. - * @return - * - private boolean alltimeSpanBlocked(TimeSpan timespan, Period period) { - boolean AllTimeSpanBlock = false; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Recherche des TimeSpans avec la même période. - // (on doit récupérer normalement 12 timeSpans) - List<TimeSpan> listeTimeSpanOfPeriod = timeSpanDAO - .findAllByPeriod(period); - // Fermeture BDD - topiaContext.closeContext(); - // On contrôle que les timeSpans précédents sont bloqués. - AllTimeSpanBlock = true; - for (TimeSpan timeSpanPrev : listeTimeSpanOfPeriod) { - // Si la période est avant celle qu'on souhaite bloquer ET est non bloquée - if (timeSpanPrev.getBeginTimeSpan().compareTo( - timespan.getBeginTimeSpan()) == -1 - && !timeSpanPrev.getLocked()) { - AllTimeSpanBlock = false; - if (log.isInfoEnabled()) { - log.info("Timespan " + timeSpanPrev.toString() - + " non bloqué"); - } - } - } - } catch (TopiaException e) { - log.error(e); - } - return AllTimeSpanBlock; - }*/ - - /* - * Permet d'effacer un timeSpan. Ce dernier ne doit pas être bloqué. - * @param timeSpan - * @return - * - public String removeTimeSpan(TimeSpan timeSpan) { - String result = ServiceHelper.RESPOND_ERROR; - // Si le timspan est bloqué - if (timeSpan.getLocked()) { - if (log.isWarnEnabled()) { - log.warn("Timespan bloqué !"); - } - } else { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Mise à jour de timespan dans la BDD - timeSpanDAO.delete(timeSpan); - // Création BDD - topiaContext.commitTransaction(); - if (log.isInfoEnabled()) { - log.info("Timespan supprimé avec succès"); - } - result = ServiceHelper.RESPOND_SUCCESS; - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - } - return result; - }*/ - - /* - * Vérifie si le timeSpan donné en paramètre est bloqué ou non. - * @param timeSpan - * @return - * - public boolean isTimeSpanBlocked(TimeSpan timeSpan) { - boolean isTimeSpanBlocked = true; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper - .getTimeSpanDAO(topiaContext); - // Mise à jour de timespan dans la BDD - TimeSpan timeSpanSearch = timeSpanDAO.findByTopiaId(timeSpan - .getTopiaId()); - isTimeSpanBlocked = timeSpanSearch.getLocked(); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return isTimeSpanBlocked; - }*/ -} Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/TransactionServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/TransactionServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/TransactionServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,745 +0,0 @@ -/* - * *##% Callao TransactionServiceImpl - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.business.dto.EntryDTO; -import org.chorem.lima.business.dto.LogDTO; -import org.chorem.lima.business.dto.TransactionDTO; -import org.chorem.lima.business.utils.ServiceHelper; -import org.chorem.lima.entity.Account; -import org.chorem.lima.entity.Entry; -import org.chorem.lima.entity.EntryDAO; -import org.chorem.lima.entity.Journal; -import org.chorem.lima.entity.LimaCallaoDAOHelper; -import org.chorem.lima.entity.TimeSpan; -import org.chorem.lima.entity.Transaction; -import org.chorem.lima.entity.TransactionDAO; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; - -/** - * 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 - */ -public class TransactionServiceImpl { - - private static final Log log = LogFactory - .getLog(TransactionServiceImpl.class); - - private TopiaContext rootContext; - - private LogServiceImpl logServiceImpl = new LogServiceImpl(); - - private EntryServiceImpl entryServiceImpl = new EntryServiceImpl(); - - private TimeSpanServiceImpl timeSpanServiceImpl = new TimeSpanServiceImpl(); - - public TransactionServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - } - - /** - * Permet de créer une transaction comptable. Pour ajouter une transaction, - * le timeSpan doit être non bloqué. - * @param entryDate - * @param voucherRef - * @param description - * @param timespan - * @param journal - * @return - */ - public void createTransaction(Transaction transaction /*Date entryDate, String voucherRef, - String description, TimeSpan timeSpan, Journal journal*/) { - /*String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - String isCorrectTransaction = isCorrectTransaction(timeSpan, - journal); - if (isCorrectTransaction.equals(ServiceHelper.RESPOND_SUCCESS)) { - // Creation de la transaction - Transaction newtransaction = transactionDAO.create(); - newtransaction.setTransDate(entryDate); - newtransaction.setVoucherRef(voucherRef); - newtransaction.setDescription(description); - newtransaction.setTimeSpan(timeSpan); - newtransaction.setJournal(journal); - // Création BDD - topiaContext.commitTransaction(); - if (log.isInfoEnabled()) { - log.info("Ajout avec succes de la transaction"); - } - - // Il renvoie soit l'identifiant topiaId ou SUCCESS. - result = newtransaction.getTopiaId(); - //result = ServiceHelper.RESPOND_SUCCESS; - } else { - result = isCorrectTransaction; - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result;*/ - } - - /* - * Permet de créer une transaction à partir d'une transaction DTO. - * ATTENTION : si le journal ou timespan n'existe pas, l'ajout ne peut se - * faire. Si on souhaite, on peut créer le journal automatiquement lors de - * l'ajout de la transaction si il n'existe pas. Pour le timeSpan, il n'est - * pas cohérent qu'il n'existe pas. On ne peut travailler que sur une période - * comptable existante, et par conséquent il ne faut pas le créer. - * @param transactionDTO - * @return - * - public String createTransaction(TransactionDTO transactionDTO) { - String result = ServiceHelper.RESPOND_ERROR; - // Vérifie que transactionDTO possède un journalDTO et un timeSpanDTO - if (transactionDTO.getJournalDTO() == null - || transactionDTO.getTimeSpanDTO() == null) { - if (log.isErrorEnabled()) { - log.error("L'objet transactionDTO ne possède pas de timeSpan ET/OU de journal."); - } - result = ServiceHelper.TRANSACTION_NOT_JOURNAL; - } else { - // Recherche du journal - JournalServiceImpl journalServiceImpl = new JournalServiceImpl(); - Journal journal = journalServiceImpl - .searchJournalWithLabel(transactionDTO.getJournalDTO() - .getLabel()); - // Recherche du timeSpan - TimeSpan timeSpan = timeSpanServiceImpl - .searchTimeSpanByDate(transactionDTO.getTimeSpanDTO() - .getBeginTimeSpan()); - - // Vérification si timeSpan et Journal existe bien - if (journal == null) { - if (log.isErrorEnabled()) { - log.error("Création transaction : Le journal " - + transactionDTO.getJournalDTO().getLabel() - + " n'existe pas."); - } - result = ServiceHelper.TRANSACTION_NOT_JOURNAL; - } else { - if (timeSpan == null) { - if (log.isErrorEnabled()) { - log.error("Création transaction : Le timeSpan " - + transactionDTO.getTimeSpanDTO().toString() - + " n'existe pas."); - } - result = ServiceHelper.TRANSACTION_NOT_TIMESPAN; - } else { - result = createTransaction(transactionDTO.getEntryDate(), - transactionDTO.getVoucherRef(), transactionDTO - .getDescription(), timeSpan, journal); - } - } - } - return result; - }*/ - - /* - * Permet de modifier une transaction. Cette dernière est identifiée par la - * clé topiaId. - * @param topiaId - * @param entryDate - * @param voucherRef - * @param description - * @param timespan - * @param journal - * @return - * - public String modifyTransaction(String topiaId, Date entryDate, - String voucherRef, String description, TimeSpan timeSpan, - Journal journal) { - String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Vérification que la transaction existe bien - Transaction transaction = transactionDAO.findByTopiaId(topiaId); - if (transaction == null) { - if (log.isInfoEnabled()) { - log.info("La transaction " + voucherRef - + " n'existe pas. (identifiant " + topiaId + ")"); - } - result = ServiceHelper.TRANSACTION_NOT_EXIST; - } else { - // Vérification si la transaction possède de bons paramètres - String correct = isCorrectTransaction(timeSpan, journal); - // Si la transaction est correcte - if (correct.equals(ServiceHelper.RESPOND_SUCCESS)) { - // Modification - transaction.setTransDate(entryDate); - transaction.setVoucherRef(voucherRef); - transaction.setDescription(description); - transaction.setTimeSpan(timeSpan); - transaction.setJournal(journal); - transaction.update(); - // Création BDD - topiaContext.commitTransaction(); - result = ServiceHelper.RESPOND_SUCCESS; - } - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result; - }*/ - - /* - * Permet de modifier une transaction à partir d'une transaction DTO. - * Elle va rechercher le journal et le timespan correspondants. - * @param transactionDTO - * @return - * - public String modifyTransaction(TransactionDTO transactionDTO) { - // Recherche du journal - JournalServiceImpl journalServiceImpl = new JournalServiceImpl(); - Journal journal = journalServiceImpl - .searchJournalWithLabel(transactionDTO.getJournalDTO() - .getLabel()); - // Recherche du timeSpan - TimeSpan timeSpan = timeSpanServiceImpl - .searchTimeSpanByDate(transactionDTO.getTimeSpanDTO() - .getBeginTimeSpan()); - // Appel pour la modification - String result = modifyTransaction(transactionDTO.getId(), - transactionDTO.getEntryDate(), transactionDTO.getVoucherRef(), - transactionDTO.getDescription(), timeSpan, journal); - return result; - }*/ - - /* - * Recherche une transaction unique avec son identifiant TopiaId. - * @param topiaId - * @return - * - public Transaction searchTransactionWithTopiaId(String topiaId) { - Transaction transaction = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche - transaction = transactionDAO.findByTopiaId(topiaId); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return transaction; - }*/ - - /* - * Recherche une transaction unique à partir d'une transaction DTO. - * @param transactionDTO - * @return - * - public Transaction searchTransactionWithTopiaId( - TransactionDTO transactionDTO) { - Transaction transaction = searchTransactionWithTopiaId(transactionDTO - .getId()); - return transaction; - }*/ - - /* - * Recherche une transaction dans la base de données, et renvoie celle-ci - * sous format DTO. Nous ne pouvons pas appeler la méthode searchTransactionWithTopiaId - * du fait que lors de la convertion, nous avons besoin du journal et du - * timeSpan. Or il ne faut donc pas de fermeture de connexion à la base de - * données pour celà. - * @param topiaId - * @return - * - public TransactionDTO searchTransactionDTO(String topiaId) { - TransactionDTO transactionDTO = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche - Transaction transaction = transactionDAO.findByTopiaId(topiaId); - // Converti la transaction en DTO - convertTransaction.setTransaction(rootContext); - transactionDTO = convertTransaction - .transactionEntityToDto(transaction); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return transactionDTO; - }*/ - - /* - * Recherche toutes les transactions qui correspondent à un timespan. - * @param timeSpan - * @return - * - public List<Transaction> searchListTransactionWithTimeSpan(TimeSpan timeSpan) { - List<Transaction> listTransaction = null; - if (timeSpan != null) { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche - listTransaction = transactionDAO.findAllByTimeSpan(timeSpan); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - } - return listTransaction; - }*/ - - /* - * Recherche les transactions DTO d'un timeSpan - * @param timeSpan - * @return - * - public List<TransactionDTO> searchListTransactionDTOWithTimeSpan( - TimeSpan timeSpan) { - List<TransactionDTO> listTransactionDTO = new ArrayList<TransactionDTO>(); - if (timeSpan != null) { - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche - List<Transaction> listTransaction = transactionDAO - .findAllByTimeSpan(timeSpan); - // Converti la transaction en DTO - convertTransaction.setTransaction(rootContext); - for (Transaction transaction : listTransaction) { - TransactionDTO transactionDTO = convertTransaction - .transactionEntityToDto(transaction); - listTransactionDTO.add(transactionDTO); - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - } - return listTransactionDTO; - }*/ - - /* - * Recherche toutes les transactions appartenant à un même journal donné - * en paramètre. - * @param journal - * @return - * - public List<Transaction> searchListTransactionWithJournal(Journal journal) { - List<Transaction> listTransaction = null; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche - listTransaction = transactionDAO.findAllByJournal(journal); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return listTransaction; - }*/ - - /* - * Permet de rechercher toutes les transactions dans la base de données, - * avec en retour une liste de transactions au format DTO. - * @return - * - public List<TransactionDTO> getAllTransactionDTO() { - List<TransactionDTO> listTransactionDTO = new ArrayList<TransactionDTO>(); - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche - List<Transaction> listTransaction = transactionDAO.findAll(); - // Converti la transaction en DTO - convertTransaction.setTransaction(rootContext); - for (Transaction transaction : listTransaction) { - TransactionDTO transactionDTO = convertTransaction - .transactionEntityToDto(transaction); - listTransactionDTO.add(transactionDTO); - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return listTransactionDTO; - }*/ - - /* - * Cette méthode permet de vérifier si une transaction possède des paramètres - * corrects. - * Un journal doit exister. - * Un timeSpan doit exister et être non bloqué. - * @param timeSpan - * @param journal - * @return - * - public String isCorrectTransaction(TimeSpan timeSpan, Journal journal) { - String result = ServiceHelper.RESPOND_SUCCESS; - // Vérification si timeSpan et Journal existe bien - if (journal == null) { - if (log.isErrorEnabled()) { - log.error("Création transaction : Le journal n'existe pas."); - } - result = ServiceHelper.TRANSACTION_NOT_JOURNAL; - } - if (timeSpan == null) { - if (log.isErrorEnabled()) { - log.error("Création transaction : Le timeSpan n'existe pas."); - } - result = ServiceHelper.TRANSACTION_NOT_TIMESPAN; - } else { - // Vérifie si le timeSpan est bloqué - if (timeSpan.getLocked()) { - if (log.isErrorEnabled()) { - log.error("Le timeSpan est bloqué ! Il est donc impossible" - + " d'ajouter une transaction sur cette période. (" - + "Période du " + timeSpan + ")"); - } - result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; - } - } - return result; - }*/ - - /* - * Permet d'effacer une transaction dans la base de données. - * ATTENTION : Elle supprime également toutes les entées comptables - * associées. Une transaction appartenant à un timeSpan bloqué ne peut être - * supprimée. - * @return - * - public String removeTransaction(String topiaId) { - String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche de l'entry - Transaction transaction = transactionDAO.findByTopiaId(topiaId); - // Transaction doit exister - if (transaction != null) { - // Vérifie si la transaction est non bloquée. - if (!isTransactionBlocked(transaction)) { - // Supprime tous les entrys de la transactions - List<Entry> listEntry = entryServiceImpl - .searchEntryWithTransaction(transaction); - for (Entry entry : listEntry) { - result = removeEntry(entry.getTopiaId()); - } - // Supprime la transaction - transactionDAO.delete(transaction); - // Création BDD - topiaContext.commitTransaction(); - if (log.isInfoEnabled()) { - log.info("La transaction a été supprimée avec succès."); - } - result = ServiceHelper.RESPOND_SUCCESS; - } else { - // Transaction bloquée - result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; - } - } else { - result = ServiceHelper.TRANSACTION_NOT_EXIST; - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result; - }*/ - - /* - * Supprime une transaction au format DTO. - * @param transactionDTO - * @return - * - public String removeTransaction(TransactionDTO transactionDTO) { - String result = removeTransaction(transactionDTO.getId()); - return result; - }*/ - - /* - * Permet d'ajouter une entrée comptable pour une transaction donnée. - * ATTENTION : la transaction doit être NON bloquée. - * - * @param description - * @param amount - * @param debit - * @param lettering - * @param detail - * @param transaction - * @return - * - public String addEntry(String description, String amount, boolean debit, - String lettering, String detail, Transaction transaction, - Account account) { - String result = ServiceHelper.RESPOND_ERROR; - // Si la transaction est non bloquée - if (!isTransactionBlocked(transaction)) { - // Si il renvoie succes et non l'identifiant (à commenter dans la classe correspondante) - result = entryServiceImpl.createEntry(description, amount, debit, - lettering, detail, transaction, account); - } else { - result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; - } - return result; - }*/ - - /* - * Permet d'ajouter une entrée comptable pour une transaction donnée. - * L'entrée est sous format DTO. - * - * @param entryDTO - * @return - * - public String addEntry(EntryDTO entryDTO) { - String result = ServiceHelper.RESPOND_ERROR; - // Recherche TransactionDTO - TransactionDTO transactonDTO = entryDTO.getTransactionDTO(); - Transaction transaction = searchTransactionWithTopiaId(transactonDTO); - // Si la transaction est non bloquée - if (!isTransactionBlocked(transaction)) { - - // Si il renvoie succes et non l'identifiant (à commenter dans la classe correspondante) - result = entryServiceImpl.createEntry(entryDTO); - } else { - result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; - } - return result; - }*/ - - /* - * Permet de modifier une entrée comptable. - * ATTENTION : la transaction doit être NON bloquée. - * - * @param topiaId - * @param description - * @param amount - * @param debit - * @param lettering - * @param detail - * @param transaction - * @param account - * @return - * - public String modifyEntry(String topiaId, String description, - String amount, boolean debit, String lettering, String detail, - Transaction transaction, Account account) { - String result = ServiceHelper.RESPOND_ERROR; - if (!isTransactionBlocked(transaction)) { - result = entryServiceImpl.modifyEntry(topiaId, description, amount, - debit, lettering, detail, account); - } else { - result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; - } - return result; - }*/ - - /* - * Permet de modifier une entrée. - * @param entryDTO - * @return - * - public String modifyEntry(EntryDTO entryDTO) { - String result = ServiceHelper.RESPOND_ERROR; - // Recherche TransactionDTO - TransactionDTO transactonDTO = entryDTO.getTransactionDTO(); - Transaction transaction = searchTransactionWithTopiaId(transactonDTO); - if (!isTransactionBlocked(transaction)) { - result = entryServiceImpl.modifyEntry(entryDTO); - } else { - result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; - } - return result; - }*/ - - /* - * Permet d'effacer une entrée comptable. Elle est identifiée par son identifiant - * topiaID. Une entrée peut être supprimée seulement si elle est non bloquée. - * @param topiaId - * @return - * - public String removeEntry(String topiaId) { - String result = ServiceHelper.RESPOND_ERROR; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); - // Recherche de l'entry - Entry entryDelete = entryDAO.findByTopiaId(topiaId); - // Entry doit exister - if (entryDelete != null) { - // Prend la transaction dont appartient entry - Transaction transaction = entryDelete.getTransaction(); - // Vérifie si la transaction est non bloquée. - if (!isTransactionBlocked(transaction)) { - // Création d'un log DTO - LogDTO logDTO = new LogDTO("", new Date(), - ServiceHelper.LOG_REMOVE, transaction - .getTransDate(), transaction - .getVoucherRef(), transaction - .getDescription(), entryDelete - .getDescription(), entryDelete.getAmount(), - entryDelete.getDebit(), entryDelete.getLettering()); - // Appel pour supprimer l'entrée - result = entryServiceImpl.removeEntry(topiaId); - // Si la suppression s'est bien déroulée, création log - if (result.equals(ServiceHelper.RESPOND_SUCCESS)) { - // Ajout du log - logServiceImpl.addLog(logDTO); - } - } else { - result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; - } - } else { - result = ServiceHelper.ENTRY_NOT_EXIST; - } - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return result; - }*/ - - /* - * Permet de supprimer une entrée à partir d'un DTO. - * @param entryDTO - * @return - * - public String removeEntry(EntryDTO entryDTO) { - String result = removeEntry(entryDTO.getId()); - return result; - }*/ - - /* - * Permet de vérifier si une transaction est dans une période bloquée ou non - * @param transaction - * @return - * - public boolean isTransactionBlocked(Transaction transaction) { - boolean isTransactionBlocked = true; - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - TransactionDAO transactionDAO = LimaCallaoDAOHelper - .getTransactionDAO(topiaContext); - // Recherche - Transaction transactionSearch = transactionDAO - .findByTopiaId(transaction.getTopiaId()); - isTransactionBlocked = timeSpanServiceImpl - .isTimeSpanBlocked(transactionSearch.getTimeSpan()); - // Fermeture BDD - topiaContext.closeContext(); - } catch (TopiaException e) { - log.error(e); - } - return isTransactionBlocked; - }*/ - - /* - * Permet de vérifier si une transaction est équilibrée. - * @param transaction - * @return - * - public boolean isTransactionBalanced(Transaction transaction) { - List<EntryDTO> ListEntryDTO = entryServiceImpl - .searchEntryDTOWithTransaction(transaction); - float debit = 0; - float credit = 0; - // Pour toutes les entrées comptables trouvées - for (EntryDTO entryDTO : ListEntryDTO) { - // Si entrée au debit - if (entryDTO.isDebit()) { - debit = debit - + Float.parseFloat(entryDTO.getAmount().replaceFirst( - ",", ".")); - } else { - credit = credit - + Float.parseFloat(entryDTO.getAmount().replaceFirst( - ",", ".")); - } - } - // Vérifie si le debit == credit - boolean isTransactionBalanced = debit == credit; - return isTransactionBalanced; - }*/ - -} \ No newline at end of file Deleted: trunk/lima-business/src/main/java/org/chorem/lima/business/UserServiceImpl.java =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/UserServiceImpl.java 2010-03-23 13:45:06 UTC (rev 2810) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/UserServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -1,116 +0,0 @@ -/* - * *##% Callao - * Copyright (C) 2010 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser 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 Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.business; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.chorem.lima.entity.LimaCallaoDAOHelper; -import org.chorem.lima.entity.User; -import org.chorem.lima.entity.UserDAO; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; - -/** - * User service. - * - * @author chatellier - * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ - */ -public class UserServiceImpl { - - /** log */ - private static final Log log = LogFactory.getLog(UserServiceImpl.class); - - private TopiaContext rootContext; - - public UserServiceImpl() { - LimaConfig config = LimaConfig.getInstance(); - try { - rootContext = TopiaContextFactory.getContext(config.getOptions()); - } catch (TopiaNotFoundException ex) { - if (log.isErrorEnabled()) { - log.error("Can't init topia context", ex); - } - } - } - - /** - * Add new user. - * - * @param name new user name - * @throws LimaException - */ - public void addUser(User user/*String name*/) throws LimaException { - /*// Attention doublon utilisateur - try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - UsersDAO userdao = LimaCallaoDAOHelper.getUsersDAO(topiaContext); - // Création de l'user - Users newuser = userdao.create(); - newuser.setMatcher(name); - // Création BDD - topiaContext.commitTransaction(); - topiaContext.closeContext(); - if (log.isInfoEnabled()) { - log.info("Add user : " + name); - } - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Can't create user", ex); - throw new LimaException("Can't create user", ex); - } - - }*/ - } - - /** - * Find user with name. - * - * @param name - * @throws LimaException - */ - public void findUser(String name) throws LimaException { - /*try { - // Acces BDD - TopiaContext topiaContext = rootContext.beginTransaction(); - // Chargement du DAO - UsersDAO userdao = LimaCallaoDAOHelper.getUsersDAO(topiaContext); - // Recherche du user - Users newuser = userdao.findByMatcher(name); - // Fermeture BDD - topiaContext.closeContext(); - if (newuser == null) { - throw new LimaBusinessException("can't find user " + name); - } - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("Can't find user", ex); - throw new LimaException("Can't find user", ex); - } - }*/ - } -} Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/AccountServiceImpl.java (from rev 2807, trunk/lima-business/src/main/java/org/chorem/lima/business/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 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,803 @@ +/* + * *##% Callao AccountServiceImpl + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +import static org.nuiton.i18n.I18n._; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Stateless; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.AccountService; +import org.chorem.lima.business.LimaBusinessException; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.AccountDAO; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryDAO; +import org.chorem.lima.entity.LimaCallaoDAOHelper; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaNotFoundException; + +/** + * 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 + * renseigné si il appartient à un compte père avec le numéro de compte père. + * + * @author Rémi Chapelet + */ +@Stateless +public class AccountServiceImpl implements AccountService { + + private static final Log log = LogFactory.getLog(AccountServiceImpl.class); + + private TopiaContext rootContext; + + //private ConvertAccount convertAccount = new ConvertAccount(); + + public AccountServiceImpl() { + LimaConfig config = LimaConfig.getInstance(); + try { + rootContext = TopiaContextFactory.getContext(config.getOptions()); + } catch (TopiaNotFoundException ex) { + if (log.isErrorEnabled()) { + log.error("Can't init topia context", ex); + } + } + } + + /** + * Permet de créer un nouveau compte dans le PCG de l'application. + * Il ne peut exister deux numéros identiques. Pour chaque nouveau compte, + * il est vérifié si il n'existe pas un compte avec le numéro donné. Dans ce + * cas présent, le compte n'est pas créé. + * ATTENTION : le compte masterAccount, c'est à dire le compte père, doit + * exister, sinon le compte n'est pas créé. Si le compte n'a pas de père, alors + * mettre masterAccount à null. + * + * @param account account to create + * @throws LimaException + */ + @Override + public void createAccount(Account masterAccount, Account account) throws LimaException { + + // test la validite du numero de compte + if (StringUtils.isBlank(account.getAccountNumber())) { + throw new LimaBusinessException("Invalid AccountNumber : " + account.getAccountNumber()); + } + + TopiaContext transaction = null; + try { + // basic check done, make check in database + // TODO move it into JTA + transaction = rootContext.beginTransaction(); + + // test si le numero de compte existe deja + AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(transaction); + List<Account> existingAccounts = accountDAO.findAllByAccountNumber(account.getAccountNumber()); + if (CollectionUtils.isNotEmpty(existingAccounts)) { + throw new LimaBusinessException(_("An account already exists with this number : %s", account.getAccountNumber())); + } + + accountDAO.create(account); + + // test si le compte parent existe; + if (masterAccount != null) { + masterAccount.addSubAccounts(account); + accountDAO.update(masterAccount); + } + + // commit + transaction.commitTransaction(); + } + catch (TopiaException ex) { + if (transaction != null) { + try { + transaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't create account", ex); + } + finally { + if (transaction != null) { + try { + transaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't create account", ex); + } + } + } + } + /*public String createAccount (String accountNumber, String label,Account masterAccount,String type) + { + String result = ServiceHelper.RESPOND_ERROR; + // Détermine si le compte existe déjà ou non + boolean existAccount = existAccount(accountNumber); + // Si le numéro de compte existe + if (existAccount) + { + if (log.isWarnEnabled()) { + log.warn("Le compte numéro "+accountNumber+" existe deja !"); + } + result = ServiceHelper.ACCOUNT_DOUBLE; + } else { + // Création du compte + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(topiaContext); + + //Le compte a un père + + if ( masterAccount != null ) + { + // Vérification que le compte père existe dans la base de données + boolean existMasterAccount = existAccount(masterAccount.getAccountNumber()); + // Si le compte père n'existe pas + if (!existMasterAccount) + { + if (log.isWarnEnabled()) { + log.warn("Le compte père numéro "+accountNumber+" n'existe pas !"); + } + result = ServiceHelper.ACCOUNT_NOT_MASTER; + } else { + // Creation du compte + Account newAccount = accountDAO.create(); + newAccount.setAccountNumber(accountNumber); + newAccount.setLabel(label); + newAccount.setMasterAccount(masterAccount); + newAccount.setType(type); + // Création BDD + topiaContext.commitTransaction(); + result = ServiceHelper.RESPOND_SUCCESS; + } + } else { + // Le compte n'a pas de père + // Creation du compte + Account newAccount = accountDAO.create(); + newAccount.setAccountNumber(accountNumber); + newAccount.setLabel(label); + newAccount.setType(type); + // Création BDD + topiaContext.commitTransaction(); + result = ServiceHelper.RESPOND_SUCCESS; + } + // Fermeture BDD + topiaContext.closeContext(); + }catch (TopiaException e) { + log.error(e); + } + } + return result; + }*/ + + + /* + * Permet de créer un compte à partir du numéro de compte père. Il appelle + * ensuite createAccount avec le compte père. + * @param accountNumber numéro du compte à créer + * @param label label pour le compte + * @param maserAccountNumber numéro du compte père, si il en a pas, mettre 0. + * @return + * + public String createAccount(String accountNumber, String label, + String masterAccountNumber, String type) { + String result = ServiceHelper.RESPOND_ERROR; + // Recherche le compte Master + Account masterAccount = searchAccount(masterAccountNumber); + // Si le compte père n'existe pas + if (masterAccount == null && !masterAccountNumber.equals("0")) { + if (log.isWarnEnabled()) { + log.warn("Le compte père numéro " + masterAccountNumber + + " n'existe pas !"); + } + result = ServiceHelper.ACCOUNT_NOT_MASTER; + } else { + // Création du compte + result = createAccount(accountNumber, label, masterAccount, type); + } + return result; + }*/ + + /* + * Permet de creer un compte à partir d'un objet DTO + * @param accountDTO compte au format DTO + * @return + * + public String createAccount(AccountDTO accountDTO) { + String result; + String result_final; + boolean error = false; // Si il y a eu une erreur pour créer les enfants + + // Création du compte père + result = createAccount(accountDTO.getAccountNumber(), accountDTO + .getLabel(), accountDTO.getMasterAccount(), accountDTO + .getType()); + // Création des comptes enfants + + // Pour chaque enfant + for (AccountDTO accountChildDTO : accountDTO.getAccountChildDTO()) { + // Création de l'enfant + result = createAccount(accountChildDTO); + // Si il y a eu une erreur + if (!result.equals(ServiceHelper.RESPOND_SUCCESS)) { + if (log.isWarnEnabled()) { + log.warn("Le compte numéro " + accountChildDTO.getLabel() + + " n'a pu être créé !"); + } + error = true; + result_final = result; + } + } + // Si il y a eu une erreur lors de la création d'un enfant, il est envoyé une erreur. + if (error) { + result = ServiceHelper.RESPOND_ERROR; + } + return result; + }*/ + + /* + * Recherche un compte DTO. Il est recherché dans la base de données et est + * converti avec ConvertAccount. ConvertAccount recherche dans la liste de + * ses enfants pour les convertir également, et ainsi de suite. + * @param accountNumber numéro du compte qu'on souhait rechercher + * @return + * + public AccountDTO searchAccountDTO(String accountNumber) { + AccountDTO accountDTO = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper + .getAccountDAO(topiaContext); + // Recherche du compte + Account account = accountDAO.findByAccountNumber(accountNumber); + // Converti entity en DTO + convertAccount.setTransaction(topiaContext); + accountDTO = convertAccount.accountEntityToDto(account, null); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return accountDTO; + }*/ + + /* + * Permet de rechercher un compte à partir d'un numéro de compte. + * @param accountNumber numéro du compte à rechercher + * @return + * + public Account searchAccount(String accountNumber) { + Account accountResult = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper + .getAccountDAO(topiaContext); + // Recherche du compte + accountResult = accountDAO.findByAccountNumber(accountNumber); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return accountResult; + }*/ + + /* + * Permet de renvoyer tous les enfants du compte. + * Cette fonction permet de renvoyer les enfants, mais PAS les enfants des + * enfants (et ainsi de suite). Cette méthode descend donc uniquement d'un + * niveau sur la hiérarchie. + * @param account compte dont on souhaite obtenir ses enfants. + * @return + * + public List<Account> searchListChildAccount(Account account) { + List<Account> ListAccount = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper + .getAccountDAO(topiaContext); + // Recherche des comptes enfants + ListAccount = accountDAO.findAllByMasterAccount(account); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return ListAccount; + }*/ + + /* + * Permet de renvoyer tous les enfants du compte. Elle se base sur la fonction + * searchListChildAccount(Account account). + * Cette fonction permet de renvoyer les enfants, mais PAS les enfants des + * enfants (et ainsi de suite). Cette méthode descend donc uniquement d'un + * niveau sur la hiérarchie. + * @param account numéro de compte dont on souhaite obtenir ses enfants. + * @return + * + public List<Account> searchListChildAccount(String accountNumber) { + List<Account> ListAccount = null; + // Recherche le compte + Account account = searchAccount(accountNumber); + // Si le compte n'existe pas + if (account == null) { + if (log.isWarnEnabled()) { + log.warn("Le compte numéro " + accountNumber + + " n'existe pas !"); + } + } else { + // Recherche des comptes enfants + ListAccount = searchListChildAccount(account); + } + return ListAccount; + }*/ + + /** + * Permet de convertir tous les comptes en DTO. Il recherche dans un premier + * temps tous les comptes "master". + * + * @return + * @throws LimaException + */ + @Override + public List<Account> getAllAccounts() throws LimaException { + /*ArrayList<AccountDTO> listAccountDTO = new ArrayList<AccountDTO>(); + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper + .getAccountDAO(topiaContext); + // Recherche des comptes enfants + List<Account> listAccount = accountDAO.findAll(); + // Pour chaque compte + // Converti entity en DTO + convertAccount.setTransaction(topiaContext); + for (Account account : listAccount) { + // Pour les comptes sans père + if (account.getMasterAccount() == null) { + AccountDTO accountDTO = convertAccount.accountEntityToDto( + account, null); + listAccountDTO.add(accountDTO); + } + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return listAccountDTO;*/ + + List<Account> accountsList = new ArrayList<Account>(); + + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(transaction); + List<Account> accounts = accountDAO.findAll(); + accountsList.addAll(accounts); + } + catch (TopiaException ex) { + if (transaction != null) { + try { + transaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't create account", ex); + } + finally { + if (transaction != null) { + try { + transaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't create account", ex); + } + } + } + + return accountsList; + } + + /* + * Renvoie vrai si le compte avec son numéro existe déjà dans la base de + * données. + * @param accountNumber numéro du compte recherché + * @return + * + public boolean existAccount(String accountNumber) { + // Recherche du compte + Account accountSearch = searchAccount(accountNumber); + boolean result = false; + // Si le compte est trouvé + if (accountSearch != null) { + result = true; + } + return result; + }*/ + + /** + * Permet d'effacer un compte dans la base de données. + * + * Il est vérifié dans un premier temps si le compte existe bien. + * ATTENTION : si il existe une entrée comptable associée au numéro de + * compte, il est alors impossible de supprimer le compte. + * + * @param account + * @throws LimaException + */ + @Override + public void removeAccount(Account account) throws LimaException { + /*String result = ServiceHelper.RESPOND_ERROR; + Account deleteAccount = searchAccount(accountNumber); + // Si le compte n'existe pas + if (deleteAccount == null) { + if (log.isWarnEnabled()) { + log.warn("Le compte numéro " + accountNumber + + " n'existe pas !"); + } + result = ServiceHelper.ACCOUNT_NOT_EXIST; + } else // Sinon on efface le compte + { + // Vérifie si une entrée ne possède pas ce numéro de compte. + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryDAO entryDAO = LimaCallaoDAOHelper + .getEntryDAO(topiaContext); + // Recherche au moins une entry avec ce compte. + Entry entry = entryDAO.findByAccount(deleteAccount); + // Il existe au moins une entrée + if (entry != null) { + if (log.isWarnEnabled()) { + log.warn("Le compte numéro " + accountNumber + + " possède des entrées comptable !"); + } + result = ServiceHelper.ACCOUNT_WITH_ENTRIES; + } else { + // On efface tous les comptes enfants + List<Account> listAccountChild = searchListChildAccount(deleteAccount); + boolean ErrorRemoveChild = false; + for (Account accountChild : listAccountChild) { + // Si on souhaite supprimer les comptes enfants + result = removeAccount(accountChild.getAccountNumber()); + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + ErrorRemoveChild = true; + if (log.isErrorEnabled()) { + log.error("Le compte fils numéro " + + accountChild.getAccountNumber() + + " n'a pas été supprimé !"); + } + } + // + // Si on ne souhaite pas supprimer les comptes enfants, tous les + // comptes enfants se retrouvent sans père. Commenter removeAccountChildTest + // dans le fichier AccountServiceImplTest dans ce cas. + + //modifyAccount(accountChild.getAccountNumber(),accountChild.getLabel(),null); + } + // Si il n'a jamais eu d'erreur pour supprimer ses fils + if (!ErrorRemoveChild) { + + //// Efface le compte père + + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper + .getAccountDAO(topiaContext); + // Supprime le compte + accountDAO.delete(deleteAccount); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + result = ServiceHelper.RESPOND_SUCCESS; + if (log.isInfoEnabled()) { + log.info("Le compte numéro " + accountNumber + + " a ete supprimé avec succès."); + } + } + } + } catch (TopiaException e) { + log.error(e); + } + } + return result;*/ + + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + // Vérifie si une entrée ne possède pas ce numéro de compte. + // FIXME !IMPORTANT! check that subaccounts have no entries too + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(transaction); + Entry firstEntry = entryDAO.findByAccount(account); + + if (firstEntry != null) { + throw new LimaBusinessException("Can't delete account with entries"); + } + + // remove account + // FIXME !IMPORTANT! check that subaccounts are also deleted + AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(transaction); + accountDAO.delete(account); + } + catch (TopiaException ex) { + if (transaction != null) { + try { + transaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't delete account", ex); + } + finally { + if (transaction != null) { + try { + transaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't delete account", ex); + } + } + } + } + + /* + * Permet d'effacer un compte à partir d'un compte DTO. Il appelle la + * méthode removeAccount, qui effacera également les enfants (et ainsi de + * suite dans la hiérarchie du compte). + * @param accountDTO Compte au format DTO qu'on souhaite supprimer. + * @return + * + public String removeAccount(AccountDTO accountDTO) { + String result; + result = removeAccount(accountDTO.getAccountNumber()); + return result; + }*/ + + /** + * Permet de modifier un compte sur son label et son compte père. + * + * 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 accountNumber numéro de compte à modifier + * @param label label à modifier + * @param masterAccountNumber compte père à modifier + + * @throws LimaException + */ + @Override + public void updateAccount(Account account) throws LimaException { + /*String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper + .getAccountDAO(topiaContext); + // Recherche du compte + Account modifyAccount = accountDAO + .findByAccountNumber(accountNumber); + // Si le compte n'existe pas + if (modifyAccount == null) { + if (log.isWarnEnabled()) { + log.warn("Le compte numéro " + accountNumber + + " n'existe pas !"); + } + result = ServiceHelper.ACCOUNT_NOT_EXIST; + } else { + + // Modifie le compte + modifyAccount.setLabel(label); + modifyAccount.setType(type); + // Recherche du compte père + // Si il possède un compte père + if (masterAccount != null) { + modifyAccount.setMasterAccount(masterAccount); + } + modifyAccount.update(); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + result = ServiceHelper.RESPOND_SUCCESS; + } + } catch (TopiaException e) { + log.error(e); + } + return result;*/ + + TopiaContext transaction = null; + try { + transaction = rootContext.beginTransaction(); + + // update account + AccountDAO accountDAO = LimaCallaoDAOHelper.getAccountDAO(transaction); + accountDAO.update(account); + } + catch (TopiaException ex) { + if (transaction != null) { + try { + transaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't update account", ex); + } + finally { + if (transaction != null) { + try { + transaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't update account", ex); + } + } + } + } + + /* + * Permet de modifier un compte sur son label et son compte père. + * Il recherche le compte père avec le numéro de compte fourni. Appel ensuite + * la méthode modifyAccount avec pour paramètre le compte père trouvé. + * @param accountNumber numéro de compte à modifier + * @param label label à modifier + * @param masterAccountNumber le numéro du compte père + * @return + * + public String modifyAccount(String accountNumber, String label, + String type, String masterAccountNumber) { + String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper + .getAccountDAO(topiaContext); + + // Modifie le compte + // Recherche du compte père + Account masterAccount = accountDAO + .findByAccountNumber(masterAccountNumber); + result = modifyAccount(accountNumber, label, type, masterAccount); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result; + }*/ + + /* + * Permet de modifier un compte à partir d'un compte DTO. + * @param accountDTO compte au format DTO qu'on souhaire modifier. + * @return + * + public String modifyAccount(AccountDTO accountDTO) { + String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + AccountDAO accountDAO = LimaCallaoDAOHelper + .getAccountDAO(topiaContext); + // Recherche du compte père + Account masterAccount = accountDAO.findByAccountNumber(accountDTO + .getMasterAccount()); + result = modifyAccount(accountDTO.getAccountNumber(), accountDTO + .getLabel(), accountDTO.getType(), masterAccount); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result; + }*/ + + /* + * Permet de mettre à jour le compte DTO ainsi que tous ses fils. + * Cette méthode permet d'ajouter, modifier, et supprimer un compte et + * ses enfants (et ainsi de suite). + * @param accountDTO + * @return + * + public String updateDTO(AccountDTO accountDTO) { + String result; + // Si le compte DTO père existe + if (existAccount(accountDTO.getAccountNumber())) { + // Modification du compte père + result = modifyAccount(accountDTO); + } else { + // Création du compte père + result = createAccount(accountDTO); + } + // Pour chaque enfant on lance l'update + for (AccountDTO accountChildDTO : accountDTO.getAccountChildDTO()) { + updateDTO(accountChildDTO); + } + + // On recherche les comptes DTO effacés + List<Account> listAccountChild = searchListChildAccount(accountDTO + .getAccountNumber()); + for (Account account : listAccountChild) { + // Si le compte n'est pas dans la liste, alors on efface + if (!accountDTO.existAccountChild(account.getAccountNumber())) { + result = removeAccount(account.getAccountNumber()); + } + } + return result; + }*/ + +} \ No newline at end of file Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/EntryServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/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 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,382 @@ +/* + * *##% Callao EntryServiceImpl + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.entity.Entry; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaNotFoundException; + +/** + * Cette classe permet de contrôler les différentes saisies possibles dans + * Callao. Ces saisies sont transmises à la base de données par la classe + * Entry. Chaque action sur une entrée déclenche une création d'un log. + * Chaque opération comptable doit faire appel également au contrôl de la + * période comptable sur laquelle l'entry repose. Ainsi il n'est possible + * d'ajouter/modifier/supprimer une entrée si la période est bloquée. + * + * @author Rémi Chapelet + */ +public class EntryServiceImpl { // implements EntryService { + + private static final Log log = LogFactory.getLog(EntryServiceImpl.class); + + private TopiaContext rootContext; + + private LogServiceImpl logServiceImpl = new LogServiceImpl(); + + // TODO A revoir car transaction a besoin de entry et vice versa + private static TransactionServiceImpl transactionServiceImpl = new TransactionServiceImpl(); + + private AccountServiceImpl accountServiceImpl = new AccountServiceImpl(); + + public EntryServiceImpl() { + LimaConfig config = LimaConfig.getInstance(); + try { + rootContext = TopiaContextFactory.getContext(config.getOptions()); + } catch (TopiaNotFoundException ex) { + if (log.isErrorEnabled()) { + log.error("Can't init topia context", ex); + } + } + } + + /** + * Création d'une entrée comptable. + * La période ne doit PAS être bloquée. + * + * @return + */ + public void createEntry(Entry entry /*String description, String amount, boolean debit, + String lettering, String detail, Transaction transaction, + Account account*/) { + /*String result = isCorrectEntry(transaction, account); + if (result.equals(ServiceHelper.RESPOND_SUCCESS)) { + result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryDAO entryDAO = LimaCallaoDAOHelper + .getEntryDAO(topiaContext); + // Creation de l'entrée comptable + Entry newEntry = entryDAO.create(); + newEntry.setDescription(description); + // On formate le nombre + newEntry.setAmount(numberUtil.format(amount)); + newEntry.setDebit(debit); + newEntry.setLettering(lettering); + newEntry.setDetail(detail); + newEntry.setTransaction(transaction); + newEntry.setAccount(account); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + if (log.isInfoEnabled()) { + log.info("Ajout avec succes de l'entrée comptable."); + } + // Création du log + Date logDate = new Date(); + logServiceImpl.addLog(logDate, transaction.getTransDate(), + ServiceHelper.LOG_ADD, transaction.getVoucherRef(), + transaction.getDescription(), detail, amount, debit, + lettering); + + // Il renvoie soit l'identifiant topiaId ou SUCCESS. + result = newEntry.getTopiaId(); + //result = ServiceHelper.RESPOND_SUCCESS; + } catch (TopiaException e) { + log.error(e); + } + } + return result;*/ + } + + /* + * Permet de créer une entrée comptable à partir de son DTO. + * @param entryDTO + * @return + * + public String createEntry(EntryDTO entryDTO) { + // Recherche TransactionDTO + TransactionDTO transactonDTO = entryDTO.getTransactionDTO(); + Transaction transaction = transactionServiceImpl + .searchTransactionWithTopiaId(transactonDTO); + // Recherche AccountDTO + AccountDTO accountDTO = entryDTO.getAccountDTO(); + Account account = accountServiceImpl.searchAccount(accountDTO + .getAccountNumber()); + // Création entry + String result = createEntry(entryDTO.getDescription(), entryDTO + .getAmount(), entryDTO.isDebit(), entryDTO.getLettering(), + entryDTO.getDetail(), transaction, account); + return result; + }*/ + + /* + * Vérifie que les objets transaction et account ne sont pas nulls. + * @param transaction + * @param account + * @return + * + public String isCorrectEntry(Transaction transaction, Account account) { + String result = ServiceHelper.RESPOND_SUCCESS; + // Vérification si timeSpan et Journal existe bien + if (account == null) { + if (log.isErrorEnabled()) { + log.error("Création entry : Le account n'existe pas."); + } + result = ServiceHelper.ACCOUNT_NOT_EXIST; + } + if (transaction == null) { + if (log.isErrorEnabled()) { + log.error("Création entry : La transaction n'existe pas."); + } + result = ServiceHelper.TRANSACTION_NOT_EXIST; + } + return result; + }*/ + + /* + * Recherche toutes les entrées comptables d'une transaction. + * @param transaction + * @return + * + public List<Entry> searchEntryWithTransaction(Transaction transaction) { + List<Entry> listEntry = null; + if (transaction != null) { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryDAO entryDAO = LimaCallaoDAOHelper + .getEntryDAO(topiaContext); + // Recherche + listEntry = entryDAO.findAllByTransaction(transaction); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + } + return listEntry; + }*/ + + /* + * Recherche toutes les entrées comptables d'une transaction, et renvoie + * au format DTO. + * @param transaction + * @return + * + public List<EntryDTO> searchEntryDTOWithTransaction(Transaction transaction) { + List<EntryDTO> listEntryDTO = new ArrayList<EntryDTO>(); + // Si la transaction est trouvée + if (transaction != null) { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryDAO entryDAO = LimaCallaoDAOHelper + .getEntryDAO(topiaContext); + // Recherche toutes les entrées comptables de la transaction + List<Entry> listEntry = entryDAO + .findAllByTransaction(transaction); + // Pour chaque entry, on fait appel au convertisseur pour avoir en DTO + convertEntry.setTransaction(topiaContext); + for (Entry entry : listEntry) { + EntryDTO entryDTO = convertEntry.entryEntityToDto(entry); + // On ajoute le nouvel DTO + listEntryDTO.add(entryDTO); + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + } + return listEntryDTO; + }*/ + + /* + * Recherche les entrées comptables pour une transaction donnée au format DTO. + * @param transactionTopiaId identifiant de la transaction + * @return + * + public List<EntryDTO> searchEntryDTOWithTransaction( + String transactionTopiaId) { + List<EntryDTO> listEntryDTO = new ArrayList<EntryDTO>(); + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); + // Recherche de la transaction + Transaction transaction = transactionServiceImpl + .searchTransactionWithTopiaId(transactionTopiaId); + // Si la transaction est trouvée + if (transaction != null) { + // Recherche toutes les entrées comptables de la transaction + List<Entry> listEntry = entryDAO + .findAllByTransaction(transaction); + // Pour chaque entry, on fait appel au convertisseur pour avoir en DTO + convertEntry.setTransaction(topiaContext); + for (Entry entry : listEntry) { + EntryDTO entryDTO = convertEntry.entryEntityToDto(entry); + // On ajoute l'entrée DTO + listEntryDTO.add(entryDTO); + } + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return listEntryDTO; + }*/ + + /* + * Recherche les entrées comptables pour une transaction donnée au format DTO. + * @param transactionDTO + * @return + * + public List<EntryDTO> searchEntryDTOWithTransaction( + TransactionDTO transactionDTO) { + List<EntryDTO> listEntryOfTransaction = searchEntryDTOWithTransaction(transactionDTO + .getId()); + return listEntryOfTransaction; + }*/ + + /* + * Permet d'effacer une entrée comptable à partir de son identifiant topia. + * @param topiaId + * @return + * + public String removeEntry(String topiaId) { + String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); + // Recherche de l'entry + Entry entryDelete = entryDAO.findByTopiaId(topiaId); + // Si l'entry existe alors on supprime + if (entryDelete != null) { + // Supprime + entryDAO.delete(entryDelete); + // Création BDD + topiaContext.commitTransaction(); + result = ServiceHelper.RESPOND_SUCCESS; + } else { + result = ServiceHelper.ENTRY_NOT_EXIST; + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result; + }*/ + + /* + * Permet d'effacer une entrée comptable au format DTO. + * @param entryDTO + * @return + * + public String removeEntry(EntryDTO entryDTO) { + String result = removeEntry(entryDTO.getId()); + return result; + }*/ + + /* + * Modification d'une entrée comptable. + * @param topiaId + * @param description + * @param amount + * @param debit + * @param lettering + * @param detail + * @param transaction + * @param account + * @return + * + public String modifyEntry(String topiaId, String description, + String amount, boolean debit, String lettering, String detail, + Account account) { + String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); + // Recherche Entry + Entry entry = entryDAO.findByTopiaId(topiaId); + entry.setDescription(description); + // On formate le nombre + entry.setAmount(numberUtil.format(amount)); + entry.setDebit(debit); + entry.setLettering(lettering); + entry.setDetail(detail); + entry.setAccount(account); + entry.update(); + // Création BDD + topiaContext.commitTransaction(); + // Chargement DAO transaction + Transaction transaction = entry.getTransaction(); + if (log.isInfoEnabled()) { + log.info("Edit avec succes de l'entrée comptable."); + } + // Création du log + Date logDate = new Date(); + logServiceImpl.addLog(logDate, transaction.getTransDate(), + ServiceHelper.LOG_MODIFY, transaction.getVoucherRef(), + transaction.getDescription(), detail, amount, debit, + lettering); + result = ServiceHelper.RESPOND_SUCCESS; + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result; + }*/ + + /* + * Permet de modifier une entrée comptable. + * @param entryDTO + * @return + * + public String modifyEntry(EntryDTO entryDTO) { + // Recherche AccountDTO + AccountDTO accountDTO = entryDTO.getAccountDTO(); + Account account = accountServiceImpl.searchAccount(accountDTO + .getAccountNumber()); + // Modification entry + String result = modifyEntry(entryDTO.getId(), + entryDTO.getDescription(), entryDTO.getAmount(), entryDTO + .isDebit(), entryDTO.getLettering(), entryDTO + .getDetail(), account); + return result; + }*/ +} Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FilesServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/FilesServiceImpl.java) =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FilesServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/FilesServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,667 @@ +/* + * *##% Callao FilesServiceImpl + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.dto.AccountDTO; +import org.chorem.lima.business.dto.EntryDTO; +import org.chorem.lima.business.dto.JournalDTO; +import org.chorem.lima.business.dto.PeriodDTO; +import org.chorem.lima.business.dto.TimeSpanDTO; +import org.chorem.lima.business.dto.TransactionDTO; +import org.chorem.lima.business.utils.DateUtil; +import org.chorem.lima.business.utils.ServiceHelper; +import org.jdom.Attribute; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.input.SAXBuilder; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; +import org.jdom.xpath.XPath; +import org.nuiton.topia.TopiaContext; + +/** + * Cette classe permet d'importer et exporter des données comptables. Ces données + * sont au format xml. + * + * @author Rémi Chapelet + */ +public class FilesServiceImpl { // implements FilesService { + + /** + * log + */ + private static final Log log = LogFactory.getLog(FilesServiceImpl.class); + + static Element racine = new Element("Callao"); + + static org.jdom.Document document = new Document(racine); + + private static DateUtil dateUtil = new DateUtil(); + + private AccountServiceImpl accountServiceImpl = new AccountServiceImpl(); + + private EntryServiceImpl entryServiceImpl = new EntryServiceImpl(); + + private JournalServiceImpl journalServiceImpl = new JournalServiceImpl(); + + private PeriodServiceImpl periodServiceImpl = new PeriodServiceImpl(); + + private TimeSpanServiceImpl timeSpanServiceImpl = new TimeSpanServiceImpl(); + + private TransactionServiceImpl transactionServiceImpl = new TransactionServiceImpl(); + + /** + * Cete méthode permet d'exporter des données de Callao vers un fichier au + * format xml. + * + * @param nameFile + */ + public void exportDatas(String nameFile) { + /*if (log.isDebugEnabled()) { + log.debug("Save file XML : "); + } + + // Partie Informations + Element info = new Element("informations"); + racine.addContent(info); + Attribute date = new Attribute("date", new Date().toString()); + info.setAttribute(date); + Attribute user = new Attribute("user", "Name user"); + info.setAttribute(user); + Attribute company = new Attribute("company", "Name company"); + info.setAttribute(company); + + // Partie Save + + // Création Element save + Element save = new Element("save"); + racine.addContent(save); + + // Period + + // Création élément liste de périods + Element periods = new Element("periods"); + // Création élément liste de timespans + Element timeSpans = new Element("timespans"); + save.addContent(periods); + save.addContent(timeSpans); + // Recherche de la liste de toutes les périodes et leurs timeSpans en DTO + List<PeriodDTO> listPeriodDTO = periodServiceImpl.getAllPeriod(); + // Pour chaque période + for (PeriodDTO periodDTO : listPeriodDTO) { + // Création élément périod + Element period = new Element("period"); + periods.addContent(period); + // Identifiant période + Attribute id = new Attribute("id", periodDTO.getId()); + period.setAttribute(id); + // BeginPeriod + // Découpage date + String dateTab[] = dateUtil.arrayDate(periodDTO.getBeginPeriod()); + Attribute beginYear = new Attribute("beginYear", dateTab[0]); + period.setAttribute(beginYear); + Attribute beginMonth = new Attribute("beginMonth", dateTab[1]); + period.setAttribute(beginMonth); + Attribute beginDay = new Attribute("beginDay", dateTab[2]); + period.setAttribute(beginDay); + // EndPeriod + dateTab = dateUtil.arrayDate(periodDTO.getEndPeriod()); + Attribute endYear = new Attribute("endYear", dateTab[0]); + period.setAttribute(endYear); + Attribute endMonth = new Attribute("endMonth", dateTab[1]); + period.setAttribute(endMonth); + Attribute endDay = new Attribute("endDay", dateTab[2]); + period.setAttribute(endDay); + // Locked Period + if (periodDTO.isLocked()) { + Attribute locked = new Attribute("locked", "true"); + period.setAttribute(locked); + } else { + Attribute locked = new Attribute("locked", "false"); + period.setAttribute(locked); + } + + // TimeSpan + + // Recherche des timeSpans de la période + List<TimeSpanDTO> listTimeSpanDTO = periodDTO.getListTimeSpan(); + // Pour chaque timeSpan + for (TimeSpanDTO timeSpanDTO : listTimeSpanDTO) { + Element timeSpan = new Element("timespan"); + timeSpans.addContent(timeSpan); + // Identifiant timeSpan + Attribute idTimeSpan = new Attribute("id", timeSpanDTO.getId()); + timeSpan.setAttribute(idTimeSpan); + Attribute idPeriod = new Attribute("idPeriod", periodDTO + .getId()); + timeSpan.setAttribute(idPeriod); + // Begin TimeSpan + // Découpage date + dateTab = dateUtil.arrayDate(timeSpanDTO.getBeginTimeSpan()); + Attribute beginYearTimeSpan = new Attribute("beginYear", + dateTab[0]); + timeSpan.setAttribute(beginYearTimeSpan); + Attribute beginMonthTimeSpan = new Attribute("beginMonth", + dateTab[1]); + timeSpan.setAttribute(beginMonthTimeSpan); + Attribute beginDayTimeSpan = new Attribute("beginDay", + dateTab[2]); + timeSpan.setAttribute(beginDayTimeSpan); + // End TimeSpan + dateTab = dateUtil.arrayDate(timeSpanDTO.getEndTimeSpan()); + Attribute endYearTimeSpan = new Attribute("endYear", dateTab[0]); + timeSpan.setAttribute(endYearTimeSpan); + Attribute endMonthTimeSpan = new Attribute("endMonth", + dateTab[1]); + timeSpan.setAttribute(endMonthTimeSpan); + Attribute endDayTimeSpan = new Attribute("endDay", dateTab[2]); + timeSpan.setAttribute(endDayTimeSpan); + // Lock timeSpan + if (timeSpanDTO.isLocked()) { + Attribute locked = new Attribute("locked", "true"); + timeSpan.setAttribute(locked); + } else { + Attribute locked = new Attribute("locked", "false"); + timeSpan.setAttribute(locked); + } + } + } + + // Journal + + Element journals = new Element("journals"); + save.addContent(journals); + List<JournalDTO> listJournalDTO = journalServiceImpl.getAllJournal(); + for (JournalDTO journalDTO : listJournalDTO) { + Element journal = new Element("journal"); + journals.addContent(journal); + // Identification du journal + Attribute idJournal = new Attribute("id", journalDTO.getId()); + journal.setAttribute(idJournal); + // Label + Attribute label = new Attribute("label", journalDTO.getLabel()); + journal.setAttribute(label); + // Prefix + Attribute prefix = new Attribute("prefix", journalDTO.getPrefix()); + journal.setAttribute(prefix); + // Description + Attribute description = new Attribute("description", journalDTO + .getDescription()); + journal.setAttribute(description); + } + + // Account + + Element accounts = new Element("accounts"); + save.addContent(accounts); + List<AccountDTO> listAccountDTO = accountServiceImpl.getAllAccount(); + // Appel une fonction récursive pour parcourir l'arborescence des comptes + accountXML(listAccountDTO, accounts); + + // Transaction + Element transactions = new Element("transactions"); + save.addContent(transactions); + Element entries = new Element("entries"); + save.addContent(entries); + // Recherche de toutes les transactions + List<TransactionDTO> listTransactionDTO = transactionServiceImpl + .getAllTransactionDTO(); + // Pour chaque transaction + for (TransactionDTO transactionDTO : listTransactionDTO) { + Element transaction = new Element("transaction"); + transactions.addContent(transaction); + // Identification de la transaction + Attribute idTransaction = new Attribute("id", transactionDTO + .getId()); + transaction.setAttribute(idTransaction); + // EntryDate + String dateTab[] = dateUtil + .arrayDate(transactionDTO.getEntryDate()); + Attribute entryDateYear = new Attribute("entryDateYear", dateTab[0]); + transaction.setAttribute(entryDateYear); + Attribute entryDateMonth = new Attribute("entryDateMonth", + dateTab[1]); + transaction.setAttribute(entryDateMonth); + Attribute entryDateDay = new Attribute("entryDateDay", dateTab[2]); + transaction.setAttribute(entryDateDay); + // VoucherRef + Attribute voucherRef = new Attribute("voucherRef", transactionDTO + .getVoucherRef()); + transaction.setAttribute(voucherRef); + // Description + Attribute description = new Attribute("description", transactionDTO + .getDescription()); + transaction.setAttribute(description); + // Id journal + Attribute IdJournal = new Attribute("idJournal", transactionDTO + .getJournalDTO().getId()); + transaction.setAttribute(IdJournal); + // Id timeSpan + Attribute IdTimeSpan = new Attribute("idTimeSpan", transactionDTO + .getTimeSpanDTO().getId()); + transaction.setAttribute(IdTimeSpan); + + // Entry + List<EntryDTO> listEntryDTO = entryServiceImpl + .searchEntryDTOWithTransaction(transactionDTO); + for (EntryDTO entryDTO : listEntryDTO) { + Element entry = new Element("entry"); + entries.addContent(entry); + // Identification du entry + Attribute idEntry = new Attribute("id", entryDTO.getId()); + entry.setAttribute(idEntry); + // Description + Attribute descriptionEntry = new Attribute("description", + entryDTO.getDescription()); + entry.setAttribute(descriptionEntry); + // Amount + Attribute amount = new Attribute("amount", entryDTO.getAmount()); + entry.setAttribute(amount); + // Lettering + Attribute lettering = new Attribute("lettering", entryDTO + .getLettering()); + entry.setAttribute(lettering); + // Detail + Attribute detail = new Attribute("detail", entryDTO.getDetail()); + entry.setAttribute(detail); + // Debit / crédit + if (entryDTO.isDebit()) { + Attribute debit = new Attribute("debit", "true"); + entry.setAttribute(debit); + } else { + Attribute debit = new Attribute("debit", "false"); + entry.setAttribute(debit); + } + // Transaction + Attribute idrefTransaction = new Attribute("idTransaction", + transactionDTO.getId()); + entry.setAttribute(idrefTransaction); + // Account + Attribute idAccount = new Attribute("idAccount", entryDTO + .getAccountDTO().getId()); + entry.setAttribute(idAccount); + } + } + //affiche(); + enregistre(nameFile); + return ServiceHelper.RESPOND_SUCCESS;*/ + } + + /** + * Converti la liste des comptes pour être ajouté au document xml. + * @param listAccountDTO + * @param accounts + */ + protected void accountXML(List<AccountDTO> listAccountDTO, Element accounts) { + /*for (AccountDTO accountDTO : listAccountDTO) { + Element account = new Element("account"); + accounts.addContent(account); + // Identification du account + Attribute idAccount = new Attribute("id", accountDTO.getId()); + account.setAttribute(idAccount); + // Label + Attribute label = new Attribute("label", accountDTO.getLabel()); + account.setAttribute(label); + // Type + Attribute type = new Attribute("type", accountDTO.getType()); + account.setAttribute(type); + // AccountNumber + Attribute accountNumber = new Attribute("accountNumber", accountDTO + .getAccountNumber()); + account.setAttribute(accountNumber); + // MasterAccountNumber + Attribute masterAccountNumber = new Attribute("masterAccount", + accountDTO.getMasterAccount()); + account.setAttribute(masterAccountNumber); + // Ajoute les comptes enfants à la liste + accountXML(accountDTO.getAccountChildDTO(), accounts); + }*/ + } + + // Affiche le fichier xml + /*static void affiche() { + try { + XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); + sortie.output(document, System.out); + } catch (java.io.IOException e) { + } + }*/ + + /** + * Permet d'enregistrer le fichier xml. + * @param fichier + */ + /*static void enregistre(String fichier) { + try { + XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); + sortie.output(document, new FileOutputStream(fichier)); + } catch (java.io.IOException e) { + } + }*/ + + /** + * Permet d'importer un fichier de données au format xml dans Callao. Si le + * fichier n'est pas disponible, il est alors renvoyé un message d'erreur. + * @param file + * @return + */ + public void importDatas(String file) { + /*if (log.isDebugEnabled()) { + log.debug("Load file XML : "); + } + String result = ServiceHelper.RESPOND_ERROR; + boolean existError = false; + + + // Chargement du fichier et construction du Dom + try { + // On crée une instance de SAXBuilder + SAXBuilder sxb = new SAXBuilder(); + document = sxb.build(file); + } catch (IOException e) { + log.error("Erreur lors de la lecture du fichier " + e.getMessage()); + e.printStackTrace(); + } catch (JDOMException e) { + log.error("Erreur lors de la construction du fichier JDOM " + + e.getMessage()); + e.printStackTrace(); + } + + + // Ecriture dans la base de données + try { + // Recherche de la racine + Element racine = document.getRootElement(); + + // Journal + XPath requeteXpath = XPath.newInstance("//journal"); + List results = requeteXpath.selectNodes(racine); + + Iterator iter = results.iterator(); + // Pour tous les journaux + while (iter.hasNext()) { + Element noeudCourant = (Element) iter.next(); + // Recherche attributs + String label = noeudCourant.getAttribute("label").getValue(); + String prefix = noeudCourant.getAttribute("prefix").getValue(); + String description = noeudCourant.getAttribute("description") + .getValue(); + // Création bdd + result = journalServiceImpl.createJournal(label, prefix, + description); + // Control erreur + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + existError = true; + } + } + + // Account + requeteXpath = XPath.newInstance("//account"); + results = requeteXpath.selectNodes(racine); + + iter = results.iterator(); + // Pour tous les accounts + while (iter.hasNext()) { + Element noeudCourant = (Element) iter.next(); + // Recherche attributs + String label = noeudCourant.getAttribute("label").getValue(); + String accountNumber = noeudCourant.getAttribute( + "accountNumber").getValue(); + String masterAccount = noeudCourant.getAttribute( + "masterAccount").getValue(); + String typeAccount = noeudCourant.getAttribute("type") + .getValue(); + // Création bdd + result = accountServiceImpl.createAccount(accountNumber, label, + masterAccount, typeAccount); + // Control erreur + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + existError = true; + } + } + + // Period + requeteXpath = XPath.newInstance("//period"); + results = requeteXpath.selectNodes(racine); + + iter = results.iterator(); + // Pour tous les periods + while (iter.hasNext()) { + Element noeudCourant = (Element) iter.next(); + // Recherche attributs + String idPeriod = noeudCourant.getAttribute("id").getValue(); + int year = Integer.parseInt(noeudCourant.getAttribute( + "beginYear").getValue()); + int month = Integer.parseInt(noeudCourant.getAttribute( + "beginMonth").getValue()); + int day = Integer.parseInt(noeudCourant + .getAttribute("beginDay").getValue()); + Date beginPeriod = new Date(year - 1900, month, day); + year = Integer.parseInt(noeudCourant.getAttribute("endYear") + .getValue()); + month = Integer.parseInt(noeudCourant.getAttribute("endMonth") + .getValue()); + day = Integer.parseInt(noeudCourant.getAttribute("endDay") + .getValue()); + Date endPeriod = new Date(year - 1900, month, day); + // Création bdd + result = periodServiceImpl.createPeriod(beginPeriod, endPeriod, + false); + // Control erreur + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + existError = true; + } + + // Transaction + requeteXpath = XPath + .newInstance("//transaction[@idTimeSpan=//timespan[@idPeriod='" + + idPeriod + "']/@id]"); + List resultsTransaction = requeteXpath.selectNodes(racine); + Iterator iterTrans = resultsTransaction.iterator(); + // Pour tous les transactions + while (iterTrans.hasNext()) { + Element noeudCourantTrans = (Element) iterTrans.next(); + + // Recherche attributs + + // Id transaction XMl + String idTransactionXML = noeudCourantTrans.getAttribute( + "id").getValue(); + // Recherche du journal en DTO + String idJournal = noeudCourantTrans.getAttribute( + "idJournal").getValue(); + requeteXpath = XPath.newInstance("//journal[@id='" + + idJournal + "']/@label"); + String label = requeteXpath.valueOf(racine); + JournalDTO journalDTO = journalServiceImpl + .searchJournalDTOWithLabel(label); + // Recherche du timeSpan en DTO + String idtimeSpan = noeudCourantTrans.getAttribute( + "idTimeSpan").getValue(); + requeteXpath = XPath.newInstance("//timespan[@id='" + + idtimeSpan + "']/@beginYear"); + year = Integer.parseInt(requeteXpath.valueOf(racine)); + requeteXpath = XPath.newInstance("//timespan[@id='" + + idtimeSpan + "']/@beginMonth"); + month = Integer.parseInt(requeteXpath.valueOf(racine)); + requeteXpath = XPath.newInstance("//timespan[@id='" + + idtimeSpan + "']/@beginDay"); + day = Integer.parseInt(requeteXpath.valueOf(racine)); + Date beginTimeSpan = new Date(year - 1900, month, day); + TimeSpanDTO timeSpanDTO = timeSpanServiceImpl + .searchTimeSpanDTOByDate(beginTimeSpan); + + // Création de transaction DTO + TransactionDTO transactionDTO = new TransactionDTO(); + transactionDTO.setJournalDTO(journalDTO); + transactionDTO.setTimeSpanDTO(timeSpanDTO); + // entryDate + year = Integer.parseInt(noeudCourantTrans.getAttribute( + "entryDateYear").getValue()); + month = Integer.parseInt(noeudCourantTrans.getAttribute( + "entryDateMonth").getValue()); + day = Integer.parseInt(noeudCourantTrans.getAttribute( + "entryDateDay").getValue()); + Date entryDate = new Date(year - 1900, month, day); + transactionDTO.setEntryDate(entryDate); + // voucherRef + String voucherRef = noeudCourantTrans.getAttribute( + "voucherRef").getValue(); + transactionDTO.setVoucherRef(voucherRef); + // description + String description = noeudCourantTrans.getAttribute( + "description").getValue(); + transactionDTO.setDescription(description); + + // Création bdd + String idTransactionCallao = transactionServiceImpl + .createTransaction(transactionDTO); + + // Entry + requeteXpath = XPath.newInstance("//entry[@idTransaction='" + + idTransactionXML + "']"); + List resultsEntry = requeteXpath.selectNodes(racine); + + Iterator iterEntry = resultsEntry.iterator(); + // Pour tous les entries + while (iterEntry.hasNext()) { + Element noeudEntry = (Element) iterEntry.next(); + + // Recherche attributs + + // Transaction DTO + transactionDTO = transactionServiceImpl + .searchTransactionDTO(idTransactionCallao); + // Account DTO + String idAccount = noeudEntry.getAttribute("idAccount") + .getValue(); + requeteXpath = XPath.newInstance("//account[@id='" + + idAccount + "']/@accountNumber"); + String accountNumber = requeteXpath.valueOf(racine); + AccountDTO accountDTO = accountServiceImpl + .searchAccountDTO(accountNumber); + // Entry DTO + EntryDTO entryDTO = new EntryDTO(); + entryDTO.setAccountDTO(accountDTO); + entryDTO.setTransactionDTO(transactionDTO); + // Description + description = noeudEntry.getAttribute("description") + .getValue(); + entryDTO.setDescription(description); + // Amount + String amount = noeudEntry.getAttribute("amount") + .getValue(); + entryDTO.setAmount(amount); + // Debit + boolean debit = noeudEntry.getAttribute("debit") + .getValue().equals("true"); + entryDTO.setDebit(debit); + // Lettering + String lettering = noeudEntry.getAttribute("lettering") + .getValue(); + entryDTO.setLettering(lettering); + // Detail + String detail = noeudEntry.getAttribute("detail") + .getValue(); + entryDTO.setDetail(detail); + // Création bdd + result = transactionServiceImpl.addEntry(entryDTO); + // Control erreur + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + existError = true; + } + } + } + + + // Bloquer Period + boolean lock = noeudCourant.getAttribute("locked").getValue() + .equals("true"); + // Si la période est bloquée + if (lock) { + // Bloque tous ses timeSpans + result = periodServiceImpl + .blockAllTimeSpanOfPeriod(periodServiceImpl + .searchPeriodWithDate(beginPeriod)); + // Control erreur + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + existError = true; + } + // bloque la période + result = periodServiceImpl.blockPeriod(periodServiceImpl + .searchPeriodWithDate(beginPeriod)); + + } else { + // On regarde si il y a besoin de bloquer les timeSpans + requeteXpath = XPath.newInstance("//timespan[@idPeriod = '" + + idPeriod + "']"); + List resultsTimeSpan = requeteXpath.selectNodes(racine); + Iterator iterTimeSpan = resultsTimeSpan.iterator(); + // Pour tous les timeSpans + while (iterTimeSpan.hasNext()) { + Element noeudCourantTimeSpan = (Element) iterTimeSpan + .next(); + // Recherche attributs + year = Integer.parseInt(noeudCourantTimeSpan + .getAttribute("beginYear").getValue()); + month = Integer.parseInt(noeudCourantTimeSpan + .getAttribute("beginMonth").getValue()); + day = Integer.parseInt(noeudCourantTimeSpan + .getAttribute("beginDay").getValue()); + Date beginTimeSpan = new Date(year - 1900, month, day); + lock = noeudCourantTimeSpan.getAttribute("locked") + .getValue().equals("true"); + // Bloque le timeSpan + if (lock) { + timeSpanServiceImpl + .blockTimeSpan(timeSpanServiceImpl + .searchTimeSpanByDate(beginTimeSpan)); + } + // Control erreur + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + existError = true; + } + } + } + + } + + } catch (JDOMException e) { + log.error("Erreur JDOM " + e.getMessage()); + e.printStackTrace(); + } + + // Détection des erreurs + if (!existError) { + result = ServiceHelper.RESPOND_SUCCESS; + } + return result;*/ + } + +} Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/JournalServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/JournalServiceImpl.java) =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/JournalServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/JournalServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,473 @@ +/* + * *##% Callao JournalServiceImpl + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +import static org.nuiton.i18n.I18n._; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaBusinessException; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.entity.Journal; +import org.chorem.lima.entity.JournalDAO; +import org.chorem.lima.entity.LimaCallaoDAOHelper; +import org.chorem.lima.entity.Transaction; +import org.chorem.lima.entity.TransactionDAO; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaNotFoundException; + +/** + * Implémente la fonction multi-journal. Il est possible de créer ici le + * journal des ventes, le journal des achats, etc. + * + * @author Rémi Chapelet + */ +public class JournalServiceImpl { + + private static final Log log = LogFactory.getLog(JournalServiceImpl.class); + + private TopiaContext rootContext; + + //private ConvertJournal convertJournal = new ConvertJournal(); + + public JournalServiceImpl() { + LimaConfig config = LimaConfig.getInstance(); + try { + rootContext = TopiaContextFactory.getContext(config.getOptions()); + } catch (TopiaNotFoundException ex) { + if (log.isErrorEnabled()) { + log.error("Can't init topia context", ex); + } + } + } + + /** + * Création d'un journal. Il peut être unique sur son label (au choix). + * + * @param journal journal + * @throws LimaException + */ + public void createJournal(Journal journal) throws LimaException { + /*String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + JournalDAO journalDAO = LimaCallaoDAOHelper + .getJournalDAO(topiaContext); + + // Si on souhaite avoir un journal unique avec son label + + Journal journal = searchJournalWithLabel(label); + // Si un journal existe déjà avec ce label + if (journal != null) { + if (log.isWarnEnabled()) { + log.warn("Un journal avec le label " + label + + " existe déjà !"); + } + result = ServiceHelper.JOURNAL_DOUBLE; + } else { + // Creation du journal + Journal newJournal = journalDAO.create(); + newJournal.setLabel(label); + newJournal.setPrefix(prefix); + newJournal.setDescription(description); + // Création BDD + topiaContext.commitTransaction(); + result = ServiceHelper.RESPOND_SUCCESS; + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result;*/ + + TopiaContext transaction = null; + try { + // basic check done, make check in database + // TODO move it into JTA + transaction = rootContext.beginTransaction(); + + // test si un journal de ce nom existe deja + JournalDAO journalDAO = LimaCallaoDAOHelper.getJournalDAO(transaction); + Journal existingJournal = journalDAO.findByLabel(journal.getLabel()); + if (existingJournal != null) { + throw new LimaBusinessException(_("An journal already exists with this label : %s", journal.getLabel())); + } + + // creation du journal + journalDAO.create(journal); + + // commit + transaction.commitTransaction(); + } + catch (TopiaException ex) { + if (transaction != null) { + try { + transaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't create journal", ex); + } + finally { + if (transaction != null) { + try { + transaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't create journal", ex); + } + } + } + } + + /* + * Création d'un journal à partir de son DTO. + * @param journalDTO Journal au format DTO. + * @return + * + public String createJournal(JournalDTO journalDTO) { + String result; + result = createJournal(journalDTO.getLabel(), journalDTO.getPrefix(), + journalDTO.getDescription()); + return result; + }*/ + + public List<Journal> getAllJournal() throws LimaException { + /*List<JournalDTO> listJournalDTO = new ArrayList<JournalDTO>(); + + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + JournalDAO journalDAO = LimaCallaoDAOHelper + .getJournalDAO(topiaContext); + // Creation du journal + List<Journal> listJournal = journalDAO.findAll(); + // Pour chaque journal, on le transforme en DTO + for (Journal journal : listJournal) { + // Converti en DTO + JournalDTO journalDTO = convertJournal + .journalEntityToDto(journal); + // Ajoute à la liste + listJournalDTO.add(journalDTO); + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return listJournalDTO;*/ + + List<Journal> journalsList = new ArrayList<Journal>(); + TopiaContext transaction = null; + try { + // basic check done, make check in database + // TODO move it into JTA + transaction = rootContext.beginTransaction(); + + // test si un journal de ce nom existe deja + JournalDAO journalDAO = LimaCallaoDAOHelper.getJournalDAO(transaction); + List<Journal> journals = journalDAO.findAll(); + journalsList.addAll(journals); + + // commit + transaction.commitTransaction(); + } + catch (TopiaException ex) { + if (transaction != null) { + try { + transaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't create journal", ex); + } + finally { + if (transaction != null) { + try { + transaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't create journal", ex); + } + } + } + + return journalsList; + } + + /* + * Permet de rechercher un journal existant à partir de son label. + * ATTENTION : il est possible que plusieurs journaux existent avec ce + * même label. La méthode renvoie le premier trouvé. + * @param prefix préfixe du journal recherché + * @return + * + public Journal searchJournalWithLabel(String label) { + Journal journalResult = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + JournalDAO journalDAO = LimaCallaoDAOHelper + .getJournalDAO(topiaContext); + // Creation du journal + journalResult = journalDAO.findByLabel(label); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return journalResult; + }*/ + + /* + * Permet de rechercher un journal existant à partir du label. + * Le journal recherché est converti automatiquement en format DTO. + * @param prefix préfixe du journal recherché + * @return + * + public JournalDTO searchJournalDTOWithLabel(String label) { + Journal journal = searchJournalWithLabel(label); + JournalDTO journalDTO = convertJournal.journalEntityToDto(journal); + return journalDTO; + }*/ + + /* + * Permet de rechercher un journal unique identifé par son topiaId. + * @param topiaId identifiant du journal recherché + * @return + * + public Journal searchJournalWithTopiaId(String topiaId) { + Journal journalResult = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + JournalDAO journalDAO = LimaCallaoDAOHelper + .getJournalDAO(topiaContext); + // Creation du journal + journalResult = journalDAO.findByTopiaId(topiaId); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return journalResult; + }*/ + + /* + * Permet de rechercher un journal existant à partir du topiaId. + * Le journal recherché est converti automatiquement en format DTO. + * @param prefix préfixe du journal recherché + * @return + * + public JournalDTO searchJournalDTOWithTopiaId(String topiaId) { + Journal journal = searchJournalWithTopiaId(topiaId); + JournalDTO journalDTO = convertJournal.journalEntityToDto(journal); + return journalDTO; + }*/ + + /* + * Permet de modifier un journal. + * @param label + * @param prefix + * @return + * + public String modifyJournal(String topiaId, String label, String prefix, + String description) { + String result = ServiceHelper.RESPOND_ERROR; + Journal journalModify = searchJournalWithTopiaId(topiaId); + // Si le journal n'existe pas + if (journalModify == null) { + if (log.isWarnEnabled()) { + log.warn("Le journal " + label + " n'existe pas !"); + } + result = ServiceHelper.JOURNAL_NOT_EXIST; + } else // Sinon on modifie le journal + { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + JournalDAO journalDAO = LimaCallaoDAOHelper + .getJournalDAO(topiaContext); + // Modifie le journal + journalModify.setPrefix(prefix); + journalModify.setDescription(description); + journalDAO.update(journalModify); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + result = ServiceHelper.RESPOND_SUCCESS; + } catch (TopiaException e) { + log.error(e); + } + } + return result; + }*/ + + /** + * Permet d'effacer un journal dans la base de données. + * + * ATTENTION : si un journal est associé avec des transactions, il est alors + * impossible de supprimer celui-ci. + * + * @param prefix préfixe du journal à supprimer + * @return + * @throws LimaException + */ + public void removeJournal(Journal journal) throws LimaException { + /*String result = ServiceHelper.RESPOND_ERROR; + Journal journalDelete = searchJournalWithTopiaId(topiaId); + // Si le journal n'existe pas + if (journalDelete == null) { + if (log.isWarnEnabled()) { + log.warn("Le journal " + topiaId + " n'existe pas !"); + } + result = ServiceHelper.JOURNAL_NOT_EXIST; + } else // Sinon on efface le journal + { + + // Vérifie si une transaction n'appartient pas à ce journal. + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche au moins une transaction avec ce journal. + Transaction transaction = transactionDAO + .findByJournal(journalDelete); + // Il existe au moins une transaction + if (transaction != null) { + if (log.isWarnEnabled()) { + log.warn("Le journal " + topiaId + + " possède des transactions comptables !"); + } + result = ServiceHelper.JOURNAL_WITH_TRANSACTIONS; + } else { + + // Efface le journal + // Chargement du DAO + JournalDAO journalDAO = LimaCallaoDAOHelper + .getJournalDAO(topiaContext); + // Supprime le journal + journalDAO.delete(journalDelete); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + result = ServiceHelper.RESPOND_SUCCESS; + } + } catch (TopiaException e) { + log.error(e); + } + } + return result;*/ + + TopiaContext topiaTransaction = null; + try { + // basic check done, make check in database + // TODO move it into JTA + topiaTransaction = rootContext.beginTransaction(); + + // Vérifie si une transaction n'appartient pas à ce journal. + TransactionDAO transactionDAO = LimaCallaoDAOHelper.getTransactionDAO(topiaTransaction); + Transaction transaction = transactionDAO.findByJournal(journal); + if (transaction != null) { + throw new LimaBusinessException("Can't delete journal with transactions"); + } + + // test si un journal de ce nom existe deja + JournalDAO journalDAO = LimaCallaoDAOHelper.getJournalDAO(topiaTransaction); + journalDAO.delete(journal); + + // commit + topiaTransaction.commitTransaction(); + } + catch (TopiaException ex) { + if (topiaTransaction != null) { + try { + topiaTransaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't create journal", ex); + } + finally { + if (topiaTransaction != null) { + try { + topiaTransaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't create journal", ex); + } + } + } + } + + /* + * Permet d'effacer un journal dans la base de données. + * ATTENTION : si un journal est associé avec des transactions, il est alors + * impossible de supprimer celui-ci. + * @param journalDTO journal au format DTO à supprimer + * @return + * + public String removeJournal(JournalDTO journalDTO) { + String result = removeJournal(journalDTO.getId()); + return result; + }*/ + +} Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/LogServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/LogServiceImpl.java) =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/LogServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/LogServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,366 @@ +/* + * *##% Callao LogServiceImpl + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.LimaException; +import org.chorem.lima.entity.EntryLog; +import org.chorem.lima.entity.EntryLogDAO; +import org.chorem.lima.entity.LimaCallaoDAOHelper; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaNotFoundException; + +/** + * Permet d'ajouter des logs au systeme. + * + * ATTENTION on ne peut supprimer un log. + * + * @author Rémi Chapelet + */ +public class LogServiceImpl { //implements LogService { + + /** log */ + private static final org.apache.commons.logging.Log log = LogFactory + .getLog(LogServiceImpl.class); + + private TopiaContext rootContext; + + + public LogServiceImpl() { + LimaConfig config = LimaConfig.getInstance(); + try { + rootContext = TopiaContextFactory.getContext(config.getOptions()); + } catch (TopiaNotFoundException ex) { + if (log.isErrorEnabled()) { + log.error("Can't init topia context", ex); + } + } + } + + /** + * Création d'un log dans le systeme. + * + * @param entryLog date de creation du log + * @throws LimaException + */ + public void addLog(EntryLog entryLog) throws LimaException { + /*String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryLogDAO logDAO = LimaCallaoDAOHelper.getEntryLogDAO(topiaContext); + // Creation du log + EntryLog newlog = logDAO.create(); + newlog.setLogDate(logDate); + newlog.setTransDate(transDate); + newlog.setVoucherRef(voucherRef); + newlog.setType(type); + newlog.setTransDesc(transDesc); + newlog.setEntryDesc(entryDesc); + newlog.setAmount(amount); + newlog.setDebit(debit); + newlog.setLettering(lettering); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + // Affichage pour les logs + String topiaId = newlog.getTopiaId(); + if (log.isInfoEnabled()) { + log.info("Log created: "+ topiaId); + } + result = ServiceHelper.RESPOND_SUCCESS; + }catch (TopiaException e) { + log.error(e); + } + return result;*/ + + TopiaContext transaction = null; + try { + // basic check done, make check in database + // TODO move it into JTA + transaction = rootContext.beginTransaction(); + + // creation + EntryLogDAO entryLogDAO = LimaCallaoDAOHelper + .getEntryLogDAO(transaction); + entryLogDAO.create(entryLog); + + // commit + transaction.commitTransaction(); + } catch (TopiaException ex) { + if (transaction != null) { + try { + transaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't create entry log", ex); + } finally { + if (transaction != null) { + try { + transaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't create entry log", ex); + } + } + } + } + + /* + * Création d'un log à partir d'un log DTO. + * @param logDTO log en format DTO qu'on souhaite créer + * @return + * + public String addLog (LogDTO logDTO) { + String result = ServiceHelper.RESPOND_ERROR; + // Vérifie si logDTO existe + if (logDTO != null) + { + result = addLog(logDTO.getLogDate(),logDTO.getTransDate(),logDTO.getType(), + logDTO.getVoucherRef(),logDTO.getTransDesc(),logDTO.getEntryDesc(), + logDTO.getAmount(),logDTO.isDebit(),logDTO.getLettering()); + } + return result; + }*/ + + /** + * Recherche tous les logs dans la base de donnees. + * + * @return la liste des logs + * @throws LimaException + */ + public List<EntryLog> listeAllLog() throws LimaException { + /*List<EntryLog> listelog = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryLogDAO logDAO = LimaCallaoDAOHelper + .getEntryLogDAO(topiaContext); + // recherche des log + listelog = logDAO.findAll(); + // Fermeture BDD + topiaContext.closeContext(); + if (log.isInfoEnabled()) { + log.info("Search all logs"); + } + } catch (TopiaException e) { + log.error(e); + } + return listelog;*/ + + List<EntryLog> entryLogsList = new ArrayList<EntryLog>(); + TopiaContext transaction = null; + try { + // basic check done, make check in database + // TODO move it into JTA + transaction = rootContext.beginTransaction(); + + // creation + EntryLogDAO entryLogDAO = LimaCallaoDAOHelper + .getEntryLogDAO(transaction); + List<EntryLog> entryLogs = entryLogDAO.findAll(); + entryLogsList.addAll(entryLogs); + + // commit + transaction.commitTransaction(); + } catch (TopiaException ex) { + if (transaction != null) { + try { + transaction.rollbackTransaction(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + } + } + if (log.isErrorEnabled()) { + log.error("Error during create account", ex); + } + throw new LimaException("Can't create entry log", ex); + } finally { + if (transaction != null) { + try { + transaction.closeContext(); + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Error during rollback context", ex); + } + throw new LimaException("Can't create entry log", ex); + } + } + } + + return entryLogsList; + } + + /* + * Permet de renvoyer tous les logs au format DTO. + * @return + * + public List<LogDTO> listeAllLogDTO() { + List<LogDTO> listLogDTO = new ArrayList<LogDTO>(); + // On recherche tous les logs. + List<EntryLog> listLog = listeAllLog(); + // Pour chaque log, on le converti en logDTO et on l'ajoute à la nouvelle liste de DTO + for (EntryLog log : listLog) { + // conerti de l'entity en DTO + LogDTO logDTO = convertLog.logEntityToDto(log); + // Ajoute à la liste des logs DTO + listLogDTO.add(logDTO); + } + return listLogDTO; + }*/ + + /* + * Renvoie une liste de tous les logs suivant la date de creation + * @param datecreate date de creation des logs recherchés + * @return une liste des logs trouves + * + public List<EntryLog> searchLogWithDateCreate(Date dateCreate) { + List<EntryLog> listelog = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryLogDAO logDAO = LimaCallaoDAOHelper + .getEntryLogDAO(topiaContext); + // recherche des log + listelog = logDAO.findAllByLogDate(dateCreate); + // Fermeture BDD + topiaContext.closeContext(); + if (log.isInfoEnabled()) { + log.info("Log(s) find : " + listelog.size() + "log(s)"); + } + } catch (TopiaException e) { + log.error(e); + } + return listelog; + }*/ + + /* + * Permet de rechercher tous les logs suivant la date de création, c'est à + * dire de l'opération effectuée sur une entry à un jour précis, et qui a + * déclenchée automatiquement une création de log. + * La méthode renvoie sous forme de liste, en convertissant les objets + * entitys en DTO. + * @param dateCreate date de création des logs recherchés + * @return + * + public List<LogDTO> searchLogDTOWithDateCreate(Date dateCreate) { + List<LogDTO> listLogDTO = new ArrayList<LogDTO>(); + // On recherche tous les logs suivant la date de création. + List<EntryLog> listLog = searchLogWithDateCreate(dateCreate); + // Pour chaque log, on le converti en logDTO et on l'ajoute à la nouvelle liste de DTO + for (EntryLog log : listLog) { + // conerti de l'entity en DTO + LogDTO logDTO = convertLog.logEntityToDto(log); + // Ajoute à la liste des logs DTO + listLogDTO.add(logDTO); + } + return listLogDTO; + }*/ + + /* + * Recherche un log avec son identifiant topiaId. + * @param topiaId identifiant d'un log + * @return + * + public EntryLog searchLogWithTopiaId(String topiaId) { + EntryLog logSearch = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryLogDAO logDAO = LimaCallaoDAOHelper + .getEntryLogDAO(topiaContext); + // Creation du journal + logSearch = logDAO.findByTopiaId(topiaId); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return logSearch; + }*/ + + /* + * Efface un log : uniquement utilisé pour supprimer les logs dans les tests + * unitaires. + * @param topiaId identifiant du log à supprimer + * @return + * + public String removeLog(String topiaId) { + String result = ServiceHelper.RESPOND_ERROR; + EntryLog logDelete = searchLogWithTopiaId(topiaId); + // Si le log n'existe pas + if (logDelete == null) { + if (log.isWarnEnabled()) { + log.warn("Le log " + topiaId + " n'existe pas !"); + } + } else // Sinon on efface le log + { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryLogDAO logDAO = LimaCallaoDAOHelper + .getEntryLogDAO(topiaContext); + // Supprime le log + logDAO.delete(logDelete); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + result = ServiceHelper.RESPOND_SUCCESS; + } catch (TopiaException e) { + log.error(e); + } + } + return result; + }*/ + + /* + * Permet de supprimer un log à partir de son DTO. + * @param logDTO log à supprimer + * @return + * + public String removeLog(LogDTO logDTO) { + String result = removeLog(logDTO.getId()); + return result; + }*/ +} Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/PeriodServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/PeriodServiceImpl.java) =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/PeriodServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/PeriodServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,505 @@ +/* + * *##% Callao PeriodServiceImpl + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.entity.Period; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaNotFoundException; + +/** + * Gestion des périodes. + * Chaque période doit posséder 12 timespans mensuels. + * Une période ne peut être supprimée et débloquée. + * + * @author Rémi Chapelet + */ +public class PeriodServiceImpl { //implements PeriodService { + + private static final Log log = LogFactory.getLog(PeriodServiceImpl.class); + + private TopiaContext rootContext; + + private TimeSpanServiceImpl timeSpanServiceImpl = new TimeSpanServiceImpl(); + + public PeriodServiceImpl() { + LimaConfig config = LimaConfig.getInstance(); + try { + rootContext = TopiaContextFactory.getContext(config.getOptions()); + } catch (TopiaNotFoundException ex) { + if (log.isErrorEnabled()) { + log.error("Can't init topia context", ex); + } + } + } + + /** + * Permet de créer une période principale. Elle a une durée de un an, + * composées de 12 périodes mensuelles. Elle correspond à l'exercice + * comptable. Pour créer une nouvelle période, la précédente doit être + * obligatoirement clôturée. + * @param beginTimeSpan date début de période + * @param endTimeSpan date fin de période + * @param lock Vrai si la période est bloquée + * @return + */ + public void createPeriod(Period period /*Date beginTimeSpan, Date endTimeSpan, boolean lock*/) { + /*// Par défaut lock est à false + lock = false; + String result = ServiceHelper.RESPOND_ERROR; + + try { + boolean correctPeriod = false; + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + PeriodDAO periodDAO = LimaCallaoDAOHelper + .getPeriodDAO(topiaContext); + // Creation de la periodDate + PeriodDates newPeriod = new PeriodDates(beginTimeSpan, endTimeSpan); + + // Creation de la période + Period period = periodDAO.create(); + period.setBeginPeriod(newPeriod.getFromDate()); + period.setEndPeriod(newPeriod.getThruDate()); + period.setLocked(lock); + // Vérification si la période est correcte + correctPeriod = isCorrectPeriod(period); + if (correctPeriod) { + // Si elle est correcte : Création BDD + topiaContext.commitTransaction(); + if (log.isInfoEnabled()) { + log.info("Ajout exercice du " + beginTimeSpan.toString() + + " au " + endTimeSpan.toString()); + } + + //Ajout des timeSpans mensuels + //Par défaut, il prend seulement la date beginTimeSpan, et calcule + //la date de fin, c'est pourquoi il est laissé deux fois "beginTimeSpan" + TimeSpanServiceImpl timeSpanImpl = new TimeSpanServiceImpl(); + boolean stop = false; // En cas d'erreur lors de la création d'un timeSpan. + + List<Date> monthList = newPeriod.getMonths(); + + int max = monthList.size(); + log.debug("la periode fait:" + max); + for (int i = 0; i < max; i++) { + // Création timeSpan + result = timeSpanImpl.createTimeSpan(monthList.get(i), + monthList.get(i), period, false); + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + stop = true; + if (log.isErrorEnabled()) { + log.error("Erreur lors de la création des " + max + + " timeSpans"); + } + result = ServiceHelper.PERIOD_CREATE_TIMESPANS; + } + // Supprimer la periode si stop = true + } + if (stop == false) { + result = ServiceHelper.RESPOND_SUCCESS; + } + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result; */ + } + + /* + * Permet de créer une période à partir d'une période DTO. + * @param periodDTO période à créer au format DTO. + * @return + * + public String createPeriod(PeriodDTO periodDTO) { + String result = createPeriod(periodDTO.getBeginPeriod(), periodDTO + .getEndPeriod(), false); + // Tous les timeSpans sont automatiquement créés avec la méthode createPeriod + return result; + }*/ + + /* + * Permet de vérifier si la période est correcte (aucun chevauchement avec + * les autres périodes, période(s) précédente(s) bloquée(s), formée de 1 à 24 + * mois). + * @param period période à tester si elle est correcte + * @return + * + private boolean isCorrectPeriod(Period period) { + // Calcul du nombre de mois pour que la période soit valide (12 mois) + int number_months = dateUtil.numberOfMonths(period.getBeginPeriod(), + period.getEndPeriod()); + boolean result = true; + + if (number_months == 0 && number_months >= 24) // Periode de 1mois a 24 mois + { + if (log.isErrorEnabled()) { + log.error("Période du " + + period.getBeginPeriod() + + " au " + + period.getEndPeriod() + + " : L'exercice doit faire au minimum 1 mois et au maximum 24 mois"); + } + result = false; + } else { + // Période(s) précédente(s) bloquée(s). + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + PeriodDAO periodDAO = LimaCallaoDAOHelper + .getPeriodDAO(topiaContext); + // Recherche les périodes qui ne sont pas bloquées. + List<Period> listePeriod = periodDAO.findAllByLocked(false); + // Recherche la dernière période, les dates doivent se suivre + Date date_search = period.getBeginPeriod(); + Period previousPeriod = periodDAO.findByEndPeriod(dateUtil + .previousDay(date_search)); + // Nombre de périodes dans la base + int number_period = periodDAO.findAll().size(); + // Fermeture BDD + topiaContext.closeContext(); + // Si il y a au moins une période trouvée + if (!(listePeriod.isEmpty())) { + if (log.isErrorEnabled()) { + log.error("Il existe au moins une période précédente non bloquée !"); + } + result = false; + } + // Si la période précédente correspond au jour précédent + // et vérifie si ce n'est pas la première période + if (previousPeriod == null && number_period != 0) { + if (log.isErrorEnabled()) { + log.error("Votre période doit être collée " + + "aux autres périodes !" + + date_search.toString() + " PPP " + + dateUtil.previousDay(date_search).toString()); + } + result = false; + } + } catch (TopiaException e) { + log.error(e); + } + } + return result; + }*/ + + /* + * Cette méthode permet de bloquer une période. Elle doit vérifier que + * tous les timeSpans mensuels sont bloqués. + * @param + * @return + * + public String blockPeriod(Period period) { + String result = ServiceHelper.RESPOND_ERROR; + // La période ne doit pas être nulle + if (period != null) { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Recherche tous les timeSpans de la période non bloquées + List<TimeSpan> listeTimeSpan = timeSpanDAO + .findAllByPeriod(period); + boolean existTimeSpanNotBlock = false; + for (TimeSpan timeSpan : listeTimeSpan) { + // Si timeSpan non bloqué + if (!timeSpan.getLocked()) { + existTimeSpanNotBlock = true; + if (log.isErrorEnabled()) { + log.error("Le timeSpan du " + + timeSpan.getBeginTimeSpan().toString() + + " au " + + timeSpan.getEndTimeSpan().toString() + + " non bloqué !"); + } + result = ServiceHelper.PERIOD_TIMESPAN_NOT_BLOCK; + } + } + // Si il n'existe pas de timeSpan non bloqué + if (!(existTimeSpanNotBlock)) { + // Bloque la période + period.setLocked(true); + // Chargement du DAO + PeriodDAO periodDAO = LimaCallaoDAOHelper + .getPeriodDAO(topiaContext); + periodDAO.update(period); + // Création BDD + topiaContext.commitTransaction(); + result = ServiceHelper.RESPOND_SUCCESS; + if (log.isInfoEnabled()) { + log.info("Période " + + period.getBeginPeriod().toString() + " au " + + period.getEndPeriod().toString() + + " bloquée avec succès."); + } + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + } + return result; + }*/ + + /* + * Permet de bloquer une période. Avec la périodeDTO passée en paramètre, on + * effectue une recherche avec la date de début pour récupérer la période + * dans la base de données. Il est possible de l'identifier avec son topiaId, + * mais il y a plus de risque que cette mentien ne soit pas renseignée dans + * l'objet periodDTO. + * @param periodDTO + * @return + * + public String blockPeriod(PeriodDTO periodDTO) { + // Recherche de la période + Period period = searchPeriodWithDate(periodDTO.getBeginPeriod()); + String result = blockPeriod(period); + return result; + }*/ + + /* + * Permet de bloquer TOUS les timeSpans de la période + * @param period + * @return + * + public String blockAllTimeSpanOfPeriod(Period period) { + String result = ServiceHelper.RESPOND_ERROR; + if (period == null) { + if (log.isErrorEnabled()) { + log.error("La période ne peut bloquer ses périodes mensuelles, " + + "il faut une période en entrée."); + } + } else { + // On bloque chaque timeSpan + boolean ErrorBlockTimeSpan = false; + List<TimeSpanDTO> listTimeSpanDTO = timeSpanServiceImpl + .searchListTimeSpanDTO(period); + // tri la liste des timeSpans dans l'ordre croissant des dates + Collections.sort(listTimeSpanDTO); + for (TimeSpanDTO timeSpanDTO : listTimeSpanDTO) { + result = timeSpanServiceImpl.blockTimeSpan(timeSpanDTO); + if (result.equals(ServiceHelper.RESPOND_ERROR)) { + ErrorBlockTimeSpan = true; + } + } + // Si il n'y a pas eu d'erreurs pour bloquer les timespans + if (!ErrorBlockTimeSpan) { + result = ServiceHelper.RESPOND_SUCCESS; + } else { + if (log.isErrorEnabled()) { + log.error("Impossible de bloquer tous les timeSpans."); + } + result = ServiceHelper.PERIOD_ALL_TIMESPAN; + } + } + return result; + }*/ + + /* + * Cette méthode est semblable à searchPeriodWithDateFirst. Elle permet + * de rechercher une période sans forcément connaître la date de départ. On + * donne une date quelconque, et elle retourne la période correspondante. + * @param d + * @return + * + public Period searchPeriodWithDate(Date d) { + Period period = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + PeriodDAO periodDAO = LimaCallaoDAOHelper + .getPeriodDAO(topiaContext); + // Recherche de toutes les périodes + List<Period> listePeriod = periodDAO.findAll(); + // Fermeture BDD + topiaContext.closeContext(); + // Recherche de la période + for (Period periodSearch : listePeriod) { + // Recherche si la date d est entre la date de début et fin de la période + boolean periodBetweenDate = dateUtil.betweenDate(d, + periodSearch.getBeginPeriod(), periodSearch + .getEndPeriod()); + // Si la date est comprise dans les limites de la période + if (periodBetweenDate) { + period = periodSearch; + } + } + } catch (TopiaException e) { + log.error(e); + } + return period; + }*/ + + /* + * Permet de rechercher une période au format DTO avec une date. Cette date + * peut être quelconque (pas obligatoire d'être le premier jour de la période + * par exemple). + * @param d date comprise dans la période qu'on souhaite rechercher + * @return + * + public PeriodDTO searchPeriodDTOWithDate(Date d) { + Period period = searchPeriodWithDate(d); + // Converti la période en PeriodDTO + PeriodDTO periodDTO = convertPeriod.periodEntityToDto(period); + return periodDTO; + }*/ + + /* + * Permet de renvoyer tous les périodes en format DTO, avec tous les timeSpans + * en format DTO également. + * @return + * + public List<PeriodDTO> getAllPeriod() { + ArrayList<PeriodDTO> listAllPeriodDTO = new ArrayList<PeriodDTO>(); + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + PeriodDAO periodDAO = LimaCallaoDAOHelper + .getPeriodDAO(topiaContext); + // Recherche de toutes les périodes + List<Period> listePeriod = periodDAO.findAll(); + // Transforme les périodes en DTO + for (Period period : listePeriod) { + PeriodDTO periodDTO = convertPeriod.periodEntityToDto(period); + listAllPeriodDTO.add(periodDTO); + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return listAllPeriodDTO; + }*/ + + /* + * Recherche une période précise, avec son identifiant topiaId. + * @param topiaId identifiant de la période + * @return + * + public Period searchPeriodWithTopiaId(String topiaId) { + Period periodSearch = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + PeriodDAO periodDAO = LimaCallaoDAOHelper + .getPeriodDAO(topiaContext); + // Creation du journal + periodSearch = periodDAO.findByTopiaId(topiaId); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return periodSearch; + }*/ + + + /* + * Efface une période dans la base de données. Tous les timeSpans sont + * également effacés. Cette méthode est uniquement utilisée pour les tests + * unitaires. + * @param period + * @return + * + public String removePeriod(String topiaId) { + String result = ServiceHelper.RESPOND_ERROR; + Period periodDelete = searchPeriodWithTopiaId(topiaId); + // Si la période n'existe pas + if (periodDelete == null) { + if (log.isWarnEnabled()) { + log.warn("La période " + topiaId + " n'existe pas !"); + } + result = ServiceHelper.PERIOD_NOT_EXIST; + } else // Sinon on efface la période + { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + PeriodDAO periodDAO = LimaCallaoDAOHelper + .getPeriodDAO(topiaContext); + // Débloque la période + periodDelete.setLocked(false); + // Mise à jour dans la bdd + periodDAO.update(periodDelete); + // Création BDD + topiaContext.commitTransaction(); + + // Supprime les timeSpans de la période + List<TimeSpanDTO> listTimeSpanDTO = timeSpanServiceImpl + .searchListTimeSpanDTO(periodDelete); + // tri la liste des timeSpans dans l'ordre décroissant des dates + Collections.sort(listTimeSpanDTO, Collections.reverseOrder()); + // Débloque les timeSpans + for (TimeSpanDTO timeSpanDTO : listTimeSpanDTO) { + TimeSpan timeSpan = timeSpanServiceImpl + .searchTimeSpanByDate(timeSpanDTO); + // Si le timeSpan est bloqué + if (timeSpanDTO.isLocked()) { + // débloque le timeSpan + timeSpanServiceImpl.unblockTimeSpan(timeSpan); + } + } + // Efface les timeSpans + for (TimeSpanDTO timeSpanDTO : listTimeSpanDTO) { + TimeSpan timeSpan = timeSpanServiceImpl + .searchTimeSpanByDate(timeSpanDTO); + // efface le timeSpan + timeSpanServiceImpl.removeTimeSpan(timeSpan); + } + + + //Supprime la période + periodDAO.delete(periodDelete); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + result = ServiceHelper.RESPOND_SUCCESS; + } catch (TopiaException e) { + log.error(e); + } + } + return result; + }*/ + + /* + * Permet d'effacer une période au format DTO. + * @param periodDTO la période à supprimer + * @return + * + public String removePeriod(PeriodDTO periodDTO) { + String result = removePeriod(periodDTO.getId()); + return result; + }*/ +} Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/ReportServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/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 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,61 @@ +package org.chorem.lima.business.ejb; + +import org.nuiton.topia.TopiaContext; + +public class ReportServiceImpl { //implements ReportService { + + //@Override + public String generateAccount(String number, String amount, String label) { + // TODO Auto-generated method stub + return null; + } + + //@Override + public String generateBalanceSheet(String period) { + // TODO Auto-generated method stub + return null; + } + + //@Override + public String generateCashFlowStatement(String period) { + // TODO Auto-generated method stub + return null; + } + + //@Override + public String generateGeneralLedger(String period) { + // TODO Auto-generated method stub + return null; + } + + //@Override + public String generateIncomeStatement(String period) { + // TODO Auto-generated method stub + return null; + } + + //@Override + public String generateJournal(String type, String period) { + // TODO Auto-generated method stub + return null; + } + + //@Override + public String[] getMethods() { + // TODO Auto-generated method stub + return null; + } + + //@Override + public void destroy() { + // TODO Auto-generated method stub + + } + + //@Override + public void init(TopiaContext arg0) { + // TODO Auto-generated method stub + + } + +} Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/TimeSpanServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/TimeSpanServiceImpl.java) =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/TimeSpanServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/TimeSpanServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,534 @@ +/* + * *##% Callao TimeSpanServiceImpl + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.entity.TimeSpan; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaNotFoundException; + +/** + * Gestion des périodes intermédiaires durant l'exercice. + * Chaque timeSpan sera fixe, et devra correspondre à un mois complet. + * + * @author Rémi Chapelet + */ +public class TimeSpanServiceImpl { //implements TimeSpanService { + + /** log */ + private static final Log log = LogFactory.getLog(TimeSpanServiceImpl.class); + + private TopiaContext rootContext; + + private static TransactionServiceImpl transactionServiceImpl = new TransactionServiceImpl(); + + public TimeSpanServiceImpl() { + LimaConfig config = LimaConfig.getInstance(); + try { + rootContext = TopiaContextFactory.getContext(config.getOptions()); + } catch (TopiaNotFoundException ex) { + if (log.isErrorEnabled()) { + log.error("Can't init topia context", ex); + } + } + } + + /** + * 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. + * @param beginTimeSpan date de début de période + * @param endTimeSpan date de fin de période + * @param locked est à vrai si la période doit être bloquée. + * @return + */ + public void createTimeSpan(TimeSpan timeSpan /*Date beginTimeSpan, Date endTimeSpan, + Period period, boolean locked*/) { +/* + // timeSpan correspond à une période mensuelle. + // La fonction va donc prendre seulement pour date de référence la + // date beginTimeSpan. Elle calcule automatiquement la date de fin + // suivant le mois. + DateUtil dateutil = new DateUtil(); + // Initialise la date de début au premier du mois + beginTimeSpan = dateutil.InitDateFirstDayMonth(beginTimeSpan); + // Initialise la date de fin au dernier du mois + endTimeSpan = dateutil.InitDateEndDayMonth(beginTimeSpan); + if (log.isInfoEnabled()) { + log.info("Nouveau timeSpan du " + beginTimeSpan.toString() + " au " + + endTimeSpan.toString()); + } + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Creation du timespan + TimeSpan newtimeSpan = timeSpanDAO.create(); + newtimeSpan.setBeginTimeSpan(beginTimeSpan); + newtimeSpan.setEndTimeSpan(endTimeSpan); + newtimeSpan.setLocked(locked); + newtimeSpan.setPeriod(period); + // Création BDD + topiaContext.commitTransaction(); + // Fermeture BDD + topiaContext.closeContext(); + if (log.isInfoEnabled()) { + log.info("Ajout avec succes du timeSpan"); + } + return ServiceHelper.RESPOND_SUCCESS; + } catch (TopiaException e) { + log.error(e); + return ServiceHelper.RESPOND_ERROR; + }*/ + } + + /* + * Permet de trouver un timespan directement avec une date. La date peut + * être quelconque. Exemple : d = 17 sept 2000, renvoie la période du + * 1 sept au 30 sept 2000. + * @param d + * @return + * + public TimeSpan searchTimeSpanByDate(Date d) { + TimeSpan timeSpan = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Par précaution, on initialise la date au debut du mois + DateUtil dateutil = new DateUtil(); + // Recherche du timeSpan + Date searchDate = dateutil.InitDateFirstDayMonth(d); + timeSpan = timeSpanDAO.findByBeginTimeSpan(searchDate); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return timeSpan; + }*/ + + /* + * Recherche un timeSpan précis, avec sa date de création. + * @param timeSpanDTO timeSpan au format DTO qu'on recherche + * @return + * + public TimeSpan searchTimeSpanByDate(TimeSpanDTO timeSpanDTO) { + TimeSpan timeSpan = searchTimeSpanByDate(timeSpanDTO.getBeginTimeSpan()); + return timeSpan; + }*/ + + /* + * Recherche un timeSpan UNIQUE. Celui est identifié par son topiaId. + * @param topiaId Identifiant du timeSpan recherché + * @return + * + public TimeSpan searchTimeSpanWithTopiaId(String topiaId) { + TimeSpan timeSpan = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Recherche du timeSpan + timeSpan = timeSpanDAO.findByTopiaId(topiaId); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return timeSpan; + }*/ + + /* + * Permet de rechercher un timeSpan à l'aide d'une date. Il fait appel + * à la méthode searchTimeSpanByDate. + * La méthode renvoie un objet DTO. + * @param d + * @return + * + public TimeSpanDTO searchTimeSpanDTOByDate(Date d) { + TimeSpan timeSpan = searchTimeSpanByDate(d); + TimeSpanDTO timeSpanDTO = convertTimeSpan.timeSpanEntityToDto(timeSpan); + return timeSpanDTO; + }*/ + + /* + * Permet de faire une recherche de tous les timeSpans d'une période. + * @param period + * @return + * + public List<TimeSpan> searchListTimeSpan(Period period) { + List<TimeSpan> listTimeSpan = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Recherche les timeSpans avec cette période + listTimeSpan = timeSpanDAO.findAllByPeriod(period); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return listTimeSpan; + }*/ + + /* + * Permet de rechercher tous les timeSpans suivant une période donnée. + * Chaque timeSpan est converti ensuite en DTO. + * @param period + * @return + * + public List<TimeSpanDTO> searchListTimeSpanDTO(Period period) { + List<TimeSpanDTO> listTimeSpanDTO = new ArrayList<TimeSpanDTO>(); + List<TimeSpan> listTimeSpan = searchListTimeSpan(period); + for (TimeSpan timeSpan : listTimeSpan) { + TimeSpanDTO timeSpanDTO = convertTimeSpan + .timeSpanEntityToDto(timeSpan); + listTimeSpanDTO.add(timeSpanDTO); + } + return listTimeSpanDTO; + }*/ + + /* + * Permet de bloquer un timespan, celle-ci ne doit pas être bloquée. + * La fonction doit s'assurer que les timeSpans précédents doivent être + * bloqués. + * Les transactions doivent être équilibrées + * @param timespan période qui doit être fermée + * @param period période (12 smois) + * + public String blockTimeSpan(TimeSpan timespan) { + String result = ServiceHelper.RESPOND_ERROR; + // Si la période n'est pas déjà fermée. + if (timespan.getLocked()) { + if (log.isInfoEnabled()) { + log.info("Timespan deja bloqué !"); + } + } else { + Period period = getPeriodWithTimeSpan(timespan); + if (period.getLocked()) { + if (log.isErrorEnabled()) { + log.error("La période du timespan est bloquée !"); + } + } else { + // Vérifie si tous les timeSpans précédents sont bloqués + boolean AllTimeSpanBlock = alltimeSpanBlocked(timespan, period); + if (AllTimeSpanBlock) { + // Enregistrement dans la base de données + try { + // Acces BDD + TopiaContext topiaContext = rootContext + .beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + + // Vérifie si les transactons sont équilibrées + List<Transaction> listTransaction = transactionServiceImpl + .searchListTransactionWithTimeSpan(timespan); + boolean isTransactionBalanced = true; + boolean existTransactionNotBalanced = false; + for (Transaction transaction : listTransaction) { + isTransactionBalanced = transactionServiceImpl + .isTransactionBalanced(transaction); + if (!isTransactionBalanced) { + if (log.isInfoEnabled()) { + log.info("La transaction n'est pas bloquée."); + } + existTransactionNotBalanced = true; + } + } + if (!existTransactionNotBalanced) { + // Bloque la période + timespan.setLocked(true); + // Mise à jour de timespan dans la BDD + timeSpanDAO.update(timespan); + // Création BDD + topiaContext.commitTransaction(); + if (log.isInfoEnabled()) { + log.info("Timespan bloqué avec succès"); + } + result = ServiceHelper.RESPOND_SUCCESS; + } else { + result = ServiceHelper.TRANSACTION_NOT_BALANCED; + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + } else { + if (log.isErrorEnabled()) { + log.error("Il existe un ou plusieurs timespans précédents" + + " non bloqués."); + } + result = ServiceHelper.TIMESPAN_PREC_NOT_BLOCK; + } + } + } + return result; + }*/ + + /* + * Permet de bloquer une période au format DTO. + * + * @param timespanDTO + * @return + * + public String blockTimeSpan(TimeSpanDTO timespanDTO) { + return blockTimeSpan(searchTimeSpanByDate(timespanDTO)); + }*/ + + /* + * Permet de débloquer un timespan, à condition que les timespans suivants + * celui-ci soient bien débloqués. + * @param timespan + * @param period + * @return + * + public String unblockTimeSpan(TimeSpan timespan) { + String result = ServiceHelper.RESPOND_ERROR; + // Si le timspan n'est pas bloqué + if (!timespan.getLocked()) { + if (log.isWarnEnabled()) { + log.warn("Timespan non bloqué !"); + } + } else { + Period period = getPeriodWithTimeSpan(timespan); + if (period.getLocked()) { + if (log.isErrorEnabled()) { + log.error("La période du timespan est bloquée !"); + } + } else { + boolean NextTimeSpanUnblock = nextTimeSpanUnblock(timespan, + period); + // Si aucun timespan suivant bloqué + if (NextTimeSpanUnblock) { + try { + // Acces BDD + TopiaContext topiaContext = rootContext + .beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // débloque la période + timespan.setLocked(false); + // Mise à jour de timespan dans la BDD + timeSpanDAO.update(timespan); + // Création BDD + topiaContext.commitTransaction(); + if (log.isInfoEnabled()) { + log.info("Timespan débloqué avec succès"); + } + result = ServiceHelper.RESPOND_SUCCESS; + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + } else { + result = ServiceHelper.TIMESPAN_NEXT_NOT_BLOCK; + } + } + } + return result; + }*/ + + /* + * Permet de bloquer une période au format DTO. + * + * @param timespanDTO + * @return + * + public String unblockTimeSpan(TimeSpanDTO timespanDTO) { + return unblockTimeSpan(searchTimeSpanByDate(timespanDTO)); + }*/ + + /* + * Cette méthode va rechercher tous les timeSpans non bloqués après + * le timeSpan renseigné en paramètre. + * Si elle trouve au moins un timeSpan NON bloqué, elle renvoie alors faux. + * Cette méthode permet essentiellement de définir si il est possible + * ou non de bloquer un timeSpan. A savoir, un timeSpan ne peut être bloqué, + * si il existe des timeSpans suivant (dans le calendrier) qui sont non + * bloqués. + * @param timespan + * @param period + * @return + * + private boolean nextTimeSpanUnblock(TimeSpan timespan, Period period) { + boolean NextTimeSpanUnblock = false; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Recherche des TimeSpans avec la même période. + // (on doit récupérer normalement 12 timeSpans) + List<TimeSpan> listeTimeSpanOfPeriod = timeSpanDAO + .findAllByPeriod(period); + NextTimeSpanUnblock = true; + for (TimeSpan timeSpanNext : listeTimeSpanOfPeriod) { + // Si le timespan est après celui qu'on souhaite bloquer ET est non bloqué + if (timeSpanNext.getBeginTimeSpan().compareTo( + timespan.getBeginTimeSpan()) == 1 + && timeSpanNext.getLocked()) { + NextTimeSpanUnblock = false; + if (log.isInfoEnabled()) { + log.info("Timespan " + timeSpanNext.toString() + + " est bloqué"); + } + } + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return NextTimeSpanUnblock; + }*/ + + /* + * Permet de renvoyer une période dont appartient le timeSpan. + * @param timeSpan timeSpan dont on souhaite retourner la période + * @return + * + private Period getPeriodWithTimeSpan(TimeSpan timeSpan) { + PeriodServiceImpl periodServiceImpl = new PeriodServiceImpl(); + Date beginTimeSpan = timeSpan.getBeginTimeSpan(); + Period period = periodServiceImpl.searchPeriodWithDate(beginTimeSpan); + return period; + }*/ + + /* + * Cette méthode renvoie vrai lorsque tous les timespans de la période + * précédent au timespan en paramètre sont bloqués. + * @param timespan + * @param period le paramètre period est important, en effet un timespan ne + * peut être indépendant. + * @return + * + private boolean alltimeSpanBlocked(TimeSpan timespan, Period period) { + boolean AllTimeSpanBlock = false; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Recherche des TimeSpans avec la même période. + // (on doit récupérer normalement 12 timeSpans) + List<TimeSpan> listeTimeSpanOfPeriod = timeSpanDAO + .findAllByPeriod(period); + // Fermeture BDD + topiaContext.closeContext(); + // On contrôle que les timeSpans précédents sont bloqués. + AllTimeSpanBlock = true; + for (TimeSpan timeSpanPrev : listeTimeSpanOfPeriod) { + // Si la période est avant celle qu'on souhaite bloquer ET est non bloquée + if (timeSpanPrev.getBeginTimeSpan().compareTo( + timespan.getBeginTimeSpan()) == -1 + && !timeSpanPrev.getLocked()) { + AllTimeSpanBlock = false; + if (log.isInfoEnabled()) { + log.info("Timespan " + timeSpanPrev.toString() + + " non bloqué"); + } + } + } + } catch (TopiaException e) { + log.error(e); + } + return AllTimeSpanBlock; + }*/ + + /* + * Permet d'effacer un timeSpan. Ce dernier ne doit pas être bloqué. + * @param timeSpan + * @return + * + public String removeTimeSpan(TimeSpan timeSpan) { + String result = ServiceHelper.RESPOND_ERROR; + // Si le timspan est bloqué + if (timeSpan.getLocked()) { + if (log.isWarnEnabled()) { + log.warn("Timespan bloqué !"); + } + } else { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Mise à jour de timespan dans la BDD + timeSpanDAO.delete(timeSpan); + // Création BDD + topiaContext.commitTransaction(); + if (log.isInfoEnabled()) { + log.info("Timespan supprimé avec succès"); + } + result = ServiceHelper.RESPOND_SUCCESS; + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + } + return result; + }*/ + + /* + * Vérifie si le timeSpan donné en paramètre est bloqué ou non. + * @param timeSpan + * @return + * + public boolean isTimeSpanBlocked(TimeSpan timeSpan) { + boolean isTimeSpanBlocked = true; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TimeSpanDAO timeSpanDAO = LimaCallaoDAOHelper + .getTimeSpanDAO(topiaContext); + // Mise à jour de timespan dans la BDD + TimeSpan timeSpanSearch = timeSpanDAO.findByTopiaId(timeSpan + .getTopiaId()); + isTimeSpanBlocked = timeSpanSearch.getLocked(); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return isTimeSpanBlocked; + }*/ +} Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/TransactionServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/TransactionServiceImpl.java) =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/TransactionServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/TransactionServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,746 @@ +/* + * *##% Callao TransactionServiceImpl + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.LimaConfig; +import org.chorem.lima.business.dto.EntryDTO; +import org.chorem.lima.business.dto.LogDTO; +import org.chorem.lima.business.dto.TransactionDTO; +import org.chorem.lima.business.utils.ServiceHelper; +import org.chorem.lima.entity.Account; +import org.chorem.lima.entity.Entry; +import org.chorem.lima.entity.EntryDAO; +import org.chorem.lima.entity.Journal; +import org.chorem.lima.entity.LimaCallaoDAOHelper; +import org.chorem.lima.entity.TimeSpan; +import org.chorem.lima.entity.Transaction; +import org.chorem.lima.entity.TransactionDAO; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaNotFoundException; + +/** + * 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 + */ +public class TransactionServiceImpl { + + private static final Log log = LogFactory + .getLog(TransactionServiceImpl.class); + + private TopiaContext rootContext; + + private LogServiceImpl logServiceImpl = new LogServiceImpl(); + + private EntryServiceImpl entryServiceImpl = new EntryServiceImpl(); + + private TimeSpanServiceImpl timeSpanServiceImpl = new TimeSpanServiceImpl(); + + public TransactionServiceImpl() { + LimaConfig config = LimaConfig.getInstance(); + try { + rootContext = TopiaContextFactory.getContext(config.getOptions()); + } catch (TopiaNotFoundException ex) { + if (log.isErrorEnabled()) { + log.error("Can't init topia context", ex); + } + } + } + + /** + * Permet de créer une transaction comptable. Pour ajouter une transaction, + * le timeSpan doit être non bloqué. + * @param entryDate + * @param voucherRef + * @param description + * @param timespan + * @param journal + * @return + */ + public void createTransaction(Transaction transaction /*Date entryDate, String voucherRef, + String description, TimeSpan timeSpan, Journal journal*/) { + /*String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + String isCorrectTransaction = isCorrectTransaction(timeSpan, + journal); + if (isCorrectTransaction.equals(ServiceHelper.RESPOND_SUCCESS)) { + // Creation de la transaction + Transaction newtransaction = transactionDAO.create(); + newtransaction.setTransDate(entryDate); + newtransaction.setVoucherRef(voucherRef); + newtransaction.setDescription(description); + newtransaction.setTimeSpan(timeSpan); + newtransaction.setJournal(journal); + // Création BDD + topiaContext.commitTransaction(); + if (log.isInfoEnabled()) { + log.info("Ajout avec succes de la transaction"); + } + + // Il renvoie soit l'identifiant topiaId ou SUCCESS. + result = newtransaction.getTopiaId(); + //result = ServiceHelper.RESPOND_SUCCESS; + } else { + result = isCorrectTransaction; + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result;*/ + } + + /* + * Permet de créer une transaction à partir d'une transaction DTO. + * ATTENTION : si le journal ou timespan n'existe pas, l'ajout ne peut se + * faire. Si on souhaite, on peut créer le journal automatiquement lors de + * l'ajout de la transaction si il n'existe pas. Pour le timeSpan, il n'est + * pas cohérent qu'il n'existe pas. On ne peut travailler que sur une période + * comptable existante, et par conséquent il ne faut pas le créer. + * @param transactionDTO + * @return + * + public String createTransaction(TransactionDTO transactionDTO) { + String result = ServiceHelper.RESPOND_ERROR; + // Vérifie que transactionDTO possède un journalDTO et un timeSpanDTO + if (transactionDTO.getJournalDTO() == null + || transactionDTO.getTimeSpanDTO() == null) { + if (log.isErrorEnabled()) { + log.error("L'objet transactionDTO ne possède pas de timeSpan ET/OU de journal."); + } + result = ServiceHelper.TRANSACTION_NOT_JOURNAL; + } else { + // Recherche du journal + JournalServiceImpl journalServiceImpl = new JournalServiceImpl(); + Journal journal = journalServiceImpl + .searchJournalWithLabel(transactionDTO.getJournalDTO() + .getLabel()); + // Recherche du timeSpan + TimeSpan timeSpan = timeSpanServiceImpl + .searchTimeSpanByDate(transactionDTO.getTimeSpanDTO() + .getBeginTimeSpan()); + + // Vérification si timeSpan et Journal existe bien + if (journal == null) { + if (log.isErrorEnabled()) { + log.error("Création transaction : Le journal " + + transactionDTO.getJournalDTO().getLabel() + + " n'existe pas."); + } + result = ServiceHelper.TRANSACTION_NOT_JOURNAL; + } else { + if (timeSpan == null) { + if (log.isErrorEnabled()) { + log.error("Création transaction : Le timeSpan " + + transactionDTO.getTimeSpanDTO().toString() + + " n'existe pas."); + } + result = ServiceHelper.TRANSACTION_NOT_TIMESPAN; + } else { + result = createTransaction(transactionDTO.getEntryDate(), + transactionDTO.getVoucherRef(), transactionDTO + .getDescription(), timeSpan, journal); + } + } + } + return result; + }*/ + + /* + * Permet de modifier une transaction. Cette dernière est identifiée par la + * clé topiaId. + * @param topiaId + * @param entryDate + * @param voucherRef + * @param description + * @param timespan + * @param journal + * @return + * + public String modifyTransaction(String topiaId, Date entryDate, + String voucherRef, String description, TimeSpan timeSpan, + Journal journal) { + String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Vérification que la transaction existe bien + Transaction transaction = transactionDAO.findByTopiaId(topiaId); + if (transaction == null) { + if (log.isInfoEnabled()) { + log.info("La transaction " + voucherRef + + " n'existe pas. (identifiant " + topiaId + ")"); + } + result = ServiceHelper.TRANSACTION_NOT_EXIST; + } else { + // Vérification si la transaction possède de bons paramètres + String correct = isCorrectTransaction(timeSpan, journal); + // Si la transaction est correcte + if (correct.equals(ServiceHelper.RESPOND_SUCCESS)) { + // Modification + transaction.setTransDate(entryDate); + transaction.setVoucherRef(voucherRef); + transaction.setDescription(description); + transaction.setTimeSpan(timeSpan); + transaction.setJournal(journal); + transaction.update(); + // Création BDD + topiaContext.commitTransaction(); + result = ServiceHelper.RESPOND_SUCCESS; + } + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result; + }*/ + + /* + * Permet de modifier une transaction à partir d'une transaction DTO. + * Elle va rechercher le journal et le timespan correspondants. + * @param transactionDTO + * @return + * + public String modifyTransaction(TransactionDTO transactionDTO) { + // Recherche du journal + JournalServiceImpl journalServiceImpl = new JournalServiceImpl(); + Journal journal = journalServiceImpl + .searchJournalWithLabel(transactionDTO.getJournalDTO() + .getLabel()); + // Recherche du timeSpan + TimeSpan timeSpan = timeSpanServiceImpl + .searchTimeSpanByDate(transactionDTO.getTimeSpanDTO() + .getBeginTimeSpan()); + // Appel pour la modification + String result = modifyTransaction(transactionDTO.getId(), + transactionDTO.getEntryDate(), transactionDTO.getVoucherRef(), + transactionDTO.getDescription(), timeSpan, journal); + return result; + }*/ + + /* + * Recherche une transaction unique avec son identifiant TopiaId. + * @param topiaId + * @return + * + public Transaction searchTransactionWithTopiaId(String topiaId) { + Transaction transaction = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche + transaction = transactionDAO.findByTopiaId(topiaId); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return transaction; + }*/ + + /* + * Recherche une transaction unique à partir d'une transaction DTO. + * @param transactionDTO + * @return + * + public Transaction searchTransactionWithTopiaId( + TransactionDTO transactionDTO) { + Transaction transaction = searchTransactionWithTopiaId(transactionDTO + .getId()); + return transaction; + }*/ + + /* + * Recherche une transaction dans la base de données, et renvoie celle-ci + * sous format DTO. Nous ne pouvons pas appeler la méthode searchTransactionWithTopiaId + * du fait que lors de la convertion, nous avons besoin du journal et du + * timeSpan. Or il ne faut donc pas de fermeture de connexion à la base de + * données pour celà. + * @param topiaId + * @return + * + public TransactionDTO searchTransactionDTO(String topiaId) { + TransactionDTO transactionDTO = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche + Transaction transaction = transactionDAO.findByTopiaId(topiaId); + // Converti la transaction en DTO + convertTransaction.setTransaction(rootContext); + transactionDTO = convertTransaction + .transactionEntityToDto(transaction); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return transactionDTO; + }*/ + + /* + * Recherche toutes les transactions qui correspondent à un timespan. + * @param timeSpan + * @return + * + public List<Transaction> searchListTransactionWithTimeSpan(TimeSpan timeSpan) { + List<Transaction> listTransaction = null; + if (timeSpan != null) { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche + listTransaction = transactionDAO.findAllByTimeSpan(timeSpan); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + } + return listTransaction; + }*/ + + /* + * Recherche les transactions DTO d'un timeSpan + * @param timeSpan + * @return + * + public List<TransactionDTO> searchListTransactionDTOWithTimeSpan( + TimeSpan timeSpan) { + List<TransactionDTO> listTransactionDTO = new ArrayList<TransactionDTO>(); + if (timeSpan != null) { + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche + List<Transaction> listTransaction = transactionDAO + .findAllByTimeSpan(timeSpan); + // Converti la transaction en DTO + convertTransaction.setTransaction(rootContext); + for (Transaction transaction : listTransaction) { + TransactionDTO transactionDTO = convertTransaction + .transactionEntityToDto(transaction); + listTransactionDTO.add(transactionDTO); + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + } + return listTransactionDTO; + }*/ + + /* + * Recherche toutes les transactions appartenant à un même journal donné + * en paramètre. + * @param journal + * @return + * + public List<Transaction> searchListTransactionWithJournal(Journal journal) { + List<Transaction> listTransaction = null; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche + listTransaction = transactionDAO.findAllByJournal(journal); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return listTransaction; + }*/ + + /* + * Permet de rechercher toutes les transactions dans la base de données, + * avec en retour une liste de transactions au format DTO. + * @return + * + public List<TransactionDTO> getAllTransactionDTO() { + List<TransactionDTO> listTransactionDTO = new ArrayList<TransactionDTO>(); + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche + List<Transaction> listTransaction = transactionDAO.findAll(); + // Converti la transaction en DTO + convertTransaction.setTransaction(rootContext); + for (Transaction transaction : listTransaction) { + TransactionDTO transactionDTO = convertTransaction + .transactionEntityToDto(transaction); + listTransactionDTO.add(transactionDTO); + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return listTransactionDTO; + }*/ + + /* + * Cette méthode permet de vérifier si une transaction possède des paramètres + * corrects. + * Un journal doit exister. + * Un timeSpan doit exister et être non bloqué. + * @param timeSpan + * @param journal + * @return + * + public String isCorrectTransaction(TimeSpan timeSpan, Journal journal) { + String result = ServiceHelper.RESPOND_SUCCESS; + // Vérification si timeSpan et Journal existe bien + if (journal == null) { + if (log.isErrorEnabled()) { + log.error("Création transaction : Le journal n'existe pas."); + } + result = ServiceHelper.TRANSACTION_NOT_JOURNAL; + } + if (timeSpan == null) { + if (log.isErrorEnabled()) { + log.error("Création transaction : Le timeSpan n'existe pas."); + } + result = ServiceHelper.TRANSACTION_NOT_TIMESPAN; + } else { + // Vérifie si le timeSpan est bloqué + if (timeSpan.getLocked()) { + if (log.isErrorEnabled()) { + log.error("Le timeSpan est bloqué ! Il est donc impossible" + + " d'ajouter une transaction sur cette période. (" + + "Période du " + timeSpan + ")"); + } + result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; + } + } + return result; + }*/ + + /* + * Permet d'effacer une transaction dans la base de données. + * ATTENTION : Elle supprime également toutes les entées comptables + * associées. Une transaction appartenant à un timeSpan bloqué ne peut être + * supprimée. + * @return + * + public String removeTransaction(String topiaId) { + String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche de l'entry + Transaction transaction = transactionDAO.findByTopiaId(topiaId); + // Transaction doit exister + if (transaction != null) { + // Vérifie si la transaction est non bloquée. + if (!isTransactionBlocked(transaction)) { + // Supprime tous les entrys de la transactions + List<Entry> listEntry = entryServiceImpl + .searchEntryWithTransaction(transaction); + for (Entry entry : listEntry) { + result = removeEntry(entry.getTopiaId()); + } + // Supprime la transaction + transactionDAO.delete(transaction); + // Création BDD + topiaContext.commitTransaction(); + if (log.isInfoEnabled()) { + log.info("La transaction a été supprimée avec succès."); + } + result = ServiceHelper.RESPOND_SUCCESS; + } else { + // Transaction bloquée + result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; + } + } else { + result = ServiceHelper.TRANSACTION_NOT_EXIST; + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result; + }*/ + + /* + * Supprime une transaction au format DTO. + * @param transactionDTO + * @return + * + public String removeTransaction(TransactionDTO transactionDTO) { + String result = removeTransaction(transactionDTO.getId()); + return result; + }*/ + + /* + * Permet d'ajouter une entrée comptable pour une transaction donnée. + * ATTENTION : la transaction doit être NON bloquée. + * + * @param description + * @param amount + * @param debit + * @param lettering + * @param detail + * @param transaction + * @return + * + public String addEntry(String description, String amount, boolean debit, + String lettering, String detail, Transaction transaction, + Account account) { + String result = ServiceHelper.RESPOND_ERROR; + // Si la transaction est non bloquée + if (!isTransactionBlocked(transaction)) { + // Si il renvoie succes et non l'identifiant (à commenter dans la classe correspondante) + result = entryServiceImpl.createEntry(description, amount, debit, + lettering, detail, transaction, account); + } else { + result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; + } + return result; + }*/ + + /* + * Permet d'ajouter une entrée comptable pour une transaction donnée. + * L'entrée est sous format DTO. + * + * @param entryDTO + * @return + * + public String addEntry(EntryDTO entryDTO) { + String result = ServiceHelper.RESPOND_ERROR; + // Recherche TransactionDTO + TransactionDTO transactonDTO = entryDTO.getTransactionDTO(); + Transaction transaction = searchTransactionWithTopiaId(transactonDTO); + // Si la transaction est non bloquée + if (!isTransactionBlocked(transaction)) { + + // Si il renvoie succes et non l'identifiant (à commenter dans la classe correspondante) + result = entryServiceImpl.createEntry(entryDTO); + } else { + result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; + } + return result; + }*/ + + /* + * Permet de modifier une entrée comptable. + * ATTENTION : la transaction doit être NON bloquée. + * + * @param topiaId + * @param description + * @param amount + * @param debit + * @param lettering + * @param detail + * @param transaction + * @param account + * @return + * + public String modifyEntry(String topiaId, String description, + String amount, boolean debit, String lettering, String detail, + Transaction transaction, Account account) { + String result = ServiceHelper.RESPOND_ERROR; + if (!isTransactionBlocked(transaction)) { + result = entryServiceImpl.modifyEntry(topiaId, description, amount, + debit, lettering, detail, account); + } else { + result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; + } + return result; + }*/ + + /* + * Permet de modifier une entrée. + * @param entryDTO + * @return + * + public String modifyEntry(EntryDTO entryDTO) { + String result = ServiceHelper.RESPOND_ERROR; + // Recherche TransactionDTO + TransactionDTO transactonDTO = entryDTO.getTransactionDTO(); + Transaction transaction = searchTransactionWithTopiaId(transactonDTO); + if (!isTransactionBlocked(transaction)) { + result = entryServiceImpl.modifyEntry(entryDTO); + } else { + result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; + } + return result; + }*/ + + /* + * Permet d'effacer une entrée comptable. Elle est identifiée par son identifiant + * topiaID. Une entrée peut être supprimée seulement si elle est non bloquée. + * @param topiaId + * @return + * + public String removeEntry(String topiaId) { + String result = ServiceHelper.RESPOND_ERROR; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + EntryDAO entryDAO = LimaCallaoDAOHelper.getEntryDAO(topiaContext); + // Recherche de l'entry + Entry entryDelete = entryDAO.findByTopiaId(topiaId); + // Entry doit exister + if (entryDelete != null) { + // Prend la transaction dont appartient entry + Transaction transaction = entryDelete.getTransaction(); + // Vérifie si la transaction est non bloquée. + if (!isTransactionBlocked(transaction)) { + // Création d'un log DTO + LogDTO logDTO = new LogDTO("", new Date(), + ServiceHelper.LOG_REMOVE, transaction + .getTransDate(), transaction + .getVoucherRef(), transaction + .getDescription(), entryDelete + .getDescription(), entryDelete.getAmount(), + entryDelete.getDebit(), entryDelete.getLettering()); + // Appel pour supprimer l'entrée + result = entryServiceImpl.removeEntry(topiaId); + // Si la suppression s'est bien déroulée, création log + if (result.equals(ServiceHelper.RESPOND_SUCCESS)) { + // Ajout du log + logServiceImpl.addLog(logDTO); + } + } else { + result = ServiceHelper.TRANSACTION_TIMESPAN_BLOCKED; + } + } else { + result = ServiceHelper.ENTRY_NOT_EXIST; + } + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return result; + }*/ + + /* + * Permet de supprimer une entrée à partir d'un DTO. + * @param entryDTO + * @return + * + public String removeEntry(EntryDTO entryDTO) { + String result = removeEntry(entryDTO.getId()); + return result; + }*/ + + /* + * Permet de vérifier si une transaction est dans une période bloquée ou non + * @param transaction + * @return + * + public boolean isTransactionBlocked(Transaction transaction) { + boolean isTransactionBlocked = true; + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + TransactionDAO transactionDAO = LimaCallaoDAOHelper + .getTransactionDAO(topiaContext); + // Recherche + Transaction transactionSearch = transactionDAO + .findByTopiaId(transaction.getTopiaId()); + isTransactionBlocked = timeSpanServiceImpl + .isTimeSpanBlocked(transactionSearch.getTimeSpan()); + // Fermeture BDD + topiaContext.closeContext(); + } catch (TopiaException e) { + log.error(e); + } + return isTransactionBlocked; + }*/ + + /* + * Permet de vérifier si une transaction est équilibrée. + * @param transaction + * @return + * + public boolean isTransactionBalanced(Transaction transaction) { + List<EntryDTO> ListEntryDTO = entryServiceImpl + .searchEntryDTOWithTransaction(transaction); + float debit = 0; + float credit = 0; + // Pour toutes les entrées comptables trouvées + for (EntryDTO entryDTO : ListEntryDTO) { + // Si entrée au debit + if (entryDTO.isDebit()) { + debit = debit + + Float.parseFloat(entryDTO.getAmount().replaceFirst( + ",", ".")); + } else { + credit = credit + + Float.parseFloat(entryDTO.getAmount().replaceFirst( + ",", ".")); + } + } + // Vérifie si le debit == credit + boolean isTransactionBalanced = debit == credit; + return isTransactionBalanced; + }*/ + +} \ No newline at end of file Copied: trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/UserServiceImpl.java (from rev 2802, trunk/lima-business/src/main/java/org/chorem/lima/business/UserServiceImpl.java) =================================================================== --- trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/UserServiceImpl.java (rev 0) +++ trunk/lima-business/src/main/java/org/chorem/lima/business/ejb/UserServiceImpl.java 2010-03-23 15:26:54 UTC (rev 2811) @@ -0,0 +1,118 @@ +/* + * *##% Callao + * Copyright (C) 2010 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.business.ejb; + +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.entity.LimaCallaoDAOHelper; +import org.chorem.lima.entity.User; +import org.chorem.lima.entity.UserDAO; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaNotFoundException; + +/** + * User service. + * + * @author chatellier + * @version $Revision$ + * + * Last update : $Date$ + * By : $Author$ + */ +public class UserServiceImpl { + + /** log */ + private static final Log log = LogFactory.getLog(UserServiceImpl.class); + + private TopiaContext rootContext; + + public UserServiceImpl() { + LimaConfig config = LimaConfig.getInstance(); + try { + rootContext = TopiaContextFactory.getContext(config.getOptions()); + } catch (TopiaNotFoundException ex) { + if (log.isErrorEnabled()) { + log.error("Can't init topia context", ex); + } + } + } + + /** + * Add new user. + * + * @param name new user name + * @throws LimaException + */ + public void addUser(User user/*String name*/) throws LimaException { + /*// Attention doublon utilisateur + try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + UsersDAO userdao = LimaCallaoDAOHelper.getUsersDAO(topiaContext); + // Création de l'user + Users newuser = userdao.create(); + newuser.setMatcher(name); + // Création BDD + topiaContext.commitTransaction(); + topiaContext.closeContext(); + if (log.isInfoEnabled()) { + log.info("Add user : " + name); + } + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Can't create user", ex); + throw new LimaException("Can't create user", ex); + } + + }*/ + } + + /** + * Find user with name. + * + * @param name + * @throws LimaException + */ + public void findUser(String name) throws LimaException { + /*try { + // Acces BDD + TopiaContext topiaContext = rootContext.beginTransaction(); + // Chargement du DAO + UsersDAO userdao = LimaCallaoDAOHelper.getUsersDAO(topiaContext); + // Recherche du user + Users newuser = userdao.findByMatcher(name); + // Fermeture BDD + topiaContext.closeContext(); + if (newuser == null) { + throw new LimaBusinessException("can't find user " + name); + } + } catch (TopiaException ex) { + if (log.isErrorEnabled()) { + log.error("Can't find user", ex); + throw new LimaException("Can't find user", ex); + } + }*/ + } +}