Skip to content
Snippets Groups Projects
bonprelevement.class.php 64.2 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>
 * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@capnetworks.com>
 * Copyright (C) 2010-2015 Juanjo Menent        <jmenent@2byte.es>
 * Copyright (C) 2010-2014 Laurent Destailleur  <eldy@users.sourceforge.net>
 * Copyright (C) 2014-2016 Ferran Marcet       <fmarcet@2byte.es>
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 3 of the License, or
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
/**
 *      \file       htdocs/compta/prelevement/class/bonprelevement.class.php
 *      \ingroup    prelevement
 *      \brief      File of withdrawal receipts class
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed

require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed

Laurent Destailleur's avatar
Laurent Destailleur committed
 *	Class to manage withdrawal receipts
 */
class BonPrelevement extends CommonObject
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
{
	public $element='widthdraw';
	public $table_element='prelevement_bons';
	public $picto = 'payment';

    var $date_echeance;
    var $raison_sociale;
    var $reference_remise;
    var $emetteur_code_guichet;
    var $emetteur_numero_compte;
    var $emetteur_code_banque;
    var $emetteur_number_key;

    var $emetteur_iban;
    var $emetteur_bic;
    var $emetteur_ics;

    var $statut;    // 0-Wait, 1-Trans, 2-Done
    var $labelstatut=array();
    var $invoice_in_error=array();
    /**
     *	Constructor
     *
Laurent Destailleur's avatar
Laurent Destailleur committed
     *  @param		DoliDB		$db      	Database handler
     *  @param		string		$filename	Filename of withdraw receipt
     */
    function __construct($db, $filename='')
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
    {
        global $conf,$langs;
Laurent Destailleur's avatar
Laurent Destailleur committed
        $this->db = $db;
        $this->date_echeance = time();
        $this->raison_sociale = "";
        $this->reference_remise = "";
        $this->emetteur_code_guichet = "";
        $this->emetteur_numero_compte = "";
        $this->emetteur_code_banque = "";
        $this->emetteur_number_key = "";
        $this->emetteur_iban = "";
        $this->emetteur_bic = "";
        $this->emetteur_ics = "";

        $this->methodes_trans = array();
        $this->methodes_trans[0] = "Internet";
        $langs->load("withdrawals");
        $this->labelstatut[0]=$langs->trans("StatusWaiting");
        $this->labelstatut[1]=$langs->trans("StatusTrans");
        $this->labelstatut[2]=$langs->trans("StatusCredited");
Rodolphe Quiedeville's avatar
Rodolphe Quiedeville committed
    }
     * Add invoice to withdrawal
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     * @param	int		$facture_id 	id invoice to add
     * @param	int		$client_id  	id invoice customer
     * @param	string	$client_nom 	customer name
     * @param	int		$amount 		amount of invoice
     * @param	string	$code_banque 	code of bank withdrawal
     * @param	string	$code_guichet 	code of bank's office
     * @param	string	$number bank 	account number
     * @param	string	$number_key 	number key of account number
     * @return	int						>0 if OK, <0 if KO
    function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
Regis Houssin's avatar
Regis Houssin committed
        $line_id = 0;
        $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key);
