Exemplo n.º 1
0
 /**
  * Create invoice object
  * 
  * @param array $request_data   Request datas
  * @return int  ID of invoice
  *
  * @url	POST invoice/
  */
 function post($request_data = NULL)
 {
     if (!DolibarrApiAccess::$user->rights->facture->creer) {
         throw new RestException(401);
     }
     // Check mandatory fields
     $result = $this->_validate($request_data);
     foreach ($request_data as $field => $value) {
         $this->invoice->{$field} = $value;
     }
     if (!array_keys($request_data, 'date')) {
         $this->invoice->date = dol_now();
     }
     if (!$this->invoice->create(DolibarrApiAccess::$user)) {
         throw new RestException(500);
     }
     return $this->invoice->id;
 }
Exemplo n.º 2
0
 /**
  *		Load an object from its id and create a new one in database
  *		@param      fromid     		Id of object to clone
  *		@param		invertdetail	Reverse sign of amounts for lines
  * 	 	@return		int				New id of clone
  */
 function createFromClone($fromid, $invertdetail = 0)
 {
     global $conf, $user, $langs;
     $error = 0;
     // Load source object
     $objFrom = new Facture($this->db);
     $objFrom->fetch($fromid);
     // Load new object
     $object = new Facture($this->db);
     $object->fetch($fromid);
     // Instantiate hooks of thirdparty module
     if (is_array($conf->hooks_modules) && !empty($conf->hooks_modules)) {
         $object->callHooks('invoicecard');
     }
     $this->db->begin();
     $object->id = 0;
     $object->statut = 0;
     // Clear fields
     $object->user_author = $user->id;
     $object->user_valid = '';
     $object->fk_facture_source = 0;
     $object->date_creation = '';
     $object->date_validation = '';
     $object->ref_client = '';
     $object->close_code = '';
     $object->close_note = '';
     $object->products = $object->lines;
     // Tant que products encore utilise
     // Loop on each line of new invoice
     foreach ($object->lines as $i => $line) {
         if (($object->lines[$i]->info_bits & 0x2) == 0x2) {
             unset($object->lines[$i]);
             unset($object->products[$i]);
             // Tant que products encore utilise
         }
     }
     // Create clone
     $result = $object->create($user);
     // Other options
     if ($result < 0) {
         $this->error = $object->error;
         $error++;
     }
     if (!$error) {
         // Hook for external modules
         if (!empty($object->hooks)) {
             foreach ($object->hooks as $hook) {
                 if (!empty($hook['modules'])) {
                     foreach ($hook['modules'] as $module) {
                         if (method_exists($module, 'createfrom')) {
                             $result = $module->createfrom($objFrom, $result, $object->element);
                             if ($result < 0) {
                                 $error++;
                             }
                         }
                     }
                 }
             }
         }
         // Appel des triggers
         include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
         $interface = new Interfaces($this->db);
         $result = $interface->run_triggers('BILL_CLONE', $object, $user, $langs, $conf);
         if ($result < 0) {
             $error++;
             $this->errors = $interface->errors;
         }
         // Fin appel triggers
     }
     // End
     if (!$error) {
         $this->db->commit();
         return $object->id;
     } else {
         $this->db->rollback();
         return -1;
     }
 }
Exemplo n.º 3
0
 /**
  * testFactureCreate
  *
  * @return int
  */
 public function testFactureRecCreate()
 {
     global $conf, $user, $langs, $db;
     $conf = $this->savconf;
     $user = $this->savuser;
     $langs = $this->savlangs;
     $db = $this->savdb;
     $localobjectinv = new Facture($this->savdb);
     $localobjectinv->initAsSpecimen();
     $localobjectinv->create($user);
     $localobject = new FactureRec($this->savdb);
     $localobject->initAsSpecimen();
     $result = $localobject->create($user, $localobjectinv->id);
     $this->assertLessThan($result, 0);
     print __METHOD__ . " result=" . $result . "\n";
     return $result;
 }
/**
 * Create an invoice
 *
 * @param	array		$authentication		Array of authentication information
 * @param	Facture		$invoice			Invoice
 * @return	array							Array result
 */
