Skip to content
Snippets Groups Projects
bon-prelevement.class.php 39.1 KiB
Newer Older
Benoit Mortier's avatar
 
Benoit Mortier committed
<?php
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
/* Copyright (C) 2004-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * $Id$
 * $Source$
 */

Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
/**
        \file       htdocs/bon-prelevement.class.php
        \ingroup    prelevement
        \brief      Fichier de la classe des bons de prlvements
        \version    $Revision$
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
require_once (DOL_DOCUMENT_ROOT."/facture.class.php");
require_once (DOL_DOCUMENT_ROOT."/societe.class.php");

class BonPrelevement
{
    var $db;

    var $date_echeance;
    var $raison_sociale;
    var $reference_remise;
    var $emetteur_code_guichet;
    var $emetteur_numero_compte;
    var $emetteur_code_etablissement;
    var $total;
    var $_fetched;

    function BonPrelevement($DB, $filename='')
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
    {
        $this->filename=$filename;
        
        $this->date_echeance = time();
        $this->raison_sociale = "";
        $this->reference_remise = "";
        $this->emetteur_code_guichet = "";
        $this->emetteur_numero_compte = "";
        $this->emetteur_code_etablissement = "";
        $this->numero_national_emetteur = "";
        $this->methodes_trans = array();
        $this->methodes_trans[0] = "Internet";
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
    }

    /**
     *
     *
     */
    function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number)
        $result = 0;
        $ligne_id = 0;

        $result = $this->AddLigne($ligne_id, $client_id, $client_nom,
        $amount, $code_banque, $code_guichet, $number);

        if ($result == 0)
        {
            if ($ligne_id > 0)
            {
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture ";
                $sql .= " (fk_facture,fk_prelevement_lignes)";
                $sql .= " VALUES (".$facture_id.",".$ligne_id.")";

                if ($this->db->query($sql))
                {
                    $result = 0;
                }
                else
                {
                    $result = -1;
                    dolibarr_syslog("BonPrelevement::AddFacture Erreur $result");
                }
            }
            else
            {
                $result = -2;
                dolibarr_syslog("BonPrelevement::AddFacture Erreur $result");
            }
        }
        else
        {
            $result = -3;
            dolibarr_syslog("BonPrelevement::AddFacture Erreur $result");
        }

        return $result;

    function AddLigne(&$ligne_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number)
    {
        $result = -1;
        $concat = 0;

        if ($concat == 1)
        {
            /*
             * On aggrge les lignes
             */
            $sql = "SELECT rowid FROM  ".MAIN_DB_PREFIX."prelevement_lignes";
            $sql .= " WHERE fk_prelevement_bons".$this->id;
            $sql .= " AND fk_soc       =".$client_id;
            $sql .= " AND code_banque  ='".$code_banque."'";
            $sql .= " AND code_guichet ='".$code_guichet."'";
            $sql .= " AND number       ='".$number."'";

            if ($this->db->query($sql))
            {
                $num = $this->db->num_rows();
            }
            else
            {
                $result = -1;
            }
        }
        else
        {
            /*
             * Pas de d'agrgation
             */
            $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes (fk_prelevement_bons";
            $sql .= " , fk_soc , client_nom ";
            $sql .= " , amount";
            $sql .= " , code_banque , code_guichet , number)";

            $sql .= " VALUES (".$this->id;
            $sql .= ",".$client_id.",'".addslashes($client_nom)."'";
            $sql .= ",'".ereg_replace(",",".",$amount)."'";
            $sql .= ", '$code_banque', '$code_guichet', '$number')";

            if ($this->db->query($sql))
            {
                $ligne_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes");
                $result = 0;
            }
            else
            {
                dolibarr_syslog("BonPrelevement::AddLigne Erreur -2");
                $result = -2;
            }

        }

        return $result;
    }

    /**
    function ReadError($error)
    {
        $errors = array();

        $errors[1027] = "Date invalide";

        return $errors[abs($error)];
    }

    /**
     *
     */
    function Fetch($rowid)
    {
        $sql = "SELECT p.rowid, p.ref, p.amount, p.note, p.credite";
        $sql .= ",".$this->db->pdate("p.datec")." as dc";
        $sql .= ",".$this->db->pdate("p.date_trans")." as date_trans";
        $sql .= " , method_trans, fk_user_trans";
        $sql .= ",".$this->db->pdate("p.date_credit")." as date_credit";
        $sql .= " , fk_user_credit";
        $sql .= " , statut";
        $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";

        $sql .= " WHERE p.rowid=".$rowid;

        $result=$this->db->query($sql);
        if ($result)
        {
            if ($this->db->num_rows($result))
            {
                $obj = $this->db->fetch_object();

                $this->id                 = $obj->rowid;
                $this->ref                = $obj->ref;
                $this->amount             = $obj->amount;
                $this->note               = stripslashes($obj->note);
                $this->datec              = $obj->dc;
                $this->credite            = $obj->credite;

                $this->date_trans         = $obj->date_trans;
                $this->method_trans       = $obj->method_trans;
                $this->user_trans         = $obj->fk_user_trans;

                $this->date_credit        = $obj->date_credit;
                $this->user_credit        = $obj->fk_user_credit;

                $this->statut             = $obj->statut;

                $this->_fetched = 1;

                return 0;
            }
            else
            {
                dolibarr_syslog("BonPrelevement::Fetch Erreur aucune ligne retourne");
                return -1;
            }
        }
        else
        {
            dolibarr_syslog("BonPrelevement::Fetch Erreur ");
            dolibarr_syslog($sql);
            return -2;
        }
    }

    /**
        $error == 0;

        if ($this->db->begin())
        {
            $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
            $sql .= " SET credite = 1";
            $sql .= " WHERE rowid=".$this->id;

            $result=$this->db->query($sql);
            if (! $result)
            {
                dolibarr_syslog("bon-prelevement::set_credite Erreur 1");
                $error++;
            }

            if ($error == 0)
            {
                $facs = array();
                $facs = $this->_get_list_factures();

                for ($i = 0 ; $i < sizeof($facs) ; $i++)
                {
                    /* Tag la facture comme impaye */
                    dolibarr_syslog("BonPrelevement::set_credite set_payed fac ".$facs[$i]);
                    $fac = new Facture($this->db);
                    $fac->fetch($facs[$i]);
                    $result = $fac->set_payed($user);
                }
            }

            if ($error == 0)
            {

                $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes ";
                $sql .= " SET statut  = 2";
                $sql .= " WHERE fk_prelevement_bons=".$this->id;

                if (! $this->db->query($sql))
                {
                    dolibarr_syslog("BonPrelevement::set_credite Erreur 1");
                    $error++;
                }
            }

            /*
             * Fin de la procdure
             *
             */
            if ($error == 0)
            {
                $this->db->commit();
                return 0;
            }
            else
            {

                $this->db->rollback();
                dolibarr_syslog("BonPrelevement::set_credite ROLLBACK ");

                return -1;
            }


        }
        else
        {

            dolibarr_syslog("BonPrelevement::set_credite Ouverture transaction SQL impossible ");
            return -2;
        }
    }

    /**
     *
     *
     */
    function set_infocredit($user, $date)
    {
        $error == 0;

        if ($this->_fetched == 1)
        {
            if ($date >= $this->date_trans)
            {
                if ($this->db->begin())
                {
                    $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
                    $sql .= " SET fk_user_credit = ".$user->id;
                    $sql .= " , statut = 2";
                    $sql .= " , date_credit='".$this->db->idate($date)."'";
                    $sql .= " WHERE rowid=".$this->id;
                    $sql .= " AND statut = 1";

                    if ($this->db->query($sql))
                    {
                        $subject = "Crdit prlvement ".$this->ref."  la banque";
                        $message = "Le bon de prlvement ".$this->ref;
                        $message .= " a t crdit par la banque.\n";
                        $message .= "Date crdit : ".strftime("%A %e %B %Y", $date);

                        $this->Notify($user, "cr", $subject, $message);
                    }
                    else
                    {
                        dolibarr_syslog("BonPrelevement::set_infocredit Erreur 1");
                        $error++;
                    }

                    /*
                     * Fin de la procdure
                     *
                     */
                    if ($error == 0)
                    {
                        $this->db->commit();
                        return 0;
                    }
                    else
                    {
                        $this->db->rollback();
                        dolibarr_syslog("bon-prelevment::set_infocredit ROLLBACK ");
                        return -1;
                    }
                }
                else
                {
                    dolibarr_syslog("bon-prelevement::set_infocredit Ouverture transaction SQL impossible ");
                    return -1025;
                }
            }
            else
            {
                dolibarr_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans ");
                return -1027;
            }
        }
        else
        {
            return -1026;
        }
    }

    /**
     *
     *
    function set_infotrans($user, $date, $method)
    {
        $error == 0;
        dolibarr_syslog("bon-prelevement::set_infotrans Start",LOG_INFO);
        if ($this->db->begin())
        {
            $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
            $sql .= " SET fk_user_trans = ".$user->id;
            $sql .= " , date_trans='".$this->db->idate($date)."'";
            $sql .= " , method_trans=".$method;
            $sql .= " , statut = 1";
            $sql .= " WHERE rowid=".$this->id;
            $sql .= " AND statut = 0";

            if ($this->db->query($sql))
            {
                $this->method_trans = $method;

                $subject = "Transmission du prlvement ".$this->ref."  la banque";
                $message = "Le bon de prlvement ".$this->ref;
                $message .= " a t transmis  la banque par ".$user->prenom. " ".$user->nom;
                $message .= "\n\n";
                $message .= "\nMontant : ".price($this->amount);
                $message .= "\nMthode : ".$this->methodes_trans[$this->method_trans];
                $message .= "\nDate  : ".strftime("%A %e %B %Y", $date);

                $this->Notify($user,"tr", $subject, $message, 1);
            }
            else
            {
                dolibarr_syslog("bon-prelevement::set_infotrans Erreur 1", LOG_ERR);
                dolibarr_syslog($this->db->error());
                $error++;
            }

            /*
             * Fin de la procdure
             *
             */
            if ($error == 0)
            {
                $this->db->commit();
                return 0;
            }
            else
            {
                $this->db->rollback();
                dolibarr_syslog("BonPrelevement::set_infotrans ROLLBACK", LOG_ERR);

                return -1;
            }
        }
        else
        {

            dolibarr_syslog("BonPrelevement::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT);
            return -2;
        }
    }
    /**
     *
     *
     */
    function Notify($user, $action, $subject, $message, $joinfile=0)
    {
        $message .= "\n\n--\n";
        $message .= "Ceci est un message automatique envoy par Dolibarr";

        $sql = "SELECT u.name, u.firstname, u.email";
        $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
        $sql .= " , ".MAIN_DB_PREFIX."prelevement_notifications as pn";
        $sql .= " WHERE pn.action ='".$action."'";
        $sql .= " AND u.rowid = pn.fk_user;";

        $resql = $this->db->query($sql);
        if ($resql)
        {
            $num = $this->db->num_rows($resql);
            $i = 0;
            while ($i < $num)
            {
                $obj = $this->db->fetch_object($resql);

                require_once(DOL_DOCUMENT_ROOT."/lib/CMailFile.class.php");

                $sendto = $obj->firstname . " " .$obj->name . "<".$obj->email.">";
                $from = $user->prenom . " " .$user->nom . "<".$user->email.">";
                $arr_file = array();
                $arr_mime = array();
                $arr_name = array();
                if ($joinfile == 1)
                {
                    $arr_file = array(DOL_DATA_ROOT.'/prelevement/bon/'.$this->ref.'.ps');
                    $arr_mime = array("application/ps");
                    $arr_name = array($this->ref.".ps");
                }

                $mailfile = new CMailFile($subject,$sendto,$from,$message,$arr_file,$arr_mime,$arr_name);

                $result=$mailfile->sendfile();

                $i++;
            }
            $this->db->free($resql);
        }
    }
    /**
     *    \brief      Recupre la liste des factures concernes
    function _get_list_factures()
    {
        $arr = array();

        /*
         * Renvoie toutes les factures prsente
         * dans un bon de prlvement
         */
        $sql = "SELECT fk_facture";
        $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
        $sql .= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl";
        $sql .= " , ".MAIN_DB_PREFIX."prelevement_facture as pf";
        $sql .= " WHERE pf.fk_prelevement_lignes = pl.rowid";
        $sql .= " AND pl.fk_prelevement_bons = p.rowid";
        $sql .= " AND p.rowid=".$this->id;

        $resql=$this->db->query($sql);
        if ($resql)
        {
            $num = $this->db->num_rows($resql);

            if ($num)
            {
                $i = 0;
                while ($i < $num)
                {
                    $row = $this->db->fetch_row($resql);
                    $arr[$i] = $row[0];
                    $i++;
                }
            }
            $this->db->free($resql);
        }
        else
        {
            dolibarr_syslog("Bon-Prelevement::_get_list_factures Erreur");
        }

        return $arr;
    }

    /**
     *
     *
     */
    function SommeAPrelever()
    {
        $sql = "SELECT sum(f.total_ttc)";
        $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
        $sql .= " , ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";

        $sql .= " WHERE f.fk_statut = 1";
        $sql .= " AND f.rowid = pfd.fk_facture";
        $sql .= " AND f.paye = 0";
        $sql .= " AND pfd.traite = 0";
        $sql .= " AND f.total_ttc > 0";
        $sql .= " AND f.fk_mode_reglement = 3";

        $resql = $this->db->query($sql);

        if ( $resql )
        {
            $row = $this->db->fetch_row($resql);

            return $row[0];

            $this->db->free($resql);
        }
        else
        {
            $error = 1;
            dolibarr_syslog("BonPrelevement::SommeAPrelever Erreur -1");
            dolibarr_syslog($this->db->error());
        }
    }

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
     *
     *
     */
    function NbFactureAPrelever($banque=0,$agence=0)
    {
        $sql = "SELECT count(f.total_ttc)";
        $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
        $sql .= " , ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
        $sql .= " , ".MAIN_DB_PREFIX."societe_rib as sr";

        $sql .= " WHERE f.fk_statut = 1";
        $sql .= " AND f.rowid = pfd.fk_facture";
        $sql .= " AND f.fk_soc = sr.fk_soc";
        $sql .= " AND f.paye = 0";
        $sql .= " AND pfd.traite = 0";
        $sql .= " AND f.total_ttc > 0";
        $sql .= " AND f.fk_mode_reglement = 3";

        if ($banque == 1)
        {
            $sql .= " AND sr.code_banque = '".PRELEVEMENT_CODE_BANQUE."'";
        }

        if ($agence == 1)
        {
            $sql .= " AND sr.code_guichet = '".PRELEVEMENT_CODE_GUICHET."'";
        }

        $resql = $this->db->query($sql);

        if ( $resql )
        {
            $row = $this->db->fetch_row($resql);

            return $row[0];

            $this->db->free($resql);
        }
        else
        {
            $error = 1;
            dolibarr_syslog("BonPrelevement::SommeAPrelever Erreur -1");
            dolibarr_syslog($this->db->error());
        }
    }

    /**
     *      \brief      Cree prelevement
     *
     */
    function Create($banque=0, $guichet=0)
    {
        global $conf;
        
        dolibarr_syslog("BonPrelevement::Create");

        require_once (DOL_DOCUMENT_ROOT."/bon-prelevement.class.php");
        require_once (DOL_DOCUMENT_ROOT."/facture.class.php");
        require_once (DOL_DOCUMENT_ROOT."/societe.class.php");
        require_once (DOL_DOCUMENT_ROOT."/paiement.class.php");

        $error = 0;

        $datetimeprev = time();

        $month = strftime("%m", $datetimeprev);
        $year = strftime("%Y", $datetimeprev);

        $user = new user($this->db, PRELEVEMENT_USER);

        /**
         * Lectures des factures
         */
        $factures = array();
        $factures_prev = array();

        if (!$error)
        {

            $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc";
            $sql .= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib";
            $sql .= ", pfd.amount";
            $sql .= ", s.nom";
            $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
            $sql .= " , ".MAIN_DB_PREFIX."societe as s";
            $sql .= " , ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
            $sql .= " , ".MAIN_DB_PREFIX."societe_rib as sr";

            $sql .= " WHERE f.rowid = pfd.fk_facture";
            $sql .= " AND s.idp = f.fk_soc";
            $sql .= " AND s.idp = sr.fk_soc";
            $sql .= " AND f.fk_statut = 1";
            $sql .= " AND f.paye = 0";
            $sql .= " AND pfd.traite = 0";
            $sql .= " AND f.total_ttc > 0";
            $sql .= " AND f.fk_mode_reglement = 3"; // Mode prlvement

            if ($banque == 1)
            {
                $sql .= " AND sr.code_banque = '".PRELEVEMENT_CODE_BANQUE."'";
            }
            if ($agence == 1)
            {
                $sql .= " AND sr.code_guichet = '".PRELEVEMENT_CODE_GUICHET."'";
            }

            $resql = $this->db->query($sql);

            if ($resql)
            {
                $num = $this->db->num_rows($resql);
                $i = 0;

                while ($i < $num)
                {
                    $row = $this->db->fetch_row($resql);
                    $factures[$i] = $row;
                    $i++;
                }
                $this->db->free($resql);
                dolibarr_syslog("$i factures  prlever");
            }
            else
            {
                $error = 1;
                dolibarr_syslog("Erreur -1");
                dolibarr_syslog($this->db->error());
            }
        }

        /*
         *
         * Verif des clients
         *
         */

        if (! $error)
        {
            /*
             * Vrification des RIB
             *
             */
            $i = 0;
            dolibarr_syslog("Dbut vrification des RIB");

            if (sizeof($factures) > 0)
            {
                foreach ($factures as $fac)
                {
                    $fact = new Facture($this->db);

                    if ($fact->fetch($fac[0]) == 1)
                    {
                        $soc = new Societe($this->db);
                        if ($soc->fetch($fact->socidp) == 1)
                        {
                            if ($soc->verif_rib() == 1)
                            {
                                $factures_prev[$i] = $fac;
                                /* second tableau necessaire pour bon-prelevement */
                                $factures_prev_id[$i] = $fac[0];
                                $i++;
                            }
                            else
                            {
                                dolibarr_syslog("Erreur de RIB societe $fact->socidp $soc->nom");
                            }
                        }
                        else
                        {
                            dolibarr_syslog("Impossible de lire la socit");
                        }
                    }
                    else
                    {
                        dolibarr_syslog("Impossible de lire la facture");
                    }
                }
            }
            else
            {
                dolibarr_syslog("Aucune factures a traiter");
            }
        }

        /*
         *
         *
         */

        dolibarr_syslog(sizeof($factures_prev)." factures seront prleves");

        if (sizeof($factures_prev) > 0)
        {
            /*
             * Ouverture de la transaction
             *
             */
            $result=$this->db->begin();
            if ($result <= 0)
            {
                $error++;
            }

            /*
             * Traitements
             *
             */
            if (!$error)
            {
                $ref = "T".substr($year,-2).$month;

                $sql = "SELECT count(*) FROM ".MAIN_DB_PREFIX."prelevement_bons";
                $sql .= " WHERE ref LIKE '$ref%'";

                $resql = $this->db->query($sql);

                if ($resql)
                {
                    $row = $this->db->fetch_row($resql);
                }
                else
                {
                    $error++;
                    dolibarr_syslog("Erreur recherche reference");
                }

                $ref = $ref . substr("00".($row[0]+1), -2);

                $filebonprev = $ref;

                /*
                 * Creation du bon de prelevement
                 *
                 */

                $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (ref,datec)";
                $sql .= " VALUES ('".$ref."',now())";

                $resql = $this->db->query($sql);

                if ($resql)
                {
                    $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons");

                    $dir=$conf->prelevement->dir_output.'/bon';
                    $file=$filebonprev;
                    if (! is_dir($dir)) create_exdir($dir);
                    
                    $bonprev = new BonPrelevement($this->db, $dir."/".$file);
                    $bonprev->id = $prev_id;
                }
                else
                {
                    $error++;
                    dolibarr_syslog("Erreur cration du bon de prelevement");
                }
            }

            /*
             *
             *
             */
            if (!$error)
            {
                dolibarr_syslog("Dbut gnration des paiements");
                dolibarr_syslog("Nombre de factures ".sizeof($factures_prev));

                if (sizeof($factures_prev) > 0)
                {
                    foreach ($factures_prev as $fac)
                    {
                        $fact = new Facture($this->db);
                        $fact->fetch($fac[0]);

                        $pai = new Paiement($this->db);

                        $pai->amounts = array();
                        $pai->amounts[$fac[0]] = $fact->total_ttc;
                        $pai->datepaye = $this->db->idate($datetimeprev);
                        $pai->paiementid = 3; // prlvement
                        $pai->num_paiement = $ref;

                        if ($pai->create($user, 1) == -1)  // on appelle en no_commit
                        {
                            $error++;
                            dolibarr_syslog("Erreur creation paiement facture ".$fac[0]);
                        }
                        else
                        {
                            /*
                            * Validation du paiement
                            */
                            $pai->valide();

                            /*
                            * Ajout d'une ligne de prlvement
                            *
                            *
                            * $fac[3] : banque
                            * $fac[4] : guichet
                            * $fac[5] : number
                            * $fac[6] : cle rib
                            * $fac[7] : amount
                            * $fac[8] : client nom
                            * $fac[2] : client id
                            */

                            $ri = $bonprev->AddFacture($fac[0], $fac[2], $fac[8], $fac[7],
                            $fac[3], $fac[4], $fac[5], $fac[6]);
                            if ($ri <> 0)
                            {
                                $error++;
                            }

                            /*
                             * Mise  jour des demandes
                             *
                             */
                            $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande";
                            $sql .= " SET traite = 1";
                            $sql .= ", date_traite=now()";
                            $sql .= ", fk_prelevement_bons = ".$prev_id;
                            $sql .= " WHERE rowid=".$fac[1];

                            if ($this->db->query($sql))
                            {

                            }
                            else
                            {
                                $error++;
                                dolibarr_syslog("Erreur mise a jour des demandes");
                                dolibarr_syslog($this->db->error());
                            }

                        }
                    }
                }

                dolibarr_syslog("Fin des paiements");
            }

            if (!$error)
            {
                /*
                 * Bon de Prelevement
                 *
                 *
                 */

                dolibarr_syslog("Debut prelevement");
                dolibarr_syslog("Nombre de factures ".sizeof($factures_prev));

                if (sizeof($factures_prev) > 0)
                {
                    $bonprev->date_echeance = $datetimeprev;
                    $bonprev->reference_remise = $ref;

                    $bonprev->numero_national_emetteur = PRELEVEMENT_NUMERO_NATIONAL_EMETTEUR;
                    $bonprev->raison_sociale = PRELEVEMENT_RAISON_SOCIALE;

                    $bonprev->emetteur_code_etablissement = PRELEVEMENT_CODE_BANQUE;
                    $bonprev->emetteur_code_guichet       = PRELEVEMENT_CODE_GUICHET;
                    $bonprev->emetteur_numero_compte      = PRELEVEMENT_NUMERO_COMPTE;


                    $bonprev->factures = $factures_prev_id;

                    $bonprev->generate();
                }
                dolibarr_syslog( $filebonprev ) ;
                dolibarr_syslog("Fin prelevement");
            }

            /*
             * Mise  jour du total
             *
             */

            $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
            $sql .= " SET amount = ".ereg_replace(",",".",$bonprev->total);
            $sql .= " WHERE rowid = ".$prev_id;

            $resql=$this->db->query($sql);
            if (! $resql)
            {
                $error++;
                dolibarr_syslog("Erreur mise  jour du total - $sql");
            }

            /*
             * Rollback ou Commit
             *
             */
            if (!$error)
            {
                $this->db->commit();
                dolibarr_syslog("COMMIT");
            }
            else
            {
                $this->db->rollback();
                dolibarr_syslog("ROLLBACK");
            }
        }
    }