Beispiel #1
0
 /**
  *    Create payment of invoices into database.
  *    Use this->amounts to have list of invoices for the payment.
  *    For payment of a customer invoice, amounts are postive, for payment of credit note, amounts are negative
  *
  *    @param	User	$user                	Object user
  *    @param    int		$closepaidinvoices   	1=Also close payed invoices to paid, 0=Do nothing more
  *    @return   int                 			id of created payment, < 0 if error
  */
 function create($user, $closepaidinvoices = 0)
 {
     global $conf, $langs;
     $error = 0;
     $now = dol_now();
     // Clean parameters
     $totalamount = 0;
     $atleastonepaymentnotnull = 0;
     foreach ($this->amounts as $key => $value) {
         $newvalue = price2num($value, 'MT');
         $this->amounts[$key] = $newvalue;
         $totalamount += $newvalue;
         if (!empty($newvalue)) {
             $atleastonepaymentnotnull++;
         }
     }
     $totalamount = price2num($totalamount);
     // Check parameters
     if (empty($totalamount) && empty($atleastonepaymentnotnull)) {
         $this->error = 'TotalAmountEmpty';
         return -1;
     }
     $this->db->begin();
     $ref = $this->getNextNumRef('');
     $sql = "INSERT INTO " . MAIN_DB_PREFIX . "paiement (entity, ref, datec, datep, amount, fk_paiement, num_paiement, note, fk_user_creat)";
     $sql .= " VALUES (" . $conf->entity . ", '" . $ref . "', '" . $this->db->idate($now) . "', '" . $this->db->idate($this->datepaye) . "', '" . $totalamount . "', " . $this->paiementid . ", '" . $this->num_paiement . "', '" . $this->db->escape($this->note) . "', " . $user->id . ")";
     dol_syslog(get_class($this) . "::Create insert paiement", LOG_DEBUG);
     $resql = $this->db->query($sql);
     if ($resql) {
         $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . 'paiement');
         // Insert links amount / invoices
         foreach ($this->amounts as $key => $amount) {
             $facid = $key;
             if (is_numeric($amount) && $amount != 0) {
                 $amount = price2num($amount);
                 $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . 'paiement_facture (fk_facture, fk_paiement, amount)';
                 $sql .= ' VALUES (' . $facid . ', ' . $this->id . ', \'' . $amount . '\')';
                 dol_syslog(get_class($this) . '::Create Amount line ' . $key . ' insert paiement_facture', LOG_DEBUG);
                 $resql = $this->db->query($sql);
                 if ($resql) {
                     // If we want to closed payed invoices
                     if ($closepaidinvoices) {
                         $invoice = new Facture($this->db);
                         $invoice->fetch($facid);
                         $paiement = $invoice->getSommePaiement();
                         $creditnotes = $invoice->getSumCreditNotesUsed();
                         $deposits = $invoice->getSumDepositsUsed();
                         $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
                         $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
                         //var_dump($invoice->total_ttc.' - '.$paiement.' -'.$creditnotes.' - '.$deposits.' - '.$remaintopay);exit;
                         // If there is withdrawals request to do and not done yet, we wait before closing.
                         $mustwait = 0;
                         $listofpayments = $invoice->getListOfPayments();
                         foreach ($listofpayments as $paym) {
                             // This payment might be this one or a previous one
                             if ($paym['type'] == 'PRE') {
                                 if (!empty($conf->prelevement->enabled)) {
                                     // TODO Check if this payment has a withdraw request
                                     // if not, $mustwait++;      // This will disable automatic close on invoice to allow to process
                                 }
                             }
                         }
                         //Invoice types that are eligible for changing status to paid
                         $affected_types = array(Facture::TYPE_STANDARD, Facture::TYPE_REPLACEMENT, Facture::TYPE_CREDIT_NOTE, Facture::TYPE_DEPOSIT, Facture::TYPE_SITUATION);
                         if (!in_array($invoice->type, $affected_types)) {
                             dol_syslog("Invoice " . $facid . " is not a standard, nor replacement invoice, nor credit note, nor deposit invoice, nor situation invoice. We do nothing more.");
                         } else {
                             if ($remaintopay) {
                                 dol_syslog("Remain to pay for invoice " . $facid . " not null. We do nothing more.");
                             } else {
                                 if ($mustwait) {
                                     dol_syslog("There is " . $mustwait . " differed payment to process, we do nothing more.");
                                 } else {
                                     $result = $invoice->set_paid($user, '', '');
                                     if ($result < 0) {
                                         $this->error = $invoice->error;
                                         $error++;
                                     }
                                 }
                             }
                         }
                     }
                 } else {
                     $this->error = $this->db->lasterror();
                     $error++;
                 }
             } else {
                 dol_syslog(get_class($this) . '::Create Amount line ' . $key . ' not a number. We discard it.');
             }
         }
         if (!$error) {
             // Appel des triggers
             $result = $this->call_trigger('PAYMENT_CUSTOMER_CREATE', $user);
             if ($result < 0) {
                 $error++;
             }
             // Fin appel triggers
         }
     } else {
         $this->error = $this->db->lasterror();
         $error++;
     }
     if (!$error) {
         $this->amount = $totalamount;
         $this->total = $totalamount;
         // deprecated
         $this->db->commit();
         return $this->id;
     } else {
         $this->db->rollback();
         return -1;
     }
 }
         setEventMessages($paiement->error, $paiement->errors, 'errors');
         $error++;
     }
 }
 if (!$error) {
     // Update fk_bank into subscription table
     $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'cotisation SET fk_bank=' . $bank_line_id;
     $sql .= ' WHERE rowid=' . $crowid;
     $result = $db->query($sql);
     if (!$result) {
         $error++;
     }
 }
 if (!$error) {
     // Set invoice as paid
     $invoice->set_paid($user);
 }
 if (!$error) {
     // Define output language
     $outputlangs = $langs;
     $newlang = '';
     if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) {
         $newlang = $_REQUEST['lang_id'];
     }
     if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
         $newlang = $customer->default_lang;
     }
     if (!empty($newlang)) {
         $outputlangs = new Translate("", $conf);
         $outputlangs->setDefaultLang($newlang);
     }