function createInvoice($authentication, $invoice)
{
    global $db, $conf, $langs;
    $now = dol_now();
    dol_syslog("Function: createInvoiceForThirdParty login=" . $authentication['login']);
    if ($authentication['entity']) {
        $conf->entity = $authentication['entity'];
    }
    // Init and check authentication
    $objectresp = array();
    $errorcode = '';
    $errorlabel = '';
    $error = 0;
    $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
    if (!$error) {
        $newobject = new Facture($db);
        $newobject->socid = $invoice['thirdparty_id'];
        $newobject->type = $invoice['type'];
        $newobject->ref_ext = $invoice['ref_ext'];
        $newobject->date = dol_stringtotime($invoice['date'], 'dayrfc');
        $newobject->note_private = $invoice['note_private'];
        $newobject->note_public = $invoice['note_public'];
        $newobject->statut = 0;
        // We start with status draft
        $newobject->fk_project = $invoice['project_id'];
        $newobject->date_creation = $now;
        // Trick because nusoap does not store data with same structure if there is one or several lines
        $arrayoflines = array();
        if (isset($invoice['lines']['line'][0])) {
            $arrayoflines = $invoice['lines']['line'];
        } else {
            $arrayoflines = $invoice['lines'];
        }
        foreach ($arrayoflines as $key => $line) {
            // $key can be 'line' or '0','1',...
            $newline = new FactureLigne($db);
            $newline->product_type = $line['type'];
            $newline->desc = $line['desc'];
            $newline->fk_product = $line['fk_product'];
            $newline->tva_tx = $line['vat_rate'];
            $newline->qty = $line['qty'];
            $newline->subprice = $line['unitprice'];
            $newline->total_ht = $line['total_net'];
            $newline->total_tva = $line['total_vat'];
            $newline->total_ttc = $line['total'];
            $newline->date_start = dol_stringtotime($line['date_start']);
            $newline->date_end = dol_stringtotime($line['date_end']);
            $newline->fk_product = $line['product_id'];
            $newobject->lines[] = $newline;
        }
        //var_dump($newobject->date_lim_reglement); exit;
        //var_dump($invoice['lines'][0]['type']);
        $db->begin();
        $result = $newobject->create($fuser, 0, dol_stringtotime($invoice['date_due'], 'dayrfc'));
        if ($result < 0) {
            $error++;
        }
        if ($invoice['status'] == 1) {
            $result = $newobject->validate($fuser);
            if ($result < 0) {
                $error++;
            }
        }
        if (!$error) {
            $db->commit();
            $objectresp = array('result' => array('result_code' => 'OK', 'result_label' => ''), 'id' => $newobject->id, 'ref' => $newobject->ref);
        } else {
            $db->rollback();
            $error++;
            $errorcode = 'KO';
            $errorlabel = $newobject->error;
        }
    }
    if ($error) {
        $objectresp = array('result' => array('result_code' => $errorcode, 'result_label' => $errorlabel));
    }
    return $objectresp;
}
Exemplo n.º 5
0
        $i++;
        $row = $db->fetch_row($resql);
        $prodids[$i] = $row[0];
    }
}
$i = 0;
$result = 0;
while ($i < GEN_NUMBER_FACTURE && $result >= 0) {
    $i++;
    $socid = rand(1, $num_socs);
    print "Invoice " . $i . " for socid " . $socid;
    $facture = new Facture($db, $socids[$socid]);
    $facture->date = time();
    $facture->cond_reglement_id = 3;
    $facture->mode_reglement_id = 3;
    $result = $facture->create($user);
    if ($result >= 0) {
        $result = $facture->validate($user);
        if ($result) {
            $nbp = rand(2, 5);
            $xnbp = 0;
            while ($xnbp < $nbp) {
                $prodid = rand(1, $num_prods);
                $product = new Product($db);
                $result = $product->fetch($prodids[$prodid]);
                $result = $facture->addline($facture->id, $product->description, $product->price, rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, '', '', 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type);
                $xnbp++;
            }
            print " OK with ref " . $facture->ref . "\n";
        } else {
            dol_print_error($db, $facture->error);
Exemplo n.º 6
0
   (at your option) any later version.

    Webfinance 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 Webfinance; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
include "../inc/main.php";
if (!is_numeric($_GET['id_facture'])) {
    $Facture = new Facture();
    $invoice = array('client_id' => $_GET['id_client'], 'rows' => array());
    $id_facture = $Facture->create($invoice);
    header("Location: edit_facture.php?id_facture=" . $id_facture);
    die;
}
$Facture = new Facture();
$facture = $Facture->getInfos($_GET['id_facture']);
list($currency, $exchange) = getCurrency($facture->id_compte);
$title = $facture->nom_client;
$roles = 'manager,employee,accounting';
include "../top.php";
include "nav.php";
?>

<script type="text/javascript" language="javascript"
  src="/js/ask_confirmation.js"></script>
Exemplo n.º 7
0
     $invoice->lines[] = $invoiceline;
 }
 $invoice->socid = $conf_fksoc;
 $invoice->date_creation = $now;
 $invoice->date = $now;
 $invoice->date_lim_reglement = 0;
 $invoice->total_ht = $obj_facturation->prixTotalHt();
 $invoice->total_tva = $obj_facturation->montantTva();
 $invoice->total_ttc = $obj_facturation->prixTotalTtc();
 $invoice->note = $note;
 $invoice->cond_reglement_id = $cond_reglement_id;
 $invoice->mode_reglement_id = $mode_reglement_id;
 //print "c=".$invoice->cond_reglement_id." m=".$invoice->mode_reglement_id; exit;
 // Si paiement differe ...
 if ($obj_facturation->getSetPaymentMode() == 'DIF') {
     $resultcreate = $invoice->create($user, 0, dol_stringtotime($obj_facturation->paiementLe()));
     if ($resultcreate > 0) {
         $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice());
     } else {
         $error++;
     }
     $id = $invoice->id;
 } else {
     $resultcreate = $invoice->create($user, 0, 0);
     if ($resultcreate > 0) {
         $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0);
         $id = $invoice->id;
         // Add the payment
         $payment = new Paiement($db);
         $payment->datepaye = $now;
         $payment->bank_account = $conf_fkaccount;
 /**
  *
  * Create facture into Database
  *
  * @param	array	$aryTicket		Ticket object
  */
 private function CreateFacture($aryTicket)
 {
     global $db, $user, $conf;
     $function = "CreateFacture";
     $idFacture = -1;
     $data = $aryTicket['data'];
     $lines = $data['lines'];
     $idTicket = $data["id"];
     if ($data['idsource'] > 0) {
         $prods_returned = self::testSourceFac($aryTicket);
         if (sizeof($prods_returned) > 0) {
             return -6;
         }
         $vater = new Facture($db);
         $vater->fetch($data['idsource']);
         $data['payment_type'] = $vater->mode_reglement_id;
     }
     $cash = new Cash($db);
     $terminal = $data['cashId'];
     $cash->fetch($terminal);
     if (!$data['customerId']) {
         $socid = $cash->fk_soc;
         $data['customerId'] = $socid;
     } else {
         $socid = $data['customerId'];
     }
     if (!$data['employeeId']) {
         $employee = $_SESSION['uid'];
     } else {
         $employee = $data['employeeId'];
     }
     if ($data['mode'] == 1) {
         $object = new Facturesim($db);
     } else {
         $object = new Facture($db);
     }
     $object->type = $data['type'] == 0 ? 0 : 2;
     $object->socid = $socid;
     $object->statut = $data['state'];
     $object->fk_cash = $terminal;
     $object->remise_percent = $data['discount_percent'];
     $object->remise_absolue = $data['discount_qty'];
     if ($data['customerpay1'] > 0) {
         $object->mode_reglement_id = $cash->fk_modepaycash;
     } else {
         if ($data['customerpay2'] > 0) {
             $object->mode_reglement_id = $cash->fk_modepaybank;
         } else {
             $object->mode_reglement_id = $cash->fk_modepaybank_extra;
         }
     }
     $object->fk_place = $data['id_place'];
     $object->note_private = $data['note'];
     $object->customer_pay = $data['customerpay'];
     if ($object->customer_pay > 0) {
         $object->diff_payment = $data['difpayment'];
     } else {
         $object->diff_payment = $data['total'];
     }
     $object->fk_facture_source = $data['idsource'];
     $employ = new User($db);
     $employ->fetch($employee);
     $employ->getrights();
     $now = dol_now();
     $object->date = $now;
     $db->begin;
     $idFacture = $object->create($employ);
     if ($object->statut == 1 || $object->type == 2) {
         $res = $object->validate($employ);
         if ($res < 0) {
             $soc = new Societe($db);
             $soc->fetch($socid);
             $num = $object->getNextNumRef($soc);
             // Validate
             $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'facture';
             $sql .= " SET facnumber='" . $num . "', fk_statut = 1, fk_user_valid = " . $employ->id . ", date_valid = '" . $db->idate($now) . "'";
             if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
                 $sql .= ', datef=' . $db->idate($now);
                 $sql .= ', date_lim_reglement=' . $db->idate($now);
             }
             $sql .= ' WHERE rowid = ' . $object->id;
             dol_syslog(get_class($this) . "::validate sql=" . $sql);
             $resql = $db->query($sql);
             $object->ref = $num;
         }
     }
     $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . 'pos_facture (fk_cash, fk_place,fk_facture,customer_pay) VALUES (' . $object->fk_cash . ',' . ($object->fk_place ? $object->fk_place : 'null') . ',' . $idFacture . ',' . $object->customer_pay . ')';
     dol_syslog("pos_facture::update sql=" . $sql);
     $resql = $db->query($sql);
     if (!$resql) {
         $this->db->rollback();
         return -1;
     }
     $data['ref'] = $object->ref;
     if ($idFacture < 0) {
         $db->rollback();
         return -1;
     } else {
         //Adding lines
         $data['id'] = $idFacture;
         //introducir descuentos
         if (!empty($data['idCoupon'])) {
             $res_dis = $object->insert_discount($data['idCoupon']);
         } else {
             $res_dis = 1;
         }
         $idLines = self::addFactureLines($lines, $idFacture, $object->type == 1 ? true : false);
         if ($idLines < 0 || $res_dis < 0) {
             $db->rollback();
             return -2;
         } else {
             //Adding Payments
             $payment = self::addPaymentFac($data);
             if ($payment < 0) {
                 $db->rollback();
                 return -3;
             }
             //Decrease stock
             $stock = self::quitSotck($lines, $object->type == 2 ? true : false);
             if ($stock) {
                 $db->rollback();
                 return -4;
             }
         }
     }
     if ($idTicket) {
         $ticket = new Ticket($db);
         $ticket->fetch($idTicket);
         $ticket->delete_ticket();
     }
     return $idFacture;
 }
Exemplo n.º 9
0
 /**
  *	Create a new invoice in database from current invoice
  *
  *	@param      User	$user    		Object user that ask creation
  *	@param		int		$invertdetail	Reverse sign of amounts for lines
  *	@return		int						<0 if KO, >0 if OK
  */
 function createFromCurrent($user, $invertdetail = 0)
 {
     global $conf;
     // Charge facture source
     $facture = new Facture($this->db);
     $facture->fk_facture_source = $this->fk_facture_source;
     $facture->type = $this->type;
     $facture->socid = $this->socid;
     $facture->date = $this->date;
     $facture->note_public = $this->note_public;
     $facture->note_private = $this->note_private;
     $facture->ref_client = $this->ref_client;
     $facture->modelpdf = $this->modelpdf;
     $facture->fk_project = $this->fk_project;
     $facture->cond_reglement_id = $this->cond_reglement_id;
     $facture->mode_reglement_id = $this->mode_reglement_id;
     $facture->remise_absolue = $this->remise_absolue;
     $facture->remise_percent = $this->remise_percent;
     $facture->origin = $this->origin;
     $facture->origin_id = $this->origin_id;
     $facture->lines = $this->lines;
     // Tableau des lignes de factures
     $facture->products = $this->lines;
     // Tant que products encore utilise
     $facture->situation_counter = $this->situation_counter;
     $facture->situation_cycle_ref = $this->situation_cycle_ref;
     $facture->situation_final = $this->situation_final;
     // Loop on each line of new invoice
     foreach ($facture->lines as $i => $line) {
         $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
         if ($invertdetail) {
             $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
             $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
             $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
             $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
             $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
             $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
         }
     }
     dol_syslog(get_class($this) . "::createFromCurrent invertdetail=" . $invertdetail . " socid=" . $this->socid . " nboflines=" . count($facture->lines));
     $facid = $facture->create($user);
     if ($facid <= 0) {
         $this->error = $facture->error;
         $this->errors = $facture->errors;
     } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
         $this->fetchObjectLinked('', '', $object->id, 'facture');
         foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
             foreach ($Tfk_object as $fk_object) {
                 $facture->add_object_linked($typeObject, $fk_object);
             }
         }
         $facture->add_object_linked('facture', $this->fk_facture_source);
     }
     return $facid;
 }