Regis Houssin's avatar
Regis Houssin committed
            if ($line_id > 0)
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture (";
                $sql.= "fk_facture";
                $sql.= ",fk_prelevement_lignes";
                $sql.= ") VALUES (";
                $sql.= $facture_id;
Regis Houssin's avatar
Regis Houssin committed
                $sql.= ", ".$line_id;

                if ($this->db->query($sql))
                {
                    $result = 0;
                }
                else
                {
                    $result = -1;
                    dol_syslog(get_class($this)."::AddFacture Erreur $result");
                dol_syslog(get_class($this)."::AddFacture Erreur $result");
            dol_syslog(get_class($this)."::AddFacture Erreur $result");
     *	Add line to withdrawal
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
Laurent Destailleur's avatar
Laurent Destailleur committed
     *	@param	int		$line_id 		id line to add
Laurent Destailleur's avatar
Laurent Destailleur committed
     *	@param	int		$client_id  	id invoice customer
     *	@param	string	$client_nom 	customer name
Laurent Destailleur's avatar
Laurent Destailleur committed
     *	@param	int		$amount 		amount of invoice
     *	@param	string	$code_banque 	code of bank withdrawal
     *	@param	string	$code_guichet 	code of bank's office
     *	@param	string	$number 		bank account number
     *	@param  string	$number_key 	number key of account number
     *	@return	int						>0 if OK, <0 if KO
    function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
             * We aggregate the lines
            $sql = "SELECT rowid";
            $sql.= " 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."'";
            $resql=$this->db->query($sql);
            if ($resql)
                $num = $this->db->num_rows($resql);
             * No aggregate
            $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes (";
            $sql.= "fk_prelevement_bons";
            $sql.= ", fk_soc";
            $sql.= ", client_nom";
            $sql.= ", amount";
            $sql.= ", code_banque";
            $sql.= ", code_guichet";
            $sql.= ", number";
            $sql.= ") VALUES (";
            $sql.= $this->id;
            $sql.= ", ".$client_id;
            $sql.= ", '".$this->db->escape($client_nom)."'";
            $sql.= ", '".price2num($amount)."'";
            $sql.= ", '".$code_banque."'";
            $sql.= ", '".$code_guichet."'";
            $sql.= ", '".$number."'";
            $sql.= ", '".$number_key."'";
Regis Houssin's avatar
Regis Houssin committed
                $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes");
                dol_syslog(get_class($this)."::addline Error -2");
     *	Return error string
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     *  @param	int		$error 		 Id of error
     *	@return	string               Error string
    function getErrorString($error)
        $errors[1027] = $langs->trans("DateInvalid");
    /**
     *	Get object and lines from database
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     *	@param	int		$rowid		Id of object to load
     *  @param	string	$ref		Ref of direct debit
Laurent Destailleur's avatar
Laurent Destailleur committed
     *	@return	int					>0 if OK, <0 if KO
    function fetch($rowid, $ref='')
        global $conf;
Laurent Destailleur's avatar
Laurent Destailleur committed

        $sql = "SELECT p.rowid, p.ref, p.amount, p.note";
Laurent Destailleur's avatar
Laurent Destailleur committed
        $sql.= ", p.datec as dc";
        $sql.= ", p.date_trans as date_trans";
        $sql.= ", p.method_trans, p.fk_user_trans";
Laurent Destailleur's avatar
Laurent Destailleur committed
        $sql.= ", p.date_credit as date_credit";
        $sql.= ", p.fk_user_credit";
        $sql.= ", p.statut";
        $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
        $sql.= " WHERE p.entity = ".$conf->entity;
        if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid;
        else $sql.= " AND p.ref = '".$this->db->escape($ref)."'";
        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
        $result=$this->db->query($sql);
        if ($result)
        {
            if ($this->db->num_rows($result))
            {
                $obj = $this->db->fetch_object($result);

                $this->id                 = $obj->rowid;
                $this->ref                = $obj->ref;
                $this->amount             = $obj->amount;
Laurent Destailleur's avatar
Laurent Destailleur committed
                $this->note               = $obj->note;
                $this->datec              = $this->db->jdate($obj->dc);
Laurent Destailleur's avatar
Laurent Destailleur committed
                $this->date_trans         = $this->db->jdate($obj->date_trans);
                $this->method_trans       = $obj->method_trans;
                $this->user_trans         = $obj->fk_user_trans;

Laurent Destailleur's avatar
Laurent Destailleur committed
                $this->date_credit        = $this->db->jdate($obj->date_credit);
                $this->user_credit        = $obj->fk_user_credit;

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

                $this->_fetched = 1;

                return 0;
            }
            else
            {
                dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee");
     * Set credite and set status of linked invoices. Still used ??
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     * @return		int		<0 if KO, >=0 if OK
        global $user,$conf;
            $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
            $sql.= " SET statut = 1";
            $sql.= " WHERE rowid = ".$this->id;
            $sql.= " AND entity = ".$conf->entity;

            $result=$this->db->query($sql);
            if (! $result)
            {
                dol_syslog(get_class($this)."::set_credite Erreur 1");
Laurent Destailleur's avatar
Laurent Destailleur committed
                $facs = $this->getListInvoices();
Laurent Destailleur's avatar
Laurent Destailleur committed

                $num=count($facs);
                for ($i = 0; $i < $num; $i++)
                    /* Tag invoice as payed */
                    dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]);
                    $result = $fac->set_paid($user);
                $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
                $sql.= " SET statut = 2";
                $sql.= " WHERE fk_prelevement_bons = ".$this->id;
                    dol_syslog(get_class($this)."::set_credite Erreur 1");
             * End of procedure
            {
                $this->db->commit();
                return 0;
            }
            else
            {
                $this->db->rollback();
                dol_syslog(get_class($this)."::set_credite ROLLBACK ");
            dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible ");
     *	Set direct debit order to "credited" status.
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     *	@param	User	$user			Id of user
     *	@param 	int		$date			date of action
Laurent Destailleur's avatar
Laurent Destailleur committed
     *	@return	int						>0 if OK, <0 if KO
    function set_infocredit($user, $date)
    {
        global $conf,$langs;
Laurent Destailleur's avatar
Laurent Destailleur committed


        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 entity = ".$conf->entity;
                    $sql.= " AND statut = 1";
                        $langs->load('withdrawals');
                        $subject = $langs->trans("InfoCreditSubject", $this->ref);
                        $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour'));
                        //Add payment of withdrawal into bank
                        $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT;
                        $facs = array();
                        $amounts = array();
                        // Loop on each invoice. $facs=array(0=>id, 1=>amount requested)
                        $num=count($facs);
                        for ($i = 0; $i < $num; $i++)
                        {
                            $fac = new Facture($this->db);
                            $fac->fetch($facs[$i][0]);
                            $amounts[$fac->id] = $facs[$i][1];
                            $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1];
							$totalpaye  = $fac->getSommePaiement();
							$totalcreditnotes = $fac->getSumCreditNotesUsed();
							$totaldeposits = $fac->getSumDepositsUsed();
							$alreadypayed = $totalpaye + $totalcreditnotes + $totaldeposits;
							if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) {
								$result = $fac->set_paid($user);
							}
                        // Make one payment per customer
                        foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts)
	                        $paiement = new Paiement($this->db);
	                        $paiement->datepaye     = $date;
	                        $paiement->amounts      = $cursoramounts;		// Array with detail of dispatching of payments for each invoice
	                        $paiement->paiementid   = 3; 					//
	                        $paiement->num_paiement = $this->ref;			// Set ref of direct debit note
							$paiement->id_prelevement = $this->id;

	                        $paiement_id = $paiement->create($user);
	                        if ($paiement_id < 0)
	                        {
	                            dol_syslog(get_class($this)."::set_infocredit AddPayment Error");
	                            $error++;
	                        }
	                        else
	                        {
	                            $result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'','');
	                            if ($result < 0)
	                            {
	                                dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error");
	                                $error++;
	                            }
	                        }
	                        //var_dump($paiement->amounts);
	                        //var_dump($thirdpartyid);
	                        //var_dump($cursoramounts);
                        // TODO: Translate to ligneprelevement.class.php
                        $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
                        $sql.= " SET statut = 2";
                        $sql.= " WHERE fk_prelevement_bons = ".$this->id;

                        if (! $this->db->query($sql))
                        {
                            dol_syslog(get_class($this)."::set_infocredit Update lines Error");
                        dol_syslog(get_class($this)."::set_infocredit Update Bons Error");
                        $error++;
                    }

                    /*
                     * End of procedure
                    if ($error == 0)
                    {
                        $this->db->commit();
                        return 0;
                    }
                    else
                    {
                        $this->db->rollback();
                        dol_syslog("bon-prelevment::set_infocredit ROLLBACK ");
                        return -1;
                    }
                }
                else
                {
                    dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible ");
                    return -1025;
                }
            }
            else
            {
                dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans ");
                return -1027;
            }
        }
        else
        {
            return -1026;
        }
    }
     *	Set withdrawal to transmited status
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     *	@param	User		$user		id of user
     *	@param 	int	$date		date of action
Laurent Destailleur's avatar
Laurent Destailleur committed
     *	@param	string		$method		method of transmision to bank
     *	@return	int						>0 if OK, <0 if KO
    function set_infotrans($user, $date, $method)
    {
        global $conf,$langs;
Laurent Destailleur's avatar
Laurent Destailleur committed

        dol_syslog(get_class($this)."::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 entity = ".$conf->entity;
            $sql.= " AND statut = 0";

            if ($this->db->query($sql))
            {
                $this->method_trans = $method;
                $langs->load('withdrawals');
                $subject = $langs->trans("InfoTransSubject", $this->ref);
                $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname));
                $message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day'));
                // TODO Call trigger to create a notification using notification module
                $error++;
            }

            if ($error == 0)
            {
                $this->db->commit();
                return 0;
            }
            else
            {
                $this->db->rollback();
                dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR);
            dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT);
     *	Get invoice list
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
Laurent Destailleur's avatar
Laurent Destailleur committed
     *  @param 	int		$amounts 	If you want to get the amount of the order for each invoice
     *	@return	array 				Id of invoices
        global $conf;
Laurent Destailleur's avatar
Laurent Destailleur committed

         * Returns all invoices presented
         * within a withdrawal receipt
        if ($amounts) $sql .= ", SUM(pl.amount)";
        $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;
        $sql.= " AND p.entity = ".$conf->entity;
        if ($amounts) $sql.= " GROUP BY fk_facture";

        $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);
                    if (!$amounts) $arr[$i] = $row[0];
                    else
                    {
                        $arr[$i] = array(
                            $row[0],
                            $row[1]
                        );
                    }
Laurent Destailleur's avatar
Laurent Destailleur committed
            dol_syslog(get_class($this)."::getListInvoices Erreur");
     *	Returns amount of withdrawal
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     *	@return		double	 	Total amount
        global $conf;
Laurent Destailleur's avatar
Laurent Destailleur committed

        $sql = "SELECT sum(pfd.amount) as nb";
        $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,";
        $sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
        //$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp";
        $sql.= " WHERE f.fk_statut = 1";
        $sql.= " AND f.entity = ".$conf->entity;
        $sql.= " AND f.rowid = pfd.fk_facture";
        $sql.= " AND f.paye = 0";
        $sql.= " AND pfd.traite = 0";
        $sql.= " AND f.total_ttc > 0";

        $resql = $this->db->query($sql);
        if ( $resql )
        {
            $obj = $this->db->fetch_object($resql);
            dol_syslog(get_class($this)."::SommeAPrelever Erreur -1");
Juanjo Menent's avatar
Juanjo Menent committed
     *	Get number of invoices to withdrawal
     *	TODO delete params banque and agence when not necesary
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     *	@param	int		$banque		dolibarr mysoc bank
     *	@param	int		$agence		dolibarr mysoc agence
Laurent Destailleur's avatar
Laurent Destailleur committed
     *	@return	int					<O if KO, number of invoices if OK
     */
    function NbFactureAPrelever($banque=0,$agence=0)
    {
        global $conf;
Laurent Destailleur's avatar
Laurent Destailleur committed

        $sql = "SELECT count(f.rowid) as nb";
        $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
        $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
        //if ($banque || $agence) $sql.=", ".MAIN_DB_PREFIX."societe_rib as sr";
        $sql.= " WHERE f.fk_statut = 1";
        $sql.= " AND f.entity = ".$conf->entity;
        $sql.= " AND f.rowid = pfd.fk_facture";
        $sql.= " AND f.paye = 0";
        $sql.= " AND pfd.traite = 0";
        $sql.= " AND f.total_ttc > 0";
        //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid";
        //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'";
        //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'";
	    dol_syslog(get_class($this)."::SommeAPrelever");
        $resql = $this->db->query($sql);

        if ( $resql )
        {
            $obj = $this->db->fetch_object($resql);
            $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error();
Juanjo Menent's avatar
Juanjo Menent committed
     *	Create a withdraw
     *  TODO delete params banque and agence when not necesary
Laurent Destailleur's avatar
Laurent Destailleur committed
     *
     *	@param 	int		$banque		dolibarr mysoc bank
     *	@param	int		$agence		dolibarr mysoc bank office (guichet)
Laurent Destailleur's avatar
Laurent Destailleur committed
     *	@param	string	$mode		real=do action, simu=test only
     *	@return	int					<0 if KO, nbre of invoice withdrawed if OK
    function Create($banque=0, $agence=0, $mode='real')
        global $conf,$langs;
        dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence, LOG_DEBUG);
        require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php");
        require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php");
        $error = 0;

        $datetimeprev = time();

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

        $puser = new User($this->db, $conf->global->PRELEVEMENT_USER);
         */
        $factures = array();
        $factures_prev = array();
        $factures_result = array();
        $factures_prev_id=array();
        $factures_errors=array();
        {
            $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.= " FROM ".MAIN_DB_PREFIX."facture as f";
            $sql.= ", ".MAIN_DB_PREFIX."societe as s";
            $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
            //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr";
            $sql.= " WHERE f.rowid = pfd.fk_facture";
            $sql.= " AND f.entity = ".$conf->entity;
            $sql.= " AND s.rowid = f.fk_soc";
            //if ($banque || $agence) $sql.= " AND s.rowid = 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";
            //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'";
            //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'";
            dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG);
            $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;	// All fields
                dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG);
                $error++;
                dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR);
            require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
            $soc = new Societe($this->db);

        	// Check RIB
            dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG);
            if (count($factures) > 0)
                foreach ($factures as $key => $fac)
                    if ($fact->fetch($fac[0]) >= 0)		// Field 0 of $fac is rowid of invoice
                        	$bac = new CompanyBankAccount($this->db);