Beispiel #3
0
         $payment->note = $langs->trans("Payment") . ' ' . $langs->trans("Invoice") . ' ' . $obj_facturation->numInvoice();
         $payment->paiementid = $invoice->mode_reglement_id;
         $payment->num_paiement = '';
         $paiement_id = $payment->create($user);
         if ($paiement_id > 0) {
             if (!$error) {
                 $result = $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccountid, '', '');
                 if (!$result > 0) {
                     $errmsg = $paiement->error;
                     $error++;
                 }
             }
             if (!$error) {
                 if ($invoice->total_ttc == $obj_facturation->prixTotalTtc() && $obj_facturation->getSetPaymentMode() != 'DIFF') {
                     // We set status to payed
                     $result = $invoice->set_paid($user);
                     //print 'eeeee';exit;
                 }
             }
         } else {
             $error++;
         }
     } else {
         $error++;
     }
 }
 if (!$error) {
     $db->commit();
     $redirection = 'affIndex.php?menu=validation_ok&facid=' . $id;
     // Ajout de l'id de la facture, pour l'inclure dans un lien pointant directement vers celle-ci dans Dolibarr
 } else {
 /**
  *
  * Add facture Payment
  *
  * @param array $aryTicket	Ticket data array
  */
 private function addPaymentFac($aryTicket)
 {
     global $db, $langs, $conf;
     require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
     $now = dol_now();
     $userstatic = new User($db);
     $error = 0;
     if (!$aryTicket['employeeId']) {
         $employee = $_SESSION['uid'];
     } else {
         $employee = $aryTicket['employeeId'];
     }
     $userstatic->fetch($employee);
     $max_ite = 3;
     if ($aryTicket['convertDis']) {
         require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
         $object = new Facture($db);
         $object->fetch($aryTicket['id']);
         $object->fetch_thirdparty();
         // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
         $discountcheck = new DiscountAbsolute($db);
         $result = $discountcheck->fetch(0, $object->id);
         $canconvert = 0;
         if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->paye == 0 && empty($discountcheck->id)) {
             $canconvert = 1;
         }
         // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
         if ($canconvert) {
             $db->begin();
             // Boucle sur chaque taux de tva
             $i = 0;
             foreach ($object->lines as $line) {
                 $amount_ht[$line->tva_tx] += $line->total_ht;
                 $amount_tva[$line->tva_tx] += $line->total_tva;
                 $amount_ttc[$line->tva_tx] += $line->total_ttc;
                 $i++;
             }
             // Insert one discount by VAT rate category
             $discount = new DiscountAbsolute($db);
             if ($object->type == Facture::TYPE_CREDIT_NOTE) {
                 $discount->description = $langs->trans('DiscountOf', $object->ref);
             }
             $discount->tva_tx = abs($object->total_ttc);
             $discount->fk_soc = $object->socid;
             $discount->fk_facture_source = $object->id;
             $error = 0;
             foreach ($amount_ht as $tva_tx => $xxx) {
                 $discount->amount_ht = abs($amount_ht[$tva_tx]);
                 $discount->amount_tva = abs($amount_tva[$tva_tx]);
                 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
                 $discount->tva_tx = abs($tva_tx);
                 $paiement_id = $discount->create($userstatic);
                 if ($paiement_id < 0) {
                     $error++;
                     break;
                 }
             }
             if (empty($error)) {
                 // Classe facture
                 $paiement_id = $object->set_paid($user);
                 if ($result >= 0) {
                     //$mesgs[]='OK'.$discount->id;
                     $db->commit();
                 } else {
                     $db->rollback();
                 }
             } else {
                 $db->rollback();
             }
         }
     } else {
         if ($aryTicket['type'] == 1) {
             if ($aryTicket['total'] > $aryTicket['customerpay'] && $aryTicket['difpayment'] == 0) {
                 dol_include_once('/rewards/class/rewards.class.php');
                 $reward = new Rewards($db);
                 $facture = new Facture($db);
                 $facture->fetch($aryTicket['id']);
                 $modepay[4] = dol_getIdFromCode($db, 'PNT', 'c_paiement');
                 $amount[4] = $aryTicket['total'] - $aryTicket['customerpay'];
                 $result = $reward->create($facture, price2num($amount[4]) / $conf->global->REWARDS_DISCOUNT);
                 $max_ite++;
                 $amount[4] = $amount[4] * -1;
                 //TODO tot molt bonico, pero que pasa si no gaste punts?
             }
             $aryTicket['total'] = $aryTicket['total'] * -1;
             $aryTicket['customerpay1'] = $aryTicket['customerpay1'] * -1;
             $aryTicket['customerpay2'] = $aryTicket['customerpay2'] * -1;
             $aryTicket['customerpay3'] = $aryTicket['customerpay3'] * -1;
         }
         $cash = new Cash($db);
         $terminal = $_SESSION['TERMINAL_ID'];
         $cash->fetch($terminal);
         if ($aryTicket['customerpay1'] != 0) {
             $bankaccountid[1] = $cash->fk_paycash;
             $modepay[1] = $cash->fk_modepaycash;
             $amount[1] = $aryTicket['customerpay1'] + ($aryTicket['difpayment'] < 0 ? $aryTicket['difpayment'] : 0);
         }
         if ($aryTicket['customerpay2'] != 0) {
             $bankaccountid[2] = $cash->fk_paybank;
             $modepay[2] = $cash->fk_modepaybank;
             $amount[2] = $aryTicket['customerpay2'];
         }
         if ($aryTicket['customerpay3'] != 0) {
             $bankaccountid[3] = $cash->fk_paybank_extra;
             $modepay[3] = $cash->fk_modepaybank_extra;
             $amount[3] = $aryTicket['customerpay3'];
         }
         //Añadir el posible pago de puntos
         if ($aryTicket['points'] > 0) {
             dol_include_once('/rewards/class/rewards.class.php');
             $reward = new Rewards($db);
             $facture = new Facture($db);
             $facture->fetch($aryTicket['id']);
             $res = $reward->usePoints($facture, $aryTicket['points']);
         }
         $i = 1;
         $payment = new Paiement($db);
         while ($i <= $max_ite) {
             $payment->datepaye = $now;
             $payment->bank_account = $bankaccountid[$i];
             $payment->amounts[$aryTicket['id']] = $amount[$i];
             $payment->note = $langs->trans("Payment") . ' ' . $langs->trans("Facture") . ' ' . $aryTicket['ref'];
             $payment->paiementid = $modepay[$i];
             $payment->num_paiement = '';
             if ($amount[$i] != 0) {
                 $paiement_id = $payment->create($userstatic, 1);
                 if ($paiement_id > 0) {
                     if ($payment->paiementid != dol_getIdFromCode($db, 'PNT', 'c_paiement')) {
                         $result = $payment->addPaymentToBank($userstatic, 'payment', '(CustomerFacturePayment)', $bankaccountid[$i], $aryTicket['customerId'], '', '');
                         if ($result < 0) {
                             $error++;
                         }
                     }
                 } else {
                     $error++;
                 }
             }
             $i++;
         }
     }
     if ($error > 0) {
         return -1;
     } else {
         return 1;
     }
     //$paiement_id;
 }
 /**
  *	Set withdrawal to credited status
  *
  *	@param	User		$user		id of user
  *	@param 	timestamp	$date		date of action
  *	@return	int						>0 if OK, <0 if KO
  */
 function set_infocredit($user, $date)
 {
     global $conf, $langs;
     $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 entity = " . $conf->entity;
                 $sql .= " AND statut = 1";
                 if ($this->db->query($sql)) {
                     $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();
                     $facs = $this->getListInvoices(1);
                     $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];
                         $result = $fac->set_paid($user);
                     }
                     $paiement = new Paiement($this->db);
                     $paiement->datepaye = $date;
                     $paiement->amounts = $amounts;
                     $paiement->paiementid = 3;
                     //
                     $paiement->num_paiement = $this->ref;
                     $paiement_id = $paiement->create($user);
                     if ($paiement_id < 0) {
                         dol_syslog(get_class($this) . "::set_credite AddPayment Error");
                         $error++;
                     } else {
                         $result = $paiement->addPaymentToBank($user, 'payment', '(WithdrawalPayment)', $bankaccount, '', '');
                         if ($result < 0) {
                             dol_syslog(get_class($this) . "::set_credite AddPaymentToBank Error");
                             $error++;
                         }
                     }
                     // Update prelevement line
                     // 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_credite Update lines Error");
                         $error++;
                     }
                 } else {
                     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;
     }
 }