Exemplo n.º 10
0
    /**
     * testFactureRoundingCreate2
     * 
     * @return int
     * 
     * @depends	testFactureRoundingCreate1
     * Test according to page http://wiki.dolibarr.org/index.php/Draft:VAT_calculation_and_rounding#Standard_usage
     */
    public function testFactureRoundingCreate2()
    {
        global $conf,$user,$langs,$db;
        $conf=$this->savconf;
        $user=$this->savuser;
        $langs=$this->savlangs;
        $db=$this->savdb;

        $localobject=new Facture($this->savdb);
        $localobject->initAsSpecimen();
        $localobject->lines=array();
        unset($localobject->total_ht);
        unset($localobject->total_ttc);
        unset($localobject->total_vat);
        $result=$localobject->create($user);

        // Add two lines
        for ($i=0; $i<2; $i++)
        {
            $localobject->addline($result, 'Description '.$i, 1.24, 1, 10);
        }

        $newlocalobject=new Facture($this->savdb);
        $newlocalobject->fetch($result);
        //var_dump($newlocalobject);

        $this->assertEquals($newlocalobject->total_ht, 2.48);
        //$this->assertEquals($newlocalobject->total_tva, 0.25);
        //$this->assertEquals($newlocalobject->total_ttc, 2.73);
        return $result;
    }