Marcos García de La Fuente's avatar
Marcos García de La Fuente committed
                        	$bac->fetch(0,$soc->id);
                            if ($bac->verif() >= 1)
                            //if (true)
                                /* second tableau necessaire pour BonPrelevement */
								dol_syslog(__METHOD__."::Check RIB Error on default bank number RIB/IBAN for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_ERR);
                                $this->invoice_in_error[$fac[0]]="Error on default bank number RIB/IBAN for invoice ".$fact->getNomUrl(0)." for thirdparty (reported by function verif) ".$soc->getNomUrl(0);
                            dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_ERR);
                        dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_ERR);
                dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_ERR);
        // Withdraw invoices in factures_prev array
        $out=count($factures_prev)." invoices will be withdrawn.";
        //print $out."\n";
        dol_syslog($out);
        if (count($factures_prev) > 0)
        {
            if ($mode=='real')
            {
                $ok=1;
            }
            else
            {
                print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n";
            }
        }
            /*
             * We are in real mode.
             * We create withdraw receipt and build withdraw into disk
             */
            $this->db->begin();
            $now=dol_now();
				$ref = substr($year,-2).$month;
				$sql = "SELECT substring(ref from char_length(ref) - 1)";
				$sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons";
				$sql.= " WHERE ref LIKE '%".$this->db->escape($ref)."%'";
				$sql.= " AND entity = ".$conf->entity;
				$sql.= " ORDER BY ref DESC LIMIT 1";
				dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG);
				$resql = $this->db->query($sql);

				if ($resql)
				{
					$row = $this->db->fetch_row($resql);
					$ref = "T".$ref.str_pad(dol_substr("00".intval($row[0])+1,0,2),2,"0",STR_PAD_LEFT);
					$dir=$conf->prelevement->dir_output.'/receipts';
					if (! is_dir($dir)) dol_mkdir($dir);
					$this->filename = $dir.'/'.$ref.'.xml';
	                // Create withdraw receipt in database
	                $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (";
	                $sql.= " ref, entity, datec";
	                $sql.= ") VALUES (";
	                $sql.= "'".$this->db->escape($ref)."'";
	                $sql.= ", ".$conf->entity;
	                $sql.= ", '".$this->db->idate($now)."'";
	                $sql.= ")";
	                $resql = $this->db->query($sql);
	                if ($resql)
	                {
	                    $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons");
						$this->id = $prev_id;
						$this->ref = $ref;
	                    $error++;
	                    dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR);
				}
				else
				{
					$error++;
					dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR);
            if (!$error)
            {
	            /*
	             * Create withdrawal receipt in database
	             */
            	if (count($factures_prev) > 0)
                    foreach ($factures_prev as $fac)	// Add a link in database for each invoice
                    {
                        // Fetch invoice
                        $fact = new Facture($this->db);
                        $fact->fetch($fac[0]);
                        /*
                         * Add standing order
                         *
                         *
                         * $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 = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]);