function _createAvoir(&$PDOdb, &$db, &$user, &$conf, &$langs)
{
    dol_include_once('/compta/facture/class/facture.class.php');
    dol_include_once('/core/class/discount.class.php');
    $sql = _getSql2();
    $PDOdb->Execute($sql);
    $TFacnumberFetchError = array();
    $TFacnumberCreateError = array();
    $TDiscountCreateError = array();
    $nbValidate = 0;
    while ($row = $PDOdb->Get_line()) {
        $fk_soc = $row->fk_soc;
        $facnumber = $row->facnumber;
        $factureImpayee = new Facture($db);
        if ($factureImpayee->fetch(null, $facnumber) <= 0) {
            $TFacnumberFetchError[] = $facnumber;
            continue;
        }
        $dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
        $facture = new Facture($db);
        $facture->socid = $fk_soc;
        $facture->fk_facture_source = $factureImpayee->id;
        $facture->type = Facture::TYPE_CREDIT_NOTE;
        $facture->date = $dateinvoice;
        if ($facture->create($user) <= 0) {
            $TFacnumberCreateError[] = $facnumber;
            continue;
        }
        foreach ($factureImpayee->lines as $line) {
            $line->fk_facture = $facture->id;
            $line->subprice = -$line->subprice;
            // invert price for object
            $line->pa_ht = -$line->pa_ht;
            $line->total_ht = -$line->total_ht;
            $line->total_tva = -$line->total_tva;
            $line->total_ttc = -$line->total_ttc;
            $line->total_localtax1 = -$line->total_localtax1;
            $line->total_localtax2 = -$line->total_localtax2;
            $line->insert();
            $facture->lines[] = $line;
            // insert new line in current object
        }
        $facture->update_price(1);
        $facture->validate($user);
        $discountcheck = new DiscountAbsolute($db);
        $result = $discountcheck->fetch(0, $facture->id);
        if (!empty($discountcheck->id)) {
            //can't convert
            $facture->delete();
            continue;
        }
        $i = 0;
        $amount_ht = $amount_tva = $amount_ttc = array();
        foreach ($facture->lines as $line) {
            if ($line->total_ht != 0) {
                // no need to create discount if amount is null
                $amount_ht[$line->tva_tx] += $line->total_ht;
                $amount_tva[$line->tva_tx] += $line->total_tva;
                $amount_ttc[$line->tva_tx] += $line->total_ttc;
                $i++;
            }
        }
        // Insert one discount by VAT rate category
        $discount = new DiscountAbsolute($db);
        $discount->description = '(CREDIT_NOTE)';
        $discount->tva_tx = abs($facture->total_ttc);
        $discount->fk_soc = $facture->socid;
        $discount->fk_facture_source = $facture->id;
        foreach ($amount_ht as $tva_tx => $xxx) {
            $discount->amount_ht = abs($amount_ht[$tva_tx]);
            $discount->amount_tva = abs($amount_tva[$tva_tx]);
            $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
            $discount->tva_tx = abs($tva_tx);
            $result = $discount->create($user);
            if ($result < 0) {
                $TDiscountCreateError[] = $facnumber;
                $error++;
                break;
            }
            $result = $facture->set_paid($user);
            $result = $discount->link_to_invoice(0, $factureImpayee->id);
            $r = $factureImpayee->set_paid($user);
        }
        /******/
        $nbValidate++;
    }
    if ($nbValidate) {
        setEventMessages($langs->trans('sendinvoicetoadherentAvoirValidate', $nbValidate), null);
    }
    if (count($TFacnumberFetchError) > 0) {
        setEventMessages($langs->trans('sendinvoicetoadherentErrorFetchFacture', count($TFacnumberFetchError)), null, 'errors');
    }
    if (count($TFacnumberCreateError) > 0) {
        setEventMessages($langs->trans('sendinvoicetoadherentErrorCreateAvoir', count($TFacnumberCreateError)), null, 'errors');
    }
    $_SESSION['SENDTOINVOICETOADHERENT_TFETCHERROR'] = $TFacnumberFetchError;
    $_SESSION['SENDTOINVOICETOADHERENT_TCREATEERROR'] = $TFacnumberCreateError;
    header('Location: ' . dol_buildpath('/sendinvoicetoadherent/sendinvoicetoadherent.php?action=listAvoir', 2));
    exit;
}
Beispiel #7
0
	/**
	 *    Create payment of invoices into database.
	 *    Use this->amounts to have list of invoices for the payment
	 *    @param       user                object user
	 *    @param       closepaidinvoices   1=Also close payed invoices to paid, 0=Do nothing more
	 *    @return      int                 id of created payment, < 0 if error
	 */
	function create($user,$closepaidinvoices=0)
	{
		global $langs,$conf;

		$error = 0;

        $now=dol_now();

        // Clean parameters
        $totalamount = 0;
		foreach ($this->amounts as $key => $value)	// How payment is dispatch
		{
			$newvalue = price2num($value,'MT');
			$this->amounts[$key] = $newvalue;
			$totalamount += $newvalue;
		}
		$totalamount = price2num($totalamount);

		// Check parameters
        if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null


		$this->db->begin();

		$sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (datec, datep, amount, fk_paiement, num_paiement, note, fk_user_creat)";
		$sql.= " VALUES ('".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$totalamount."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($this->note)."', ".$user->id.")";

		dol_syslog(get_class($this)."::Create insert paiement sql=".$sql);
		$resql = $this->db->query($sql);
		if ($resql)
		{
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiement');

			// Insert links amount / invoices
			foreach ($this->amounts as $key => $amount)
			{
				$facid = $key;
				if (is_numeric($amount) && $amount <> 0)
				{
					$amount = price2num($amount);
					$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiement_facture (fk_facture, fk_paiement, amount)';
					$sql .= ' VALUES ('.$facid.', '. $this->id.', \''.$amount.'\')';

					dol_syslog(get_class($this).'::Create Amount line '.$key.' insert paiement_facture sql='.$sql);
					$resql=$this->db->query($sql);
					if ($resql)
					{
						// If we want to closed payed invoices
					    if ($closepaidinvoices)
					    {
					        $invoice=new Facture($this->db);
					        $invoice->fetch($facid);
                            $paiement = $invoice->getSommePaiement();
                            $creditnotes=$invoice->getSumCreditNotesUsed();
                            $deposits=$invoice->getSumDepositsUsed();
                            $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
                            $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
                            // If there is withdrawals request to do and not done yet, we wait before closing.
                            $mustwait=0;
                            $listofpayments=$invoice->getListOfPayments();
                            foreach($listofpayments as $paym)
                            {
                                // This payment might be this one or a previous one
                                if ($paym['type']=='PRE')
                                {
                                    if ($conf->prelevement->enabled)
                                    {
                                        // TODO Check if this payment has a withdraw request
                                        // if not, $mustwait++;      // This will disable automatic close on invoice to allow to process
                                    }
                                }
                            }

                            if ($invoice->type != 0 && $invoice->type != 1) dol_syslog("Invoice ".$facid." is not a standard nor replacement invoice. We do nothing more.");
                            else if ($remaintopay) dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing more.");
                            else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more.");
                            else $result=$invoice->set_paid($user,'','');
					    }
					}
					else
					{
						$this->error=$this->db->lasterror();
						dol_syslog(get_class($this).'::Create insert paiement_facture error='.$this->error, LOG_ERR);
						$error++;
					}
				}
				else
				{
					dol_syslog(get_class($this).'::Create Amount line '.$key.' not a number. We discard it.');
				}
			}

			if (! $error)
			{
				// Appel des triggers
				include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
				$interface=new Interfaces($this->db);
				$result=$interface->run_triggers('PAYMENT_CUSTOMER_CREATE',$this,$user,$langs,$conf);
				if ($result < 0) { $error++; $this->errors=$interface->errors; }
				// Fin appel triggers
			}
		}
		else
		{
			$this->error=$this->db->lasterror();
			dol_syslog(get_class($this).'::Create insert paiement error='.$this->error, LOG_ERR);
			$error++;
		}

		if (! $error)
		{
		    $this->amount=$totalamount;
		    $this->total=$totalamount;    // deprecated
			$this->db->commit();
			return $this->id;
		}
		else
		{
			$this->db->rollback();
			return -1;
		}
	}
 function create_facture()
 {
     require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
     global $db, $user, $langs;
     $langs->load('pos@pos');
     $facture = new Facture($db);
     $facture->socid = $this->socid;
     //! Objet societe client (to load with fetch_client method)
     $facture->client = $this->client;
     $facture->author = $this->author;
     $facture->fk_user_author = $this->fk_user_author;
     $facture->fk_user_valid = $this->fk_user_valid;
     //! Ticket date
     $now = dol_now();
     $facture->date = $now;
     // Ticket date
     $facture->date_creation = $now;
     // Creation date
     $facture->datem = $this->datem;
     $facture->ref = $this->ref;
     //! 0=Standard ticket, 1=Credit note ticket,2=Deposit ticket
     $facture->type = 0;
     $facture->remise_absolue = $this->remise_absolute;
     $facture->remise_percent = $this->remise_percent;
     $facture->total_ht = $this->total_ht;
     $facture->total_tva = $this->total_tva;
     $facture->total_ttc = $this->total_ttc;
     $facture->note = $this->note;
     $facture->note_public = $this->note_public;
     //! 0=draft,
     //! 1=to invoice
     //! 2=invoiced
     //! 3=No invoicable
     //! 4=return ticket
     //! 5=abandoned
     $facture->statut = $this->statut;
     //! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon
     //! Fermeture alors que aucun paiement: replaced (si remplace), abandon
     $facture->close_code = $this->close_code;
     //! Commentaire si mis a paye sans paiement complet
     $facture->close_note = $this->close_note;
     //! 1 if ticket paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code
     $facture->paye = 0;
     $facture->mode_reglement_id = $this->mode_reglement_id;
     // Id in llx_c_paiement
     $facture->mode_reglement_code = $this->mode_reglement_code;
     // Code in llx_c_paiement
     $facture->modelpdf = $this->modelpdf;
     $facture->products = $this->products;
     // TODO deprecated
     $facture->line = $this->line;
     //! Pour board
     $facture->nbtodo = $this->nbtodo;
     $facture->nbtodolate = $this->nbtodolate;
     $facture->specimen = $this->specimen;
     for ($i = 0; $i < sizeof($this->lines); $i++) {
         $factline = new FactureLigne($db);
         $factline->fk_parent_line = $this->lines[$i]->fk_parent_line;
         //! Description ligne
         $factline->desc = $this->lines[$i]->desc;
         $factline->fk_product = $this->lines[$i]->fk_product;
         // Id of predefined product
         $factline->product_type = $this->lines[$i]->product_type;
         // Type 0 = product, 1 = Service
         $factline->qty = $this->lines[$i]->qty;
         // Quantity (example 2)
         $factline->tva_tx = $this->lines[$i]->tva_tx;
         // Taux tva produit/service (example 19.6)
         $factline->localtax1_tx = $this->lines[$i]->localtax1_tx;
         // Local tax 1
         $factline->localtax2_tx = $this->lines[$i]->localtax2_tx;
         // Local tax 2
         $factline->subprice = $this->lines[$i]->subprice;
         // P.U. HT (example 100)
         $factline->remise_percent = $this->lines[$i]->remise_percent;
         // % de la remise ligne (example 20%)
         $factline->fk_remise_except = $this->lines[$i]->fk_remise_except;
         // Link to line into llx_remise_except
         $factline->rang = $this->lines[$i]->rang;
         $factline->info_bits = $this->lines[$i]->info_bits;
         // Liste d'options cumulables:
         // Bit 0:	0 si TVA normal - 1 si TVA NPR
         // Bit 1:	0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
         $factline->special_code = $this->lines[$i]->special_code;
         // Liste d'options non cumulabels:
         // 1: frais de port
         // 2: ecotaxe
         // 3: ??
         $factline->origin = $this->lines[$i]->origin;
         $factline->origin_id = $this->lines[$i]->origin_id;
         //! Total HT  de la ligne toute quantite et incluant la remise ligne
         $factline->total_ht = $this->lines[$i]->total_ht;
         //! Total TVA  de la ligne toute quantite et incluant la remise ligne
         $factline->total_tva = $this->lines[$i]->total_tva;
         $factline->total_localtax1 = $this->lines[$i]->total_localtax1;
         //Total Local tax 1 de la ligne
         $factline->total_localtax2 = $this->lines[$i]->total_localtax2;
         //Total Local tax 2 de la ligne
         //! Total TTC de la ligne toute quantite et incluant la remise ligne
         $factline->total_ttc = $this->lines[$i]->total_ttc;
         $factline->fk_code_ventilation = $this->lines[$i]->fk_code_ventilation;
         $factline->fk_export_compta = $this->lines[$i]->fk_export_compta;
         $factline->date_start = $this->lines[$i]->date_start;
         $factline->date_end = $this->lines[$i]->date_end;
         // From llx_product
         $factline->ref = $this->lines[$i]->ref;
         // Product ref (deprecated)
         $factline->product_ref = $this->lines[$i]->product_ref;
         // Product ref
         $factline->libelle = $this->lines[$i]->libelle;
         // Product label (deprecated)
         $factline->product_label = $this->lines[$i]->product_label;
         // Product label
         $factline->product_desc = $this->lines[$i]->product_desc;
         // Description produit
         $factline->skip_update_total = $this->lines[$i]->skip_update_total;
         // Skip update price total for special lines
         $facture->lines[$i] = $factline;
     }
     $facture->create($user);
     if ($facture->statut == 1 || $facture->type == 1) {
         $facture->validate($user);
         if ($this->diff_payment <= 0) {
             $facture->set_paid($user);
         }
         if ($this->diff_payment > 0) {
             $facture->setStatut(1);
         }
     }
     $sql = 'UPDATE ' . MAIN_DB_PREFIX . "pos_ticket SET fk_facture='" . $facture->id . "' WHERE rowid=" . $this->id;
     dol_syslog("Ticket::update sql=" . $sql);
     $resql = $this->db->query($sql);
     if (!$resql) {
         $this->db->rollback();
         return -1;
     } else {
         $this->db->commit();
         $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . 'pos_facture (fk_cash, fk_place,fk_facture) VALUES (' . $this->fk_cash . ',' . ($this->fk_place ? $this->fk_place : 'null') . ',' . $facture->id . ')';
         dol_syslog("pos_facture::update sql=" . $sql);
         $resql = $this->db->query($sql);
         if (!$resql) {
             $this->db->rollback();
             return -1;
         } else {
             $this->db->commit();
         }
         $sql = 'SELECT fk_paiement, amount FROM ' . MAIN_DB_PREFIX . "pos_paiement_ticket WHERE fk_ticket=" . $this->id;
         $resql = $this->db->query($sql);
         if ($resql) {
             $num = $db->num_rows($resql);
             $i = 0;
             $totalpaye = 0;
             while ($i < $num) {
                 $objp = $db->fetch_object($resql);
                 $paye[$i]['fk_paiement'] = $objp->fk_paiement;
                 $paye[$i]['amount'] = $objp->amount;
                 $i++;
             }
             $i = 0;
             while ($i < $num) {
                 $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . 'paiement_facture (fk_paiement, fk_facture, amount) VALUES (' . $paye[$i]['fk_paiement'] . ',' . $facture->id . ',' . $paye[$i]['amount'] . ')';
                 $resql = $this->db->query($sql);
                 $i++;
             }
         } else {
             return -1;
         }
         $facture->add_object_linked('ticket', $this->id);
         return $facture->id;
     }
 }