Exemplo n.º 11
0
 function createAndSendInvoice($id_client, $prix_ht, $quantity, $description, $delivery_method)
 {
     # No invoice if amount is zero
     if ($prix_ht * $quantity <= 0) {
         return true;
     }
     $Facture = new Facture();
     $invoice = array('client_id' => $id_client, 'rows' => array());
     $id_facture = $Facture->create($invoice);
     // Get invoice payment
     $res = mysql_query("SELECT payment_method\n      FROM webfinance_invoices i\n      WHERE id_client = {$id_client}\n        AND type_doc = 'facture'\n        AND is_envoye = 1\n        AND payment_method IS NOT NULL\n        AND is_abandoned = 0\n      ORDER BY id_facture DESC\n      LIMIT 1") or die(mysql_error());
     # Default values
     $payment_method = 'unknown';
     if (mysql_num_rows($res) > 0) {
         $type_payment_res = mysql_fetch_array($res);
         $payment_method = $type_payment_res['payment_method'];
     }
     // Get id_compte
     $result = mysql_query('SELECT id_pref,value ' . 'FROM webfinance_pref ' . "WHERE type_pref='rib' " . 'LIMIT 1') or die(mysql_error());
     $cpt = mysql_fetch_object($result);
     $id_compte = $cpt->id_pref;
     // Get id_type_presta
     $result = mysql_query("SELECT id_type_presta\n                  FROM webfinance_type_presta\n                  WHERE nom = 'Support mensuel'\n                  LIMIT 1") or die(mysql_error());
     list($id_type_presta) = mysql_fetch_row($result);
     // Input facture parameters
     mysql_query("UPDATE webfinance_invoices SET\n\t\t        is_paye = 0,\n\t\t        is_envoye = 0,\n\t\t        ref_contrat = 'Support professionnel',\n\t\t        payment_method = '{$payment_method}',\n\t\t        id_compte = {$id_compte},\n\t\t        id_type_presta = {$id_type_presta}\n\t\t      WHERE id_facture = {$id_facture}") or die(mysql_error());
     // Add service rows to invoice
     $q = sprintf("INSERT INTO webfinance_invoice_rows (id_facture,description,prix_ht,qtt,ordre) " . "SELECT %d, '%s', %s, %s, if(max(ordre) is null, 1, max(ordre + 1)) " . "FROM webfinance_invoice_rows " . "WHERE id_facture=%d", $id_facture, mysql_real_escape_string($description), $prix_ht, $quantity, $id_facture);
     $result = mysql_query($q) or die(mysql_error());
     mysql_query("UPDATE webfinance_invoices SET date_generated=NULL WHERE id_facture=" . $id_facture) or die(mysql_error());
     if ($payment_method == 'direct_debit') {
         // Plan the invoice to be debited
         mysql_query("INSERT INTO direct_debit_row " . "SET invoice_id = {$id_facture}, " . "    state='todo'") or die(mysql_error());
         // Flag invoice as paid
         $Facture->setPaid($id_facture);
     }
     // Manage invoice delivery and send by email to client
     switch ($delivery_method) {
         case 'email':
             $Facture->sendByEmail($id_facture) or die("Unable to send email for invoice ID {$id_facture}");
             break;
         case 'postal':
             $send_mail_print_invoice = true;
             $attachments[] = $Facture->generatePDF($id_facture, true);
             $Facture->setSent($id_facture);
             break;
     }
     return true;
 }
Exemplo n.º 12
0
/**
 * Get list of invoices for third party
 */
function createInvoice($authentication,$invoice)
{
    global $db,$conf,$langs;

    $now=dol_now();

    dol_syslog("Function: createInvoiceForThirdParty login="******" idthirdparty=".$idthirdparty);

    if ($authentication['entity']) $conf->entity=$authentication['entity'];

    // Init and check authentication
    $objectresp=array();
    $errorcode='';$errorlabel='';
    $error=0;
    $fuser=check_authentication($authentication,$error,$errorcode,$errorlabel);
    // Check parameters

    if (! $error)
    {
        $newinvoice=new Facture($db);
        $newinvoice->socid=$invoice['thirdparty_id'];
        $newinvoice->type=$invoice['type'];
        $newinvoice->ref_ext=$invoice['ref_ext'];
        $newinvoice->date=$invoice['date'];
        $newinvoice->date_lim_reglement=$invoice['date_due'];
        $newinvoice->note=$invoice['note'];
        $newinvoice->note_public=$invoice['note_public'];
        $newinvoice->statut=$invoice['status'];
        $newinvoice->fk_project=$invoice['project_id'];
        $newinvoice->date_creation=$now;
        foreach($invoice['lines'] as $line)
        {
            $newline=new FactureLigne($db);
            $newline->type=$line['type'];
            $newline->desc=$line['desc'];
            $newline->fk_product=$line['fk_product'];
            $newline->total_ht=$line['total_net'];
            $newline->total_vat=$line['total_vat'];
            $newline->total_ttc=$line['total'];
            $newline->vat=$line['vat_rate'];
            $newline->qty=$line['qty'];
            $newline->fk_product=$line['product_id'];
        }
        //var_dump($invoice['ref_ext']);
        //var_dump($invoice['lines'][0]['type']);

        $db->begin();

        $result=$newinvoice->create($user,0,0);
        if ($result < 0)
        {
            $error++;
        }

        if ($newinvoice->statut == 1)   // We want invoice validated
        {
            $newinvoice->validate($user);
        }

        $result=$newinvoice->create($user,0,0);
        if ($result < 0)
        {
            $error++;
        }


        if (! $error)
        {
            $db->commit();
            $objectresp=array('result'=>array('result_code'=>'OK', 'result_label'=>''),'id'=>$newinvoice->id,'ref'=>$newinvoice->ref);
        }
        else
        {
            $db->rollback();
            $error++;
            $errorcode='KO';
            $errorlabel=$newinvoice->error;
        }

    }

    if ($error)
    {
        $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
    }

    return $objectresp;
}
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;
}
Exemplo n.º 14
0
 /**
  * testFactureAddLine3
  *
  * @return	void
  *
  * @depends	testFactureAddLine2
  * The depends says test is run only if previous is ok
  */
 public function testFactureAddLine3()
 {
     global $conf, $user, $langs, $db;
     $conf = $this->savconf;
     $user = $this->savuser;
     $langs = $this->savlangs;
     $db = $this->savdb;
     // With option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND = 0
     $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND = 0;
     $localobject3 = new Facture($this->savdb);
     $localobject3->initAsSpecimen('nolines');
     $facid = $localobject3->create($user);
     $localobject3->addline('Line 1', 6.36, 3, 21);
     $localobject3->addline('Line 2', 6.36, 3, 21);
     $localobject3->addline('Line 3', 6.36, 3, 21);
     $localobject3->addline('Line 4', 6.36, 3, 21);
     $localobject3->addline('Line 5', 6.36, 3, 21);
     print __METHOD__ . " id=" . $facid . " total_ttc=" . $localobject3->total_ttc . "\n";
     $this->assertEquals(95.40000000000001, $localobject3->total_ht);
     $this->assertEquals(20.05, $localobject3->total_tva);
     $this->assertEquals(115.45, $localobject3->total_ttc);
     // With option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND = 1
     $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND = 1;
     $localobject3 = new Facture($this->savdb);
     $localobject3->initAsSpecimen('nolines');
     $facid = $localobject3->create($user);
     $localobject3->addline('Line 1', 6.36, 3, 21);
     $localobject3->addline('Line 2', 6.36, 3, 21);
     $localobject3->addline('Line 3', 6.36, 3, 21);
     $localobject3->addline('Line 4', 6.36, 3, 21);
     $localobject3->addline('Line 5', 6.36, 3, 21);
     print __METHOD__ . " id=" . $facid . " total_ttc=" . $localobject3->total_ttc . "\n";
     $this->assertEquals(95.40000000000001, $localobject3->total_ht);
     $this->assertEquals(20.03, $localobject3->total_tva);
     $this->assertEquals(115.43, $localobject3->total_ttc);
 }
Exemplo n.º 15
0
 $object->note_public = trim($_POST['note_public']);
 $object->note = trim($_POST['note']);
 $object->ref_client = $_POST['ref_client'];
 $object->ref_int = $_POST['ref_int'];
 $object->modelpdf = $_POST['model'];
 $object->fk_project = $_POST['projectid'];
 $object->cond_reglement_id = $_POST['type'] == 3 ? 1 : $_POST['cond_reglement_id'];
 $object->mode_reglement_id = $_POST['mode_reglement_id'];
 $object->amount = $_POST['amount'];
 $object->remise_absolue = $_POST['remise_absolue'];
 $object->remise_percent = $_POST['remise_percent'];
 if ($_POST['origin'] && $_POST['originid']) {
     $object->origin = $_POST['origin'];
     $object->origin_id = $orders_id[$ii];
     $object->linked_objects = $orders_id;
     $id = $object->create($user);
     $object->fetch_thirdparty();
     if ($id > 0) {
         foreach ($orders_id as $origin => $origin_id) {
             $origin_id = !empty($origin_id) ? $origin_id : $object->origin_id;
             $db->begin();
             $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element (";
             $sql .= "fk_source";
             $sql .= ", sourcetype";
             $sql .= ", fk_target";
             $sql .= ", targettype";
             $sql .= ") VALUES (";
             $sql .= $origin_id;
             $sql .= ", '" . $object->origin . "'";
             $sql .= ", " . $id;
             $sql .= ", '" . $object->element . "'";
Exemplo n.º 16
0
$obj->socid          = 4;	// Put id of third party (rowid in llx_societe table)
$obj->date           = mktime();
$obj->note           = 'A comment';
$obj->cond_reglement_id = 1;

$line1=new FactureLigne($db);
$line1->tva_tx=10.0;
$line1->remise_percent=0;
$line1->qty=1;
$line1->total_ht=100;
$line1->total_tva=10;
$line1->total_ttc=110;
$obj->lines[]=$line1;

// Create invoice
$idobject=$obj->create($user);
if ($idobject > 0)
{
	// Change status to validated
	$result=$obj->validate($user);
	if ($result > 0) print "OK Object created with id ".$idobject."\n";
	else
	{
		$error++;
		dol_print_error($db,$obj->error);
	}
}
else
{
	$error++;
	dol_print_error($db,$obj->error);
 static function createFactureFromObject(&$object)
 {
     global $db, $conf, $user, $langs;
     dol_include_once('/compta/facture/class/facture.class.php');
     $langs->load('grapefruit@grapefruit');
     $dateinvoice = dol_mktime(0, 0, 0, date('m'), date('d'), date('Y'));
     $f = new Facture($db);
     $f->socid = $object->socid;
     $f->type = Facture::TYPE_STANDARD;
     $f->number = $_POST['facnumber'];
     $f->date = $dateinvoice;
     $f->note_public = $object->note_public;
     $f->note_private = $object->note_private;
     $f->ref_client = $object->ref_client;
     $f->fk_project = $object->fk_project;
     $f->cond_reglement_id = $object->cond_reglement_id;
     $f->mode_reglement_id = $object->mode_reglement_id;
     $origin = 'commande';
     $originid = $object->id;
     $f->linked_objects[$origin] = $originid;
     $id = $f->create($user);
     $lines = $object->lines;
     if (empty($lines) && method_exists($object, 'fetch_lines')) {
         $object->fetch_lines();
         $lines = $object->lines;
     }
     $fk_parent_line = 0;
     $num = count($lines);
     for ($i = 0; $i < $num; $i++) {
         $label = !empty($lines[$i]->label) ? $lines[$i]->label : '';
         $desc = !empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle;
         if ($f->situation_counter == 1) {
             $lines[$i]->situation_percent = 0;
         }
         if ($lines[$i]->subprice < 0) {
             // Negative line, we create a discount line
             $discount = new DiscountAbsolute($db);
             $discount->fk_soc = $f->socid;
             $discount->amount_ht = abs($lines[$i]->total_ht);
             $discount->amount_tva = abs($lines[$i]->total_tva);
             $discount->amount_ttc = abs($lines[$i]->total_ttc);
             $discount->tva_tx = $lines[$i]->tva_tx;
             $discount->fk_user = $user->id;
             $discount->description = $desc;
             $discountid = $discount->create($user);
             if ($discountid > 0) {
                 $result = $f->insert_discount($discountid);
                 // This include link_to_invoice
             } else {
                 setEventMessages($discount->error, $discount->errors, 'errors');
                 $error++;
                 break;
             }
         } else {
             // Positive line
             $product_type = $lines[$i]->product_type ? $lines[$i]->product_type : 0;
             // Date start
             $date_start = false;
             if ($lines[$i]->date_debut_prevue) {
                 $date_start = $lines[$i]->date_debut_prevue;
             }
             if ($lines[$i]->date_debut_reel) {
                 $date_start = $lines[$i]->date_debut_reel;
             }
             if ($lines[$i]->date_start) {
                 $date_start = $lines[$i]->date_start;
             }
             // Date end
             $date_end = false;
             if ($lines[$i]->date_fin_prevue) {
                 $date_end = $lines[$i]->date_fin_prevue;
             }
             if ($lines[$i]->date_fin_reel) {
                 $date_end = $lines[$i]->date_fin_reel;
             }
             if ($lines[$i]->date_end) {
                 $date_end = $lines[$i]->date_end;
             }
             // Reset fk_parent_line for no child products and special product
             if ($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line) || $lines[$i]->product_type == 9) {
                 $fk_parent_line = 0;
             }
             // Extrafields
             if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
                 $lines[$i]->fetch_optionals($lines[$i]->rowid);
                 $array_options = $lines[$i]->array_options;
             }
             // View third's localtaxes for now
             $localtax1_tx = get_localtax($lines[$i]->tva_tx, 1, $f->client);
             $localtax2_tx = get_localtax($lines[$i]->tva_tx, 2, $f->client);
             $result = $f->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $localtax1_tx, $localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $f->origin, $lines[$i]->rowid, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit);
             if ($result > 0) {
                 $lineid = $result;
             } else {
                 $lineid = 0;
                 $error++;
                 break;
             }
             // Defined the new fk_parent_line
             if ($result > 0 && $lines[$i]->product_type == 9) {
                 $fk_parent_line = $result;
             }
         }
     }
     if (empty($error)) {
         if ($f->validate($user) > 0) {
             $object->classifyBilled();
             // Redirection vers écrand de paiement
             setEventMessage($langs->trans('BillCreated'));
             header('Location: ' . dol_buildpath('/compta/paiement.php?action=create&facid=' . $f->id, 1));
         }
     }
 }
Exemplo n.º 18
0
 }
 if (!$error) {
     // Create draft invoice
     $invoice->type = Facture::TYPE_STANDARD;
     $invoice->cond_reglement_id = $customer->cond_reglement_id;
     if (empty($invoice->cond_reglement_id)) {
         $paymenttermstatic = new PaymentTerm($db);
         $invoice->cond_reglement_id = $paymenttermstatic->getDefaultId();
         if (empty($invoice->cond_reglement_id)) {
             $error++;
             $errmsg = 'ErrorNoPaymentTermRECEPFound';
         }
     }
     $invoice->socid = $object->fk_soc;
     $invoice->date = $datecotisation;
     $result = $invoice->create($user);
     if ($result <= 0) {
         $errmsg = $invoice->error;
         $errmsgs = $invoice->errors;
         $error++;
     }
 }
 if (!$error) {
     // Add line to draft invoice
     $idprodsubscription = 0;
     if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
         $idprodsubscription = $conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS;
     }
     $vattouse = 0;
     if (isset($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) && $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS == 'defaultforfoundationcountry') {
         $vattouse = get_default_tva($mysoc, $mysoc, $idprodsubscription);
Exemplo n.º 19
0
 /**
  * Test function addline and update_price
  *
  * @return 	boolean
  * @see		http://wiki.dolibarr.org/index.php/Draft:VAT_calculation_and_rounding#Standard_usage
  */
 public function testUpdatePrice()
 {
     //$this->sharedFixture
     global $conf, $user, $langs, $db;
     $this->savconf = $conf;
     $this->savuser = $user;
     $this->savlangs = $langs;
     $this->savdb = $db;
     $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND = 0;
     // Two lines of 1.24 give 2.48 HT and 2.72 TTC with standard vat rounding mode
     $localobject = new Facture($this->savdb);
     $localobject->initAsSpecimen('nolines');
     $invoiceid = $localobject->create($user);
     $localobject->addline('Desc', 1.24, 1, 10, 0, 0, 0, 0, '', '', 0, 0, 0, 'HT');
     $localobject->addline('Desc', 1.24, 1, 10, 0, 0, 0, 0, '', '', 0, 0, 0, 'HT');
     $newlocalobject = new Facture($this->savdb);
     $newlocalobject->fetch($invoiceid);
     $this->assertEquals(2.48, $newlocalobject->total_ht, "testUpdatePrice test1");
     $this->assertEquals(0.24, $newlocalobject->total_tva, "testUpdatePrice test2");
     $this->assertEquals(2.72, $newlocalobject->total_ttc, "testUpdatePrice test3");
     // Two lines of 1.24 give 2.48 HT and 2.73 TTC with global vat rounding mode
     $localobject = new Facture($this->savdb);
     $localobject->initAsSpecimen('nolines');
     $invoiceid = $localobject->create($user);
     $localobject->addline('Desc', 1.24, 1, 10, 0, 0, 0, 0, '', '', 0, 0, 0, 'HT');
     $localobject->addline('Desc', 1.24, 1, 10, 0, 0, 0, 0, '', '', 0, 0, 0, 'HT');
     $newlocalobject = new Facture($this->savdb);
     $newlocalobject->fetch($invoiceid);
     $this->assertEquals(2.48, $newlocalobject->total_ht, "testUpdatePrice test4");
     //$this->assertEquals(0.25,$newlocalobject->total_tva);
     //$this->assertEquals(2.73,$newlocalobject->total_ttc);
 }
Exemplo n.º 20
0
 /**
  *	Create a new invoice in database from current invoice
  *
  *	@param      User	$user    		Object user that ask creation
  *	@param		int		$invertdetail	Reverse sign of amounts for lines
  *	@return		int						<0 if KO, >0 if OK
  */
 function createFromCurrent($user, $invertdetail = 0)
 {
     // Charge facture source
     $facture = new Facture($this->db);
     $facture->fk_facture_source = $this->fk_facture_source;
     $facture->type = $this->type;
     $facture->socid = $this->socid;
     $facture->date = $this->date;
     $facture->note_public = $this->note_public;
     $facture->note_private = $this->note_private;
     $facture->ref_client = $this->ref_client;
     $facture->modelpdf = $this->modelpdf;
     $facture->fk_project = $this->fk_project;
     $facture->cond_reglement_id = $this->cond_reglement_id;
     $facture->mode_reglement_id = $this->mode_reglement_id;
     $facture->remise_absolue = $this->remise_absolue;
     $facture->remise_percent = $this->remise_percent;
     $facture->lines = $this->lines;
     // Tableau des lignes de factures
     $facture->products = $this->lines;
     // Tant que products encore utilise
     $facture->situation_counter = $this->situation_counter;
     $facture->situation_cycle_ref = $this->situation_cycle_ref;
     $facture->situation_final = $this->situation_final;
     // Loop on each line of new invoice
     foreach ($facture->lines as $i => $line) {
         $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
         if ($invertdetail) {
             $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
             $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
             $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
             $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
             $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
             $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
         }
     }
     dol_syslog(get_class($this) . "::createFromCurrent invertdetail=" . $invertdetail . " socid=" . $this->socid . " nboflines=" . count($facture->lines));
     $facid = $facture->create($user);
     if ($facid <= 0) {
         $this->error = $facture->error;
         $this->errors = $facture->errors;
     }
     return $facid;
 }
 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;
     }
 }