dolibarr 18.0.6
facture-rec.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2019 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2009-2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
6 * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
7 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
8 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
9 * Copyright (C) 2017-2020 Frédéric France <frederic.france@netlogic.fr>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
31require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
32require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
33require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
34require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
35
36
41{
42 const TRIGGER_PREFIX = 'BILLREC';
46 public $element = 'facturerec';
47
51 public $table_element = 'facture_rec';
52
56 public $table_element_line = 'facturedet_rec';
57
61 public $fk_element = 'fk_facture';
62
66 public $picto = 'bill';
67
71 public $entity;
72
76 protected $table_ref_field = 'titre';
77
81 public $title;
82
87 public $titre;
88
89 public $socid;
90 public $number;
91 public $date;
92 public $remise;
93 public $remise_absolue;
94 public $remise_percent;
95
100 public $total;
101
106 public $tva;
107
108 public $date_last_gen;
109 public $date_when;
110 public $nb_gen_done;
111 public $nb_gen_max;
112
113 public $user_author;
114
118 public $frequency;
119
123 public $unit_frequency;
124
125 public $rang;
126 public $special_code;
127
128 public $usenewprice = 0;
129
130 public $date_lim_reglement;
131 public $cond_reglement_code; // Code in llx_c_paiement
132 public $mode_reglement_code; // Code in llx_c_paiement
133
134 public $suspended; // status
135
136 public $auto_validate; // 0 to create in draft, 1 to create and validate the new invoice
137 public $generate_pdf; // 1 to generate PDF on invoice generation (default)
138
143 public $brouillon;
144
145
170 // BEGIN MODULEBUILDER PROPERTIES
174 public $fields = array(
175 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
176 'titre' =>array('type'=>'varchar(100)', 'label'=>'Titre', 'enabled'=>1, 'showoncombobox' => 1, 'visible'=>-1, 'position'=>15),
177 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1),
178 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'isModEnabled("societe")', 'visible'=>-1, 'notnull'=>1, 'position'=>25),
179 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
180 //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
181 'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
182 //'remise_percent' =>array('type'=>'double', 'label'=>'Remise percent', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
183 //'remise_absolue' =>array('type'=>'double', 'label'=>'Remise absolue', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
184 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'Tva', 'enabled'=>1, 'visible'=>-1, 'position'=>55, 'isameasure'=>1),
185 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'isameasure'=>1),
186 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>65, 'isameasure'=>1),
187 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'Total', 'enabled'=>1, 'visible'=>-1, 'position'=>70, 'isameasure'=>1),
188 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>75, 'isameasure'=>1),
189 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
190 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Fk projet', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>85),
191 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'Fk cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
192 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'Fk mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
193 'date_lim_reglement' =>array('type'=>'date', 'label'=>'Date lim reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
194 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>105),
195 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>110),
196 'modelpdf' =>array('type'=>'varchar(255)', 'label'=>'Modelpdf', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
197 'date_when' =>array('type'=>'datetime', 'label'=>'Date when', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
198 'date_last_gen' =>array('type'=>'datetime', 'label'=>'Date last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
199 'nb_gen_done' =>array('type'=>'integer', 'label'=>'Nb gen done', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
200 'nb_gen_max' =>array('type'=>'integer', 'label'=>'Nb gen max', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
201 'frequency' =>array('type'=>'integer', 'label'=>'Frequency', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
202 'unit_frequency' =>array('type'=>'varchar(2)', 'label'=>'UnitFrequency', 'enabled'=>1, 'visible'=>-1, 'position'=>152),
203 'usenewprice' =>array('type'=>'integer', 'label'=>'UseNewPrice', 'enabled'=>1, 'visible'=>0, 'position'=>155),
204 'revenuestamp' =>array('type'=>'double(24,8)', 'label'=>'RevenueStamp', 'enabled'=>1, 'visible'=>-1, 'position'=>160, 'isameasure'=>1),
205 'auto_validate' =>array('type'=>'integer', 'label'=>'Auto validate', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
206 'generate_pdf' =>array('type'=>'integer', 'label'=>'Generate pdf', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
207 'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>'isModEnabled("banque")', 'visible'=>-1, 'position'=>175),
208 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
209 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
210 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency tx', 'enabled'=>1, 'visible'=>-1, 'position'=>190, 'isameasure'=>1),
211 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>195, 'isameasure'=>1),
212 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>200, 'isameasure'=>1),
213 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>205, 'isameasure'=>1),
214 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>210),
215 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>215),
216 'suspended' =>array('type'=>'integer', 'label'=>'Suspended', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
217 );
218 // END MODULEBUILDER PROPERTIES
219
220 const STATUS_NOTSUSPENDED = 0;
221 const STATUS_SUSPENDED = 1;
222
223
224
230 public function __construct(DoliDB $db)
231 {
232 $this->db = $db;
233 }
234
243 public function create($user, $facid, $notrigger = 0)
244 {
245 global $conf;
246
247 $error = 0;
248 $now = dol_now();
249
250 // Clean parameters
251 $this->titre = trim(isset($this->titre) ? $this->titre : $this->title); // deprecated
252 $this->title = trim($this->title);
253 $this->usenewprice = empty($this->usenewprice) ? 0 : $this->usenewprice;
254 if (empty($this->suspended)) {
255 $this->suspended = 0;
256 }
257
258 // No frequency defined then no next date to execution
259 if (empty($this->frequency)) {
260 $this->frequency = 0;
261 $this->date_when = null;
262 }
263
264 $this->frequency = abs($this->frequency);
265 $this->nb_gen_done = 0;
266 $this->nb_gen_max = empty($this->nb_gen_max) ? 0 : $this->nb_gen_max;
267 $this->auto_validate = empty($this->auto_validate) ? 0 : $this->auto_validate;
268 $this->generate_pdf = empty($this->generate_pdf) ? 0 : $this->generate_pdf;
269
270 $this->db->begin();
271
272 // Charge facture modele
273 $facsrc = new Facture($this->db);
274 $result = $facsrc->fetch($facid);
275 if ($result > 0) {
276 // On positionne en mode brouillon la facture
277 $this->brouillon = 1;
278 $this->fk_soc = $facsrc->socid;
279
280 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_rec (";
281 $sql .= "titre";
282 $sql .= ", fk_soc";
283 $sql .= ", entity";
284 $sql .= ", datec";
285 $sql .= ", amount";
286 $sql .= ", remise";
287 $sql .= ", note_private";
288 $sql .= ", note_public";
289 $sql .= ", modelpdf";
290 $sql .= ", fk_user_author";
291 $sql .= ", fk_projet";
292 $sql .= ", fk_account";
293 $sql .= ", fk_cond_reglement";
294 $sql .= ", fk_mode_reglement";
295 $sql .= ", usenewprice";
296 $sql .= ", frequency";
297 $sql .= ", unit_frequency";
298 $sql .= ", date_when";
299 $sql .= ", date_last_gen";
300 $sql .= ", nb_gen_done";
301 $sql .= ", nb_gen_max";
302 $sql .= ", auto_validate";
303 $sql .= ", generate_pdf";
304 $sql .= ", fk_multicurrency";
305 $sql .= ", multicurrency_code";
306 $sql .= ", multicurrency_tx";
307 $sql .= ", suspended";
308 $sql .= ") VALUES (";
309 $sql .= "'".$this->db->escape($this->titre ? $this->titre : $this->title)."'";
310 $sql .= ", ".((int) $this->fk_soc);
311 $sql .= ", ".((int) $conf->entity);
312 $sql .= ", '".$this->db->idate($now)."'";
313 $sql .= ", ".(!empty($facsrc->total_ttc) ? ((float) $facsrc->total_ttc) : '0');
314 $sql .= ", ".(!empty($facsrc->remise_absolue) ? ((float) $this->remise_absolue) : '0');
315 $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
316 $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
317 $sql .= ", ".(!empty($this->model_pdf) ? ("'".$this->db->escape($this->model_pdf)."'") : "NULL");
318 $sql .= ", ".((int) $user->id);
319 $sql .= ", ".(!empty($this->fk_project) ? ((int) $this->fk_project) : "null");
320 $sql .= ", ".(!empty($facsrc->fk_account) ? ((int) $facsrc->fk_account) : "null");
321 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
322 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
323 $sql .= ", ".((int) $this->usenewprice);
324 $sql .= ", ".((int) $this->frequency);
325 $sql .= ", '".$this->db->escape($this->unit_frequency)."'";
326 $sql .= ", ".(!empty($this->date_when) ? "'".$this->db->idate($this->date_when)."'" : 'NULL');
327 $sql .= ", ".(!empty($this->date_last_gen) ? "'".$this->db->idate($this->date_last_gen)."'" : 'NULL');
328 $sql .= ", ".((int) $this->nb_gen_done);
329 $sql .= ", ".((int) $this->nb_gen_max);
330 $sql .= ", ".((int) $this->auto_validate);
331 $sql .= ", ".((int) $this->generate_pdf);
332 $sql .= ", ".((int) $facsrc->fk_multicurrency);
333 $sql .= ", '".$this->db->escape($facsrc->multicurrency_code)."'";
334 $sql .= ", ".((float) $facsrc->multicurrency_tx);
335 $sql .= ", ".((int) $this->suspended);
336 $sql .= ")";
337
338 if ($this->db->query($sql)) {
339 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."facture_rec");
340
341 // Fields used into addline later
342 $this->fk_multicurrency = $facsrc->fk_multicurrency;
343 $this->multicurrency_code = $facsrc->multicurrency_code;
344 $this->multicurrency_tx = $facsrc->multicurrency_tx;
345
346 // Add lines
347 $num = count($facsrc->lines);
348 for ($i = 0; $i < $num; $i++) {
349 $tva_tx = $facsrc->lines[$i]->tva_tx;
350 if (!empty($facsrc->lines[$i]->vat_src_code) && !preg_match('/\‍(/', $tva_tx)) {
351 $tva_tx .= ' ('.$facsrc->lines[$i]->vat_src_code.')';
352 }
353
354 $default_start_fill = getDolGlobalInt('INVOICEREC_SET_AUTOFILL_DATE_START');
355 $default_end_fill = getDolGlobalInt('INVOICEREC_SET_AUTOFILL_DATE_END');
356
357 $result_insert = $this->addline(
358 $facsrc->lines[$i]->desc,
359 $facsrc->lines[$i]->subprice,
360 $facsrc->lines[$i]->qty,
361 $tva_tx,
362 $facsrc->lines[$i]->localtax1_tx,
363 $facsrc->lines[$i]->localtax2_tx,
364 $facsrc->lines[$i]->fk_product,
365 $facsrc->lines[$i]->remise_percent,
366 'HT',
367 $facsrc->lines[$i]->info_bits,
368 '',
369 0,
370 $facsrc->lines[$i]->product_type,
371 $facsrc->lines[$i]->rang,
372 $facsrc->lines[$i]->special_code,
373 $facsrc->lines[$i]->label,
374 $facsrc->lines[$i]->fk_unit,
375 $facsrc->lines[$i]->multicurrency_subprice,
376 $default_start_fill,
377 $default_end_fill,
378 null,
379 $facsrc->lines[$i]->pa_ht
380 );
381
382 if ($result_insert < 0) {
383 $error++;
384 } else {
385 $objectline = new FactureLigneRec($this->db);
386
387 $result2 = $objectline->fetch($result_insert);
388 if ($result2 > 0) {
389 // Extrafields
390 if (method_exists($facsrc->lines[$i], 'fetch_optionals')) {
391 $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->id);
392 $objectline->array_options = $facsrc->lines[$i]->array_options;
393 }
394
395 $result = $objectline->insertExtraFields();
396 if ($result < 0) {
397 $error++;
398 }
399 } elseif ($result2 < 0) {
400 $this->errors[] = $objectline->error;
401 $error++;
402 }
403 }
404 }
405
406 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
407 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
408 }
409
410 // Add object linked
411 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
412 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
413 if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
414 foreach ($tmp_origin_id as $origin_id) {
415 $ret = $this->add_object_linked($origin, $origin_id);
416 if (!$ret) {
417 $this->error = $this->db->lasterror();
418 $error++;
419 }
420 }
421 } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
422 {
423 $origin_id = $tmp_origin_id;
424 $ret = $this->add_object_linked($origin, $origin_id);
425 if (!$ret) {
426 $this->error = $this->db->lasterror();
427 $error++;
428 }
429 }
430 }
431 }
432
433 if (!$error) {
434 $result = $this->insertExtraFields();
435 if ($result < 0) {
436 $error++;
437 }
438 }
439
440 if (!$error && !$notrigger) {
441 // Call trigger
442 $result = $this->call_trigger('BILLREC_CREATE', $user);
443 if ($result < 0) {
444 $this->db->rollback();
445 return -2;
446 }
447 // End call triggers
448 }
449
450 if ($error) {
451 $this->db->rollback();
452 return -3;
453 } else {
454 $this->db->commit();
455 return $this->id;
456 }
457 } else {
458 $this->error = $this->db->lasterror();
459 $this->db->rollback();
460 return -2;
461 }
462 } else {
463 $this->db->rollback();
464 return -1;
465 }
466 }
467
468
476 public function update(User $user, $notrigger = 0)
477 {
478 $error = 0;
479
480 $sql = "UPDATE ".MAIN_DB_PREFIX."facture_rec SET";
481 $sql .= " entity = ".((int) $this->entity).",";
482 $sql .= " titre = '".$this->db->escape($this->title)."',";
483 $sql .= " suspended = ".((int) $this->suspended).",";
484 $sql .= " fk_soc = ".((int) $this->socid).",";
485 $sql .= " total_tva = ".((float) $this->total_tva).",";
486 $sql .= " localtax1 = ".((float) $this->total_localtax1).",";
487 $sql .= " localtax2 = ".((float) $this->total_localtax2).",";
488 $sql .= " total_ht = ".((float) $this->total_ht).",";
489 $sql .= " total_ttc = ".((float) $this->total_ttc).",";
490 $sql .= " remise_percent = ".((float) $this->remise_percent);
491 // TODO Add missing fields
492 $sql .= " WHERE rowid = ".((int) $this->id);
493
494 $this->db->begin();
495
496 dol_syslog(get_class($this)."::update", LOG_DEBUG);
497
498 $resql = $this->db->query($sql);
499 if ($resql) {
500 if (!$error) {
501 $result = $this->insertExtraFields();
502 if ($result < 0) {
503 $error++;
504 }
505 }
506
507 if (!$error && !$notrigger) {
508 // Call trigger
509 $result = $this->call_trigger('BILLREC_MODIFY', $user);
510 if ($result < 0) {
511 $this->db->rollback();
512 return -2;
513 }
514 // End call triggers
515 }
516 $this->db->commit();
517 return 1;
518 } else {
519 $this->error = $this->db->lasterror();
520 $this->db->rollback();
521 return -1;
522 }
523 }
524
533 public function fetch($rowid, $ref = '', $ref_ext = '')
534 {
535 dol_syslog('FactureRec::fetch', LOG_DEBUG);
536
537 $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc, f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc';
538 $sql .= ', f.remise_percent, f.remise_absolue, f.remise';
539 $sql .= ', f.date_lim_reglement as dlr';
540 $sql .= ', f.note_private, f.note_public, f.fk_user_author';
541 $sql .= ', f.modelpdf as model_pdf';
542 $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project';
543 $sql .= ', f.fk_account';
544 $sql .= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.usenewprice, f.auto_validate';
545 $sql .= ', f.generate_pdf';
546 $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
547 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
548 $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
549 //$sql.= ', el.fk_source';
550 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f';
551 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
552 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
553 //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'";
554 $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')';
555 if ($rowid) {
556 $sql .= ' AND f.rowid = '.((int) $rowid);
557 } elseif ($ref) {
558 $sql .= " AND f.titre = '".$this->db->escape($ref)."'";
559 } else {
560 $sql .= ' AND f.rowid = 0';
561 }
562 /* This field are not used for template invoice
563 if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
564 */
565
566 $result = $this->db->query($sql);
567 if ($result) {
568 if ($this->db->num_rows($result)) {
569 $obj = $this->db->fetch_object($result);
570
571 $this->id = $obj->rowid;
572 $this->entity = $obj->entity;
573 $this->titre = $obj->title; // deprecated
574 $this->title = $obj->title;
575 $this->ref = $obj->title;
576 $this->suspended = $obj->suspended;
577 $this->remise_percent = $obj->remise_percent;
578 $this->remise_absolue = $obj->remise_absolue;
579 $this->remise = $obj->remise;
580 $this->total_ht = $obj->total_ht;
581 $this->total_tva = $obj->total_tva;
582 $this->total_localtax1 = $obj->localtax1;
583 $this->total_localtax2 = $obj->localtax2;
584 $this->total_ttc = $obj->total_ttc;
585 $this->socid = $obj->fk_soc;
586 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
587 $this->mode_reglement_id = $obj->fk_mode_reglement;
588 $this->mode_reglement_code = $obj->mode_reglement_code;
589 $this->mode_reglement = $obj->mode_reglement_libelle;
590 $this->cond_reglement_id = $obj->fk_cond_reglement;
591 $this->cond_reglement_code = $obj->cond_reglement_code;
592 $this->cond_reglement = $obj->cond_reglement_libelle;
593 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
594 $this->fk_project = $obj->fk_project;
595 $this->fk_account = $obj->fk_account;
596 $this->note_private = $obj->note_private;
597 $this->note_public = $obj->note_public;
598 $this->user_author = $obj->fk_user_author;
599 $this->modelpdf = $obj->model_pdf; // deprecated
600 $this->model_pdf = $obj->model_pdf;
601 //$this->special_code = $obj->special_code;
602 $this->frequency = $obj->frequency;
603 $this->unit_frequency = $obj->unit_frequency;
604 $this->date_when = $this->db->jdate($obj->date_when);
605 $this->date_last_gen = $this->db->jdate($obj->date_last_gen);
606 $this->nb_gen_done = $obj->nb_gen_done;
607 $this->nb_gen_max = $obj->nb_gen_max;
608 $this->usenewprice = $obj->usenewprice;
609 $this->auto_validate = $obj->auto_validate;
610 $this->generate_pdf = $obj->generate_pdf;
611
612 // Multicurrency
613 $this->fk_multicurrency = $obj->fk_multicurrency;
614 $this->multicurrency_code = $obj->multicurrency_code;
615 $this->multicurrency_tx = $obj->multicurrency_tx;
616 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
617 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
618 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
619
620 if ($this->statut == self::STATUS_DRAFT) {
621 $this->brouillon = 1;
622 }
623
624 // Retrieve all extrafield
625 // fetch optionals attributes and labels
626 $this->fetch_optionals();
627
628 /*
629 * Lines
630 */
631 $result = $this->fetch_lines();
632 if ($result < 0) {
633 $this->error = $this->db->lasterror();
634 return -3;
635 }
636 return 1;
637 } else {
638 $this->error = 'Bill with id '.$rowid.' or ref '.$ref.' not found';
639 dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
640 return -2;
641 }
642 } else {
643 $this->error = $this->db->error();
644 return -1;
645 }
646 }
647
648
654 public function getLinesArray()
655 {
656 return $this->fetch_lines();
657 }
658
659
660 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
666 public function fetch_lines()
667 {
668 // phpcs:enable
669
670 $this->lines = array();
671
672 dol_syslog('FactureRec::fetch_lines', LOG_DEBUG);
673
674 $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx, ';
675 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
676 $sql .= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc, l.fk_product_fournisseur_price, l.buy_price_ht as pa_ht,';
677 $sql .= ' l.rang, l.special_code,';
678 $sql .= ' l.fk_unit, l.fk_contract_line,';
679 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
680 $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
681 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
682 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
683 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
684 $sql .= ' ORDER BY l.rang';
685
686 $result = $this->db->query($sql);
687 if ($result) {
688 $num = $this->db->num_rows($result);
689 $i = 0;
690 while ($i < $num) {
691 $objp = $this->db->fetch_object($result);
692 $line = new FactureLigneRec($this->db);
693
694 $line->id = $objp->rowid;
695 $line->rowid = $objp->rowid;
696 $line->desc = $objp->description; // Description line
697 $line->description = $objp->description; // Description line
698 $line->ref = $objp->product_ref; // Ref product
699 $line->product_ref = $objp->product_ref; // Ref product
700 $line->libelle = $objp->product_label; // deprecated
701 $line->product_label = $objp->product_label; // Label product
702 $line->product_desc = $objp->product_desc; // Description product
703 $line->product_type = $objp->product_type; // Type of line
704 $line->fk_product_type = $objp->fk_product_type; // Type of product
705 $line->qty = $objp->qty;
706 $line->subprice = $objp->subprice;
707
708 $line->label = $objp->custom_label; // @deprecated
709
710 $line->vat_src_code = $objp->vat_src_code;
711 $line->tva_tx = $objp->tva_tx;
712 $line->localtax1_tx = $objp->localtax1_tx;
713 $line->localtax2_tx = $objp->localtax2_tx;
714 $line->localtax1_type = $objp->localtax1_type;
715 $line->localtax2_type = $objp->localtax2_type;
716 $line->remise_percent = $objp->remise_percent;
717 //$line->fk_remise_except = $objp->fk_remise_except;
718 $line->fk_product = $objp->fk_product;
719 $line->date_start_fill = $objp->date_start_fill;
720 $line->date_end_fill = $objp->date_end_fill;
721 $line->info_bits = $objp->info_bits;
722 $line->total_ht = $objp->total_ht;
723 $line->total_tva = $objp->total_tva;
724 $line->total_ttc = $objp->total_ttc;
725
726 //$line->code_ventilation = $objp->fk_code_ventilation;
727
728 $line->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
729 $line->fk_fournprice = $objp->fk_product_fournisseur_price; // For backward compatibility
730
731 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_product_fournisseur_price, $objp->pa_ht);
732
733 $line->buyprice = $marginInfos[0];
734 $line->pa_ht = $marginInfos[0]; // For backward compatibility
735 $line->marge_tx = $marginInfos[1];
736 $line->marque_tx = $marginInfos[2];
737 $line->rang = $objp->rang;
738 $line->special_code = $objp->special_code;
739 $line->fk_unit = $objp->fk_unit;
740 $line->fk_contract_line = $objp->fk_contract_line;
741
742 // Ne plus utiliser
743 $line->price = $objp->price;
744 $line->remise = $objp->remise;
745
746 $line->fetch_optionals();
747
748 // Multicurrency
749 $line->fk_multicurrency = $objp->fk_multicurrency;
750 $line->multicurrency_code = $objp->multicurrency_code;
751 $line->multicurrency_subprice = $objp->multicurrency_subprice;
752 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
753 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
754 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
755
756 $this->lines[$i] = $line;
757
758 $i++;
759 }
760
761 $this->db->free($result);
762 return 1;
763 } else {
764 $this->error = $this->db->lasterror();
765 return -3;
766 }
767 }
768
769
778 public function delete(User $user, $notrigger = 0, $idwarehouse = -1)
779 {
780 $rowid = $this->id;
781
782 dol_syslog(get_class($this)."::delete rowid=".((int) $rowid), LOG_DEBUG);
783
784 $error = 0;
785 $this->db->begin();
786
787 $main = MAIN_DB_PREFIX.'facturedet_rec';
788 $ef = $main."_extrafields";
789
790 $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
791 $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".((int) $rowid);
792
793 if ($this->db->query($sqlef) && $this->db->query($sql)) {
794 $sql = "DELETE FROM ".MAIN_DB_PREFIX."facture_rec WHERE rowid = ".((int) $rowid);
795 dol_syslog($sql);
796 if ($this->db->query($sql)) {
797 // Delete linked object
798 $res = $this->deleteObjectLinked();
799 if ($res < 0) {
800 $error = -3;
801 }
802 // Delete extrafields
803 $res = $this->deleteExtraFields();
804 if ($res < 0) {
805 $error = -4;
806 }
807 } else {
808 $this->error = $this->db->lasterror();
809 $error = -1;
810 }
811 } else {
812 $this->error = $this->db->lasterror();
813 $error = -2;
814 }
815 if (!$error && !$notrigger) {
816 // Call trigger
817 $result = $this->call_trigger('BILLREC_DELETE', $user);
818 if ($result < 0) {
819 $error++;
820 }
821 // End call triggers
822 }
823 if (!$error) {
824 $this->db->commit();
825 return 1;
826 } else {
827 $this->db->rollback();
828 return $error;
829 }
830 }
831
832
860 public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0)
861 {
862 global $mysoc;
863
864 $facid = $this->id;
865
866 dol_syslog(get_class($this)."::addline facid=$facid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva,txlocaltax1=$txlocaltax1,txlocaltax2=$txlocaltax2,fk_product=$fk_product,remise_percent=$remise_percent,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit,pu_ht_devise=$pu_ht_devise,date_start_fill=$date_start_fill,date_end_fill=$date_end_fill,pa_ht=$pa_ht", LOG_DEBUG);
867 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
868
869 // Check parameters
870 if ($type < 0) {
871 return -1;
872 }
873
874 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
875
876 // Clean vat code
877 $reg = array();
878 $vat_src_code = '';
879 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
880 $vat_src_code = $reg[1];
881 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
882 }
883
884 if ($this->brouillon) {
885 // Clean parameters
886 $remise_percent = price2num($remise_percent);
887 if (empty($remise_percent)) {
888 $remise_percent = 0;
889 }
890 $qty = price2num($qty);
891 $pu_ht = price2num($pu_ht);
892 $pu_ttc = price2num($pu_ttc);
893 if (!preg_match('/\‍((.*)\‍)/', $txtva)) {
894 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
895 }
896 $txlocaltax1 = price2num($txlocaltax1);
897 $txlocaltax2 = price2num($txlocaltax2);
898 if (empty($txtva)) {
899 $txtva = 0;
900 }
901 if (empty($txlocaltax1)) {
902 $txlocaltax1 = 0;
903 }
904 if (empty($txlocaltax2)) {
905 $txlocaltax2 = 0;
906 }
907 if (empty($info_bits)) {
908 $info_bits = 0;
909 }
910
911 if ($price_base_type == 'HT') {
912 $pu = $pu_ht;
913 } else {
914 $pu = $pu_ttc;
915 }
916
917 // Calcul du total TTC et de la TVA pour la ligne a partir de
918 // qty, pu, remise_percent et txtva
919 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
920 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
921
922 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
923 $total_ht = $tabprice[0];
924 $total_tva = $tabprice[1];
925 $total_ttc = $tabprice[2];
926 $total_localtax1 = $tabprice[9];
927 $total_localtax2 = $tabprice[10];
928 $pu_ht = $tabprice[3];
929
930 // MultiCurrency
931 $multicurrency_total_ht = $tabprice[16];
932 $multicurrency_total_tva = $tabprice[17];
933 $multicurrency_total_ttc = $tabprice[18];
934 $pu_ht_devise = $tabprice[19];
935
936 $product_type = $type;
937 if ($fk_product) {
938 $product = new Product($this->db);
939 $result = $product->fetch($fk_product);
940 $product_type = $product->type;
941 }
942
943 // Rank to use
944 $ranktouse = $rang;
945 if ($ranktouse == -1) {
946 $rangmax = $this->line_max(0);
947 $ranktouse = $rangmax + 1;
948 }
949
950 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facturedet_rec (";
951 $sql .= "fk_facture";
952 $sql .= ", label";
953 $sql .= ", description";
954 $sql .= ", price";
955 $sql .= ", qty";
956 $sql .= ", tva_tx";
957 $sql .= ", vat_src_code";
958 $sql .= ", localtax1_tx";
959 $sql .= ", localtax1_type";
960 $sql .= ", localtax2_tx";
961 $sql .= ", localtax2_type";
962 $sql .= ", fk_product";
963 $sql .= ", product_type";
964 $sql .= ", remise_percent";
965 $sql .= ", subprice";
966 $sql .= ", remise";
967 $sql .= ", total_ht";
968 $sql .= ", total_tva";
969 $sql .= ", total_localtax1";
970 $sql .= ", total_localtax2";
971 $sql .= ", total_ttc";
972 $sql .= ", date_start_fill";
973 $sql .= ", date_end_fill";
974 $sql .= ", fk_product_fournisseur_price";
975 $sql .= ", buy_price_ht";
976 $sql .= ", info_bits";
977 $sql .= ", rang";
978 $sql .= ", special_code";
979 $sql .= ", fk_unit";
980 $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
981 $sql .= ") VALUES (";
982 $sql .= " ".((int) $facid);
983 $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
984 $sql .= ", '".$this->db->escape($desc)."'";
985 $sql .= ", ".price2num($pu_ht);
986 $sql .= ", ".price2num($qty);
987 $sql .= ", ".price2num($txtva);
988 $sql .= ", '".$this->db->escape($vat_src_code)."'";
989 $sql .= ", ".price2num($txlocaltax1);
990 $sql .= ", '".$this->db->escape(isset($localtaxes_type[0]) ? $localtaxes_type[0] : '')."'";
991 $sql .= ", ".price2num($txlocaltax2);
992 $sql .= ", '".$this->db->escape(isset($localtaxes_type[2]) ? $localtaxes_type[2] : '')."'";
993 $sql .= ", ".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null");
994 $sql .= ", ".((int) $product_type);
995 $sql .= ", ".price2num($remise_percent);
996 $sql .= ", ".price2num($pu_ht);
997 $sql .= ", null";
998 $sql .= ", ".price2num($total_ht);
999 $sql .= ", ".price2num($total_tva);
1000 $sql .= ", ".price2num($total_localtax1);
1001 $sql .= ", ".price2num($total_localtax2);
1002 $sql .= ", ".price2num($total_ttc);
1003 $sql .= ", ".(int) $date_start_fill;
1004 $sql .= ", ".(int) $date_end_fill;
1005 $sql .= ", ".($fk_fournprice > 0 ? $fk_fournprice : 'null');
1006 $sql .= ", ".($pa_ht ? price2num($pa_ht) : 0);
1007 $sql .= ", ".((int) $info_bits);
1008 $sql .= ", ".((int) $ranktouse);
1009 $sql .= ", ".((int) $special_code);
1010 $sql .= ", ".($fk_unit ? ((int) $fk_unit) : "null");
1011 $sql .= ", ".(int) $this->fk_multicurrency;
1012 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1013 $sql .= ", ".price2num($pu_ht_devise, 'CU');
1014 $sql .= ", ".price2num($multicurrency_total_ht, 'CT');
1015 $sql .= ", ".price2num($multicurrency_total_tva, 'CT');
1016 $sql .= ", ".price2num($multicurrency_total_ttc, 'CT');
1017 $sql .= ")";
1018
1019 dol_syslog(get_class($this)."::addline", LOG_DEBUG);
1020 if ($this->db->query($sql)) {
1021 $lineId = $this->db->last_insert_id(MAIN_DB_PREFIX."facturedet_rec");
1022 $this->id = $facid;
1023 $this->update_price(1);
1024 return $lineId;
1025 } else {
1026 $this->error = $this->db->lasterror();
1027 return -1;
1028 }
1029 } else {
1030 $this->error = 'Recurring Invoice is suspended. adding lines not allowed.';
1031
1032 return -1;
1033 }
1034 }
1035
1065 public function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0)
1066 {
1067 global $mysoc;
1068
1069 $facid = $this->id;
1070
1071 dol_syslog(get_class($this)."::updateline facid=".$facid." rowid=$rowid, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, type=$type, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG);
1072 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1073
1074 // Clean parameters
1075 if (empty($remise_percent)) {
1076 $remise_percent = 0;
1077 }
1078
1079 // Check parameters
1080 if ($type < 0) {
1081 return -1;
1082 }
1083
1084 if ($this->brouillon) {
1085 // Clean parameters
1086 $remise_percent = price2num($remise_percent);
1087 $qty = price2num($qty);
1088 if (empty($info_bits)) {
1089 $info_bits = 0;
1090 }
1091 $pu_ht = price2num($pu_ht);
1092 $pu_ttc = price2num($pu_ttc);
1093 $pu_ht_devise = price2num($pu_ht_devise);
1094 if (!preg_match('/\‍((.*)\‍)/', $txtva)) {
1095 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
1096 }
1097 $txlocaltax1 = price2num($txlocaltax1);
1098 $txlocaltax2 = price2num($txlocaltax2);
1099 if (empty($txlocaltax1)) {
1100 $txlocaltax1 = 0;
1101 }
1102 if (empty($txlocaltax2)) {
1103 $txlocaltax2 = 0;
1104 }
1105
1106 if (empty($this->multicurrency_subprice)) {
1107 $this->multicurrency_subprice = 0;
1108 }
1109 if (empty($this->multicurrency_total_ht)) {
1110 $this->multicurrency_total_ht = 0;
1111 }
1112 if (empty($this->multicurrency_total_tva)) {
1113 $this->multicurrency_total_tva = 0;
1114 }
1115 if (empty($this->multicurrency_total_ttc)) {
1116 $this->multicurrency_total_ttc = 0;
1117 }
1118
1119 if ($price_base_type == 'HT') {
1120 $pu = $pu_ht;
1121 } else {
1122 $pu = $pu_ttc;
1123 }
1124
1125 // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
1126 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1127 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1128
1129 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
1130
1131 // Clean vat code
1132 $vat_src_code = '';
1133 $reg = array();
1134 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1135 $vat_src_code = $reg[1];
1136 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1137 }
1138
1139 $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
1140
1141 $total_ht = $tabprice[0];
1142 $total_tva = $tabprice[1];
1143 $total_ttc = $tabprice[2];
1144 $total_localtax1 = $tabprice[9];
1145 $total_localtax2 = $tabprice[10];
1146 $pu_ht = $tabprice[3];
1147 $pu_tva = $tabprice[4];
1148 $pu_ttc = $tabprice[5];
1149
1150 // MultiCurrency
1151 $multicurrency_total_ht = $tabprice[16];
1152 $multicurrency_total_tva = $tabprice[17];
1153 $multicurrency_total_ttc = $tabprice[18];
1154 $pu_ht_devise = $tabprice[19];
1155
1156 $product_type = $type;
1157 if ($fk_product) {
1158 $product = new Product($this->db);
1159 $result = $product->fetch($fk_product);
1160 $product_type = $product->type;
1161 }
1162
1163 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET ";
1164 $sql .= "fk_facture = ".((int) $facid);
1165 $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
1166 $sql .= ", description='".$this->db->escape($desc)."'";
1167 $sql .= ", price=".price2num($pu_ht);
1168 $sql .= ", qty=".price2num($qty);
1169 $sql .= ", tva_tx=".price2num($txtva);
1170 $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'";
1171 $sql .= ", localtax1_tx=".((float) $txlocaltax1);
1172 $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'";
1173 $sql .= ", localtax2_tx=".((float) $txlocaltax2);
1174 $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'";
1175 $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null");
1176 $sql .= ", product_type=".((int) $product_type);
1177 $sql .= ", remise_percent='".price2num($remise_percent)."'";
1178 $sql .= ", subprice='".price2num($pu_ht)."'";
1179 $sql .= ", total_ht='".price2num($total_ht)."'";
1180 $sql .= ", total_tva='".price2num($total_tva)."'";
1181 $sql .= ", total_localtax1='".price2num($total_localtax1)."'";
1182 $sql .= ", total_localtax2='".price2num($total_localtax2)."'";
1183 $sql .= ", total_ttc='".price2num($total_ttc)."'";
1184 $sql .= ", date_start_fill=".((int) $date_start_fill);
1185 $sql .= ", date_end_fill=".((int) $date_end_fill);
1186 $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : 'null');
1187 $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0);
1188 $sql .= ", info_bits=".((int) $info_bits);
1189 $sql .= ", rang=".((int) $rang);
1190 $sql .= ", special_code=".((int) $special_code);
1191 $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
1192 $sql .= ', multicurrency_subprice = '.price2num($pu_ht_devise);
1193 $sql .= ', multicurrency_total_ht = '.price2num($multicurrency_total_ht);
1194 $sql .= ', multicurrency_total_tva = '.price2num($multicurrency_total_tva);
1195 $sql .= ', multicurrency_total_ttc = '.price2num($multicurrency_total_ttc);
1196 $sql .= " WHERE rowid = ".((int) $rowid);
1197
1198 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1199 if ($this->db->query($sql)) {
1200 $this->id = $facid;
1201 $this->update_price(1);
1202 return 1;
1203 } else {
1204 $this->error = $this->db->lasterror();
1205 return -1;
1206 }
1207 }
1208 return -1;
1209 }
1210
1211
1217 public function getNextDate()
1218 {
1219 if (empty($this->date_when)) {
1220 return false;
1221 }
1222 return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency);
1223 }
1224
1230 public function isMaxNbGenReached()
1231 {
1232 $ret = false;
1233 if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) {
1234 $ret = true;
1235 }
1236 return $ret;
1237 }
1238
1245 public function strikeIfMaxNbGenReached($ret)
1246 {
1247 // Special case to strike the date
1248 return ($this->isMaxNbGenReached() ? '<strike>' : '').$ret.($this->isMaxNbGenReached() ? '</strike>' : '');
1249 }
1250
1262 public function createRecurringInvoices($restrictioninvoiceid = 0, $forcevalidation = 0, $notrigger = 0)
1263 {
1264 global $conf, $langs, $db, $user, $hookmanager;
1265
1266 $error = 0;
1267 $nb_create = 0;
1268
1269 // Load translation files required by the page
1270 $langs->loadLangs(array("main", "bills"));
1271
1272 $now = dol_now();
1273 $tmparray = dol_getdate($now);
1274 $today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); // Today is last second of current day
1275
1276 $this->output = null;
1277
1278 dol_syslog("createRecurringInvoices restrictioninvoiceid=".$restrictioninvoiceid." forcevalidation=".$forcevalidation);
1279
1280 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec';
1281 $sql .= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency
1282 $sql .= " AND (date_when IS NULL OR date_when <= '".$this->db->idate($today)."')";
1283 $sql .= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)';
1284 $sql .= ' AND suspended = 0';
1285 $sql .= ' AND entity = '.$conf->entity; // MUST STAY = $conf->entity here
1286 if ($restrictioninvoiceid > 0) {
1287 $sql .= ' AND rowid = '.((int) $restrictioninvoiceid);
1288 }
1289 $sql .= $this->db->order('entity', 'ASC');
1290 //print $sql;exit;
1291 $parameters = array(
1292 'restrictioninvoiceid' => $restrictioninvoiceid,
1293 'forcevalidation' => $forcevalidation,
1294 );
1295 $reshook = $hookmanager->executeHooks('beforeCreationOfRecurringInvoices', $parameters, $sql); // note that $sql might be modified by hooks
1296
1297 $resql = $this->db->query($sql);
1298 if ($resql) {
1299 $i = 0;
1300 $num = $this->db->num_rows($resql);
1301
1302 if ($num) {
1303 $this->output .= $langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n";
1304 } else {
1305 $this->output .= $langs->trans("NoQualifiedRecurringInvoiceTemplateFound");
1306 }
1307
1308 $saventity = $conf->entity;
1309
1310 while ($i < $num) { // Loop on each template invoice. If $num = 0, test is false at first pass.
1311 $line = $this->db->fetch_object($resql);
1312
1313 $this->db->begin();
1314
1315 $invoiceidgenerated = 0;
1316
1317 $facture = null;
1318 $facturerec = new FactureRec($this->db);
1319 $facturerec->fetch($line->rowid);
1320
1321 if ($facturerec->id > 0) {
1322 // Set entity context
1323 $conf->entity = $facturerec->entity;
1324
1325 dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity);
1326
1327 $facture = new Facture($this->db);
1328 $facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice
1329 $facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice
1330
1331 $facture->type = self::TYPE_STANDARD;
1332 $facture->brouillon = 1;
1333 $facture->statut = self::STATUS_DRAFT;
1334 $facture->status = self::STATUS_DRAFT;
1335 $facture->date = (empty($facturerec->date_when) ? $now : $facturerec->date_when); // We could also use dol_now here but we prefer date_when so invoice has real date when we would like even if we generate later.
1336 $facture->socid = $facturerec->socid;
1337 if (!empty($facturerec->fk_multicurrency)) {
1338 $facture->fk_multicurrency = $facturerec->fk_multicurrency;
1339 $facture->multicurrency_code = $facturerec->multicurrency_code;
1340 $facture->multicurrency_tx = $facturerec->multicurrency_tx;
1341 }
1342
1343 if (isset($facture->array_options) && isset($facturerec->array_options)) {
1344 foreach ($facturerec->array_options as $key => $value) {
1345 if (isset($facture->array_options[$key])) {
1346 $facture->array_options[$key] = $value;
1347 }
1348 }
1349 }
1350
1351 $invoiceidgenerated = $facture->create($user);
1352 if ($invoiceidgenerated <= 0) {
1353 $this->errors = $facture->errors;
1354 $this->error = $facture->error;
1355 $error++;
1356 }
1357
1358
1359 if (!$error && ($facturerec->auto_validate || $forcevalidation)) {
1360 $result = $facture->validate($user);
1361 if ($result <= 0) {
1362 $this->errors = $facture->errors;
1363 $this->error = $facture->error;
1364 $error++;
1365 }
1366 }
1367 if (!$error && $facturerec->generate_pdf) {
1368 // We refresh the object in order to have all necessary data (like date_lim_reglement)
1369 $facture->fetch($facture->id);
1370 $result = $facture->generateDocument($facturerec->model_pdf, $langs);
1371 if ($result <= 0) {
1372 $this->errors = $facture->errors;
1373 $this->error = $facture->error;
1374 $error++;
1375 }
1376 }
1377 if (!$error && !$notrigger) {
1378 // Call trigger
1379 $result = $facturerec->call_trigger('BILLREC_CREATEBILL', $user);
1380 if ($result < 0) {
1381 $this->errors = $facturerec->errors;
1382 $this->error = $facturerec->error;
1383 $error++;
1384 }
1385 // End call triggers
1386 }
1387 } else {
1388 $error++;
1389 $this->error = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity."\n";
1390 $this->errors[] = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity;
1391 dol_syslog("createRecurringInvoices Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity);
1392 }
1393
1394 if (!$error && $invoiceidgenerated >= 0) {
1395 $this->db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
1396 dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation");
1397 $nb_create++;
1398 $this->output .= $langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n";
1399 } else {
1400 $this->db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
1401 }
1402
1403 $parameters = array(
1404 'cpt' => $i,
1405 'total' => $num,
1406 'errorCount' => $error,
1407 'invoiceidgenerated' => $invoiceidgenerated,
1408 'facturerec' => $facturerec, // it's an object which PHP passes by "reference", so modifiable by hooks.
1409 'this' => $this, // it's an object which PHP passes by "reference", so modifiable by hooks.
1410 );
1411 $reshook = $hookmanager->executeHooks('afterCreationOfRecurringInvoice', $parameters, $facture); // note: $facture can be modified by hooks (warning: $facture can be null)
1412
1413 $i++;
1414 }
1415
1416 $conf->entity = $saventity; // Restore entity context
1417 } else {
1418 dol_print_error($this->db);
1419 }
1420
1421 $this->output = trim($this->output);
1422
1423 return $error ? $error : 0;
1424 }
1425
1438 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = '', $save_lastsearch_value = -1)
1439 {
1440 global $langs, $hookmanager;
1441
1442 $result = '';
1443
1444 $label = '<u>'.$langs->trans("RepeatableInvoice").'</u>';
1445 if (!empty($this->ref)) {
1446 $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1447 }
1448 if ($this->frequency > 0) {
1449 $label .= '<br><b>'.$langs->trans('Frequency').':</b> '.$langs->trans('FrequencyPer_'.$this->unit_frequency, $this->frequency);
1450 }
1451 if (!empty($this->date_last_gen)) {
1452 $label .= '<br><b>'.$langs->trans('DateLastGeneration').':</b> '.dol_print_date($this->date_last_gen, 'dayhour');
1453 }
1454 if ($this->frequency > 0) {
1455 if (!empty($this->date_when)) {
1456 $label .= '<br><b>'.$langs->trans('NextDateToExecution').':</b> ';
1457 $label .= (empty($this->suspended) ? '' : '<strike>').dol_print_date($this->date_when, 'day').(empty($this->suspended) ? '' : '</strike>'); // No hour for this property
1458 if (!empty($this->suspended)) {
1459 $label .= ' ('.$langs->trans("Disabled").')';
1460 }
1461 }
1462 }
1463
1464 $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$this->id;
1465
1466 if ($short) {
1467 return $url;
1468 }
1469
1470 if ($option != 'nolink') {
1471 // Add param to save lastsearch_values or not
1472 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1473 if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1474 $add_save_lastsearch_values = 1;
1475 }
1476 if ($add_save_lastsearch_values) {
1477 $url .= '&save_lastsearch_values=1';
1478 }
1479 }
1480
1481 $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1482 $linkend = '</a>';
1483
1484 $result .= $linkstart;
1485 if ($withpicto) {
1486 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1487 }
1488 if ($withpicto != 2) {
1489 $result .= $this->ref;
1490 }
1491 $result .= $linkend;
1492 global $action;
1493 $hookmanager->initHooks(array($this->element . 'dao'));
1494 $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
1495 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1496 if ($reshook > 0) {
1497 $result = $hookmanager->resPrint;
1498 } else {
1499 $result .= $hookmanager->resPrint;
1500 }
1501 return $result;
1502 }
1503
1511 public function getLibStatut($mode = 0, $alreadypaid = -1)
1512 {
1513 return $this->LibStatut($this->frequency ? 1 : 0, $this->suspended, $mode, $alreadypaid, empty($this->type) ? 0 : $this->type);
1514 }
1515
1516 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1527 public function LibStatut($recur, $status, $mode = 0, $alreadypaid = -1, $type = 0)
1528 {
1529 // phpcs:enable
1530 global $langs;
1531 $langs->load('bills');
1532
1533 $labelStatus = $langs->transnoentitiesnoconv('Active');
1534 $statusType = 'status0';
1535
1536 //print "$recur,$status,$mode,$alreadypaid,$type";
1537 if ($mode == 0) {
1538 if ($recur) {
1539 if ($status == self::STATUS_SUSPENDED) {
1540 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1541 } else {
1542 $labelStatus = $langs->transnoentitiesnoconv('Active');
1543 }
1544 } else {
1545 if ($status == self::STATUS_SUSPENDED) {
1546 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1547 } else {
1548 $labelStatus = $langs->transnoentitiesnoconv("Draft");
1549 }
1550 }
1551 } elseif ($mode == 1) {
1552 $prefix = 'Short';
1553 if ($recur) {
1554 if ($status == self::STATUS_SUSPENDED) {
1555 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1556 } else {
1557 $labelStatus = $langs->transnoentitiesnoconv('Active');
1558 }
1559 } else {
1560 if ($status == self::STATUS_SUSPENDED) {
1561 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1562 } else {
1563 $labelStatus = $langs->transnoentitiesnoconv("Draft");
1564 }
1565 }
1566 } elseif ($mode == 2) {
1567 if ($recur) {
1568 if ($status == self::STATUS_SUSPENDED) {
1569 $statusType = 'status6';
1570 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1571 } else {
1572 $statusType = 'status4';
1573 $labelStatus = $langs->transnoentitiesnoconv('Active');
1574 }
1575 } else {
1576 if ($status == self::STATUS_SUSPENDED) {
1577 $statusType = 'status6';
1578 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1579 } else {
1580 $statusType = 'status0';
1581 $labelStatus = $langs->transnoentitiesnoconv('Draft');
1582 }
1583 }
1584 } elseif ($mode == 3) {
1585 if ($recur) {
1586 $prefix = 'Short';
1587 if ($status == self::STATUS_SUSPENDED) {
1588 $statusType = 'status6';
1589 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1590 } else {
1591 $statusType = 'status4';
1592 $labelStatus = $langs->transnoentitiesnoconv('Active');
1593 }
1594 } else {
1595 if ($status == self::STATUS_SUSPENDED) {
1596 $statusType = 'status6';
1597 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1598 } else {
1599 $statusType = 'status0';
1600 $labelStatus = $langs->transnoentitiesnoconv('Draft');
1601 }
1602 }
1603 } elseif ($mode == 4) {
1604 $prefix = '';
1605 if ($recur) {
1606 if ($status == self::STATUS_SUSPENDED) {
1607 $statusType = 'status6';
1608 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1609 } else {
1610 $statusType = 'status4';
1611 $labelStatus = $langs->transnoentitiesnoconv('Active');
1612 }
1613 } else {
1614 if ($status == self::STATUS_SUSPENDED) {
1615 $statusType = 'status6';
1616 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1617 } else {
1618 $statusType = 'status0';
1619 $labelStatus = $langs->transnoentitiesnoconv('Draft');
1620 }
1621 }
1622 } elseif ($mode == 5 || $mode == 6) {
1623 $prefix = '';
1624 if ($mode == 5) {
1625 $prefix = 'Short';
1626 }
1627 if ($recur) {
1628 if ($status == self::STATUS_SUSPENDED) {
1629 $statusType = 'status6';
1630 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1631 } else {
1632 $statusType = 'status4';
1633 $labelStatus = $langs->transnoentitiesnoconv('Active');
1634 }
1635 } else {
1636 if ($status == self::STATUS_SUSPENDED) {
1637 $statusType = 'status6';
1638 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1639 } else {
1640 $statusType = 'status0';
1641 $labelStatus = $langs->transnoentitiesnoconv('Draft');
1642 }
1643 }
1644 }
1645
1646 $labelStatusShort = $labelStatus;
1647
1648 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
1649 }
1650
1659 public function initAsSpecimen($option = '')
1660 {
1661 global $user, $langs, $conf;
1662
1663 $now = dol_now();
1664 $arraynow = dol_getdate($now);
1665 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
1666
1667 // Load array of products prodids
1668 $num_prods = 0;
1669 $prodids = array();
1670
1671 $sql = "SELECT rowid";
1672 $sql .= " FROM ".MAIN_DB_PREFIX."product";
1673 $sql .= " WHERE entity IN (".getEntity('product').")";
1674 $sql .= $this->db->plimit(100);
1675
1676 $resql = $this->db->query($sql);
1677 if ($resql) {
1678 $num_prods = $this->db->num_rows($resql);
1679 $i = 0;
1680 while ($i < $num_prods) {
1681 $i++;
1682 $row = $this->db->fetch_row($resql);
1683 $prodids[$i] = $row[0];
1684 }
1685 }
1686
1687 // Initialize parameters
1688 $this->id = 0;
1689 $this->ref = 'SPECIMEN';
1690 $this->title = 'SPECIMEN';
1691 $this->specimen = 1;
1692 $this->socid = 1;
1693 $this->date = $nownotime;
1694 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
1695 $this->cond_reglement_id = 1;
1696 $this->cond_reglement_code = 'RECEP';
1697 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
1698 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
1699 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
1700 $this->note_public = 'This is a comment (public)';
1701 $this->note_private = 'This is a comment (private)';
1702 $this->note = 'This is a comment (private)';
1703 $this->fk_incoterms = 0;
1704 $this->location_incoterms = '';
1705
1706 if (empty($option) || $option != 'nolines') {
1707 // Lines
1708 $nbp = 5;
1709 $xnbp = 0;
1710 while ($xnbp < $nbp) {
1711 $line = new FactureLigne($this->db);
1712 $line->desc = $langs->trans("Description")." ".$xnbp;
1713 $line->qty = 1;
1714 $line->subprice = 100;
1715 $line->tva_tx = 19.6;
1716 $line->localtax1_tx = 0;
1717 $line->localtax2_tx = 0;
1718 $line->remise_percent = 0;
1719 if ($xnbp == 1) { // Qty is negative (product line)
1720 $prodid = mt_rand(1, $num_prods);
1721 $line->fk_product = $prodids[$prodid];
1722 $line->qty = -1;
1723 $line->total_ht = -100;
1724 $line->total_ttc = -119.6;
1725 $line->total_tva = -19.6;
1726 } elseif ($xnbp == 2) { // UP is negative (free line)
1727 $line->subprice = -100;
1728 $line->total_ht = -100;
1729 $line->total_ttc = -119.6;
1730 $line->total_tva = -19.6;
1731 $line->remise_percent = 0;
1732 } elseif ($xnbp == 3) { // Discount is 50% (product line)
1733 $prodid = mt_rand(1, $num_prods);
1734 $line->fk_product = $prodids[$prodid];
1735 $line->total_ht = 50;
1736 $line->total_ttc = 59.8;
1737 $line->total_tva = 9.8;
1738 $line->remise_percent = 50;
1739 } else // (product line)
1740 {
1741 $prodid = mt_rand(1, $num_prods);
1742 $line->fk_product = $prodids[$prodid];
1743 $line->total_ht = 100;
1744 $line->total_ttc = 119.6;
1745 $line->total_tva = 19.6;
1746 $line->remise_percent = 00;
1747 }
1748
1749 $this->lines[$xnbp] = $line;
1750 $xnbp++;
1751
1752 $this->total_ht += $line->total_ht;
1753 $this->total_tva += $line->total_tva;
1754 $this->total_ttc += $line->total_ttc;
1755 }
1756 $this->revenuestamp = 0;
1757
1758 // Add a line "offered"
1759 $line = new FactureLigne($this->db);
1760 $line->desc = $langs->trans("Description")." (offered line)";
1761 $line->qty = 1;
1762 $line->subprice = 100;
1763 $line->tva_tx = 19.6;
1764 $line->localtax1_tx = 0;
1765 $line->localtax2_tx = 0;
1766 $line->remise_percent = 100;
1767 $line->total_ht = 0;
1768 $line->total_ttc = 0; // 90 * 1.196
1769 $line->total_tva = 0;
1770 $prodid = mt_rand(1, $num_prods);
1771 $line->fk_product = $prodids[$prodid];
1772
1773 $this->lines[$xnbp] = $line;
1774 $xnbp++;
1775 }
1776
1777 $this->usenewprice = 0;
1778 }
1779
1788 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
1789 {
1790 $tables = array(
1791 'facture_rec'
1792 );
1793
1794 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
1795 }
1796
1805 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
1806 {
1807 $tables = array(
1808 'facturedet_rec'
1809 );
1810
1811 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
1812 }
1813
1822 public function setFrequencyAndUnit($frequency, $unit, $notrigger = 0)
1823 {
1824 global $user;
1825
1826 if (!$this->table_element) {
1827 dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with property table_element not defined", LOG_ERR);
1828 return -1;
1829 }
1830
1831 if (!empty($frequency) && empty($unit)) {
1832 dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with params frequency defined but unit not defined", LOG_ERR);
1833 return -2;
1834 }
1835
1836 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1837 $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null');
1838 if (!empty($unit)) {
1839 $sql .= ', unit_frequency = \''.$this->db->escape($unit).'\'';
1840 }
1841 $sql .= " WHERE rowid = ".((int) $this->id);
1842
1843 dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG);
1844 if ($this->db->query($sql)) {
1845 $this->frequency = $frequency;
1846 if (!empty($unit)) {
1847 $this->unit_frequency = $unit;
1848 }
1849
1850 if (!$notrigger) {
1851 // Call trigger
1852 $result = $this->call_trigger('BILLREC_MODIFY', $user);
1853 if ($result < 0) {
1854 return $result;
1855 }
1856 // End call triggers
1857 }
1858
1859 return 1;
1860 } else {
1861 dol_print_error($this->db);
1862 return -1;
1863 }
1864 }
1865
1874 public function setNextDate($date, $increment_nb_gen_done = 0, $notrigger = 0)
1875 {
1876
1877 global $user;
1878
1879 if (!$this->table_element) {
1880 dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR);
1881 return -1;
1882 }
1883 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1884 $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null");
1885 if ($increment_nb_gen_done > 0) {
1886 $sql .= ', nb_gen_done = nb_gen_done + 1';
1887 }
1888 $sql .= " WHERE rowid = ".((int) $this->id);
1889
1890 dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG);
1891 if ($this->db->query($sql)) {
1892 $this->date_when = $date;
1893 if ($increment_nb_gen_done > 0) {
1894 $this->nb_gen_done++;
1895 }
1896
1897 if (!$notrigger) {
1898 // Call trigger
1899 $result = $this->call_trigger('BILLREC_MODIFY', $user);
1900 if ($result < 0) {
1901 return $result;
1902 }
1903 // End call triggers
1904 }
1905 return 1;
1906 } else {
1907 dol_print_error($this->db);
1908 return -1;
1909 }
1910 }
1911
1919 public function setMaxPeriod($nb, $notrigger = 0)
1920 {
1921
1922 global $user;
1923
1924 if (!$this->table_element) {
1925 dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR);
1926 return -1;
1927 }
1928
1929 if (empty($nb)) {
1930 $nb = 0;
1931 }
1932
1933 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1934 $sql .= ' SET nb_gen_max = '.((int) $nb);
1935 $sql .= " WHERE rowid = ".((int) $this->id);
1936
1937 dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG);
1938 if ($this->db->query($sql)) {
1939 $this->nb_gen_max = $nb;
1940
1941 if (!$notrigger) {
1942 // Call trigger
1943 $result = $this->call_trigger('BILLREC_MODIFY', $user);
1944 if ($result < 0) {
1945 return $result;
1946 }
1947 // End call triggers
1948 }
1949
1950 return 1;
1951 } else {
1952 dol_print_error($this->db);
1953 return -1;
1954 }
1955 }
1956
1964 public function setAutoValidate($validate, $notrigger = 0)
1965 {
1966 global $user;
1967
1968 if (!$this->table_element) {
1969 dol_syslog(get_class($this)."::setAutoValidate was called on objet with property table_element not defined", LOG_ERR);
1970 return -1;
1971 }
1972
1973 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1974 $sql .= ' SET auto_validate = '.((int) $validate);
1975 $sql .= " WHERE rowid = ".((int) $this->id);
1976
1977 dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG);
1978 if ($this->db->query($sql)) {
1979 $this->auto_validate = $validate;
1980
1981 if (!$notrigger) {
1982 // Call trigger
1983 $result = $this->call_trigger('BILLREC_MODIFY', $user);
1984 if ($result < 0) {
1985 return $result;
1986 }
1987 // End call triggers
1988 }
1989
1990 return 1;
1991 } else {
1992 dol_print_error($this->db);
1993 return -1;
1994 }
1995 }
1996
2004 public function setGeneratePdf($validate, $notrigger = 0)
2005 {
2006 global $user;
2007
2008 if (!$this->table_element) {
2009 dol_syslog(get_class($this)."::setGeneratePdf was called on objet with property table_element not defined", LOG_ERR);
2010 return -1;
2011 }
2012
2013 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2014 $sql .= ' SET generate_pdf = '.((int) $validate);
2015 $sql .= " WHERE rowid = ".((int) $this->id);
2016
2017 dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG);
2018 if ($this->db->query($sql)) {
2019 $this->generate_pdf = $validate;
2020
2021 if (!$notrigger) {
2022 // Call trigger
2023 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2024 if ($result < 0) {
2025 return $result;
2026 }
2027 // End call triggers
2028 }
2029
2030 return 1;
2031 } else {
2032 dol_print_error($this->db);
2033 return -1;
2034 }
2035 }
2036
2044 public function setModelPdf($model, $notrigger = 0)
2045 {
2046 global $user;
2047 if (!$this->table_element) {
2048 dol_syslog(get_class($this)."::setModelPdf was called on objet with property table_element not defined", LOG_ERR);
2049 return -1;
2050 }
2051
2052 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2053 $sql .= " SET modelpdf = '".$this->db->escape($model)."'";
2054 $sql .= " WHERE rowid = ".((int) $this->id);
2055
2056 dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG);
2057 if ($this->db->query($sql)) {
2058 $this->model_pdf = $model;
2059
2060 if (!$notrigger) {
2061 // Call trigger
2062 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2063 if ($result < 0) {
2064 return $result;
2065 }
2066 // End call triggers
2067 }
2068
2069 return 1;
2070 } else {
2071 dol_print_error($this->db);
2072 return -1;
2073 }
2074 }
2075}
2076
2077
2078
2084{
2088 public $element = 'facturedetrec';
2089
2093 public $table_element = 'facturedet_rec';
2094
2095
2096 public $fk_product_fournisseur_price;
2097 public $fk_fournprice; // For backward compatibility
2098
2099 public $rang;
2100 //public $situation_percent; // Not supported on recurring invoice line
2101
2102 public $desc;
2103 public $description;
2104
2105 public $fk_product_type; // Use instead product_type
2106
2107 public $fk_contract_line;
2108
2109
2117 public function delete(User $user, $notrigger = false)
2118 {
2119 $error = 0;
2120
2121 $this->db->begin();
2122
2123 if (!$error) {
2124 if (!$notrigger) {
2125 // Call triggers
2126 $result = $this->call_trigger('LINEBILLREC_DELETE', $user);
2127 if ($result < 0) {
2128 $error++;
2129 } // Do also here what you must do to rollback action if trigger fail
2130 // End call triggers
2131 }
2132 }
2133
2134 if (!$error) {
2135 $result = $this->deleteExtraFields();
2136 if ($result < 0) {
2137 $error++;
2138 }
2139 }
2140
2141 if (!$error) {
2142 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
2143
2144 $res = $this->db->query($sql);
2145 if (!$res) {
2146 $error++;
2147 $this->errors[] = $this->db->lasterror();
2148 }
2149 }
2150
2151 // Commit or rollback
2152 if ($error) {
2153 $this->db->rollback();
2154 return -1;
2155 } else {
2156 $this->db->commit();
2157 return 1;
2158 }
2159 }
2160
2161
2168 public function fetch($rowid)
2169 {
2170 $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
2171 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
2172 $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,';
2173 $sql .= ' l.rang, l.special_code,';
2174 $sql .= ' l.fk_unit, l.fk_contract_line,';
2175 $sql .= ' l.import_key, l.fk_multicurrency,';
2176 $sql .= ' l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2177 $sql .= ' l.buy_price_ht, l.fk_product_fournisseur_price,';
2178 $sql .= ' l.fk_user_author, l.fk_user_modif,';
2179 $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2180 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
2181 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
2182 $sql .= ' WHERE l.rowid = '.((int) $rowid);
2183 $sql .= ' ORDER BY l.rang';
2184
2185 dol_syslog('FactureRec::fetch', LOG_DEBUG);
2186 $result = $this->db->query($sql);
2187 if ($result) {
2188 $objp = $this->db->fetch_object($result);
2189
2190 $this->id = $objp->rowid;
2191 $this->label = $objp->custom_label; // Label line
2192 $this->desc = $objp->description; // Description line
2193 $this->description = $objp->description; // Description line
2194 $this->product_type = $objp->product_type; // Type of line
2195 $this->ref = $objp->product_ref; // Ref product
2196 $this->product_ref = $objp->product_ref; // Ref product
2197 $this->libelle = $objp->product_label; // deprecated
2198 $this->product_label = $objp->product_label; // Label product
2199 $this->product_desc = $objp->product_desc; // Description product
2200 $this->fk_product_type = $objp->fk_product_type; // Type of product
2201 $this->qty = $objp->qty;
2202 $this->price = $objp->price;
2203 $this->subprice = $objp->subprice;
2204 $this->fk_facture = $objp->fk_facture;
2205 $this->vat_src_code = $objp->vat_src_code;
2206 $this->tva_tx = $objp->tva_tx;
2207 $this->localtax1_tx = $objp->localtax1_tx;
2208 $this->localtax2_tx = $objp->localtax2_tx;
2209 $this->localtax1_type = $objp->localtax1_type;
2210 $this->localtax2_type = $objp->localtax2_type;
2211 $this->remise_percent = $objp->remise_percent;
2212 //$this->fk_remise_except = $objp->fk_remise_except;
2213 $this->fk_product = $objp->fk_product;
2214 $this->date_start_fill = $objp->date_start_fill;
2215 $this->date_end_fill = $objp->date_end_fill;
2216 $this->info_bits = $objp->info_bits;
2217 $this->total_ht = $objp->total_ht;
2218 $this->total_tva = $objp->total_tva;
2219 $this->total_ttc = $objp->total_ttc;
2220 //$this->code_ventilation = $objp->fk_code_ventilation;
2221 $this->rang = $objp->rang;
2222 $this->special_code = $objp->special_code;
2223 $this->fk_unit = $objp->fk_unit;
2224 $this->fk_contract_line = $objp->fk_contract_line;
2225 $this->import_key = $objp->import_key;
2226 $this->fk_multicurrency = $objp->fk_multicurrency;
2227 $this->multicurrency_code = $objp->multicurrency_code;
2228 $this->multicurrency_subprice = $objp->multicurrency_subprice;
2229 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
2230 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
2231 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2232
2233 $this->buy_price_ht = $objp->buy_price_ht;
2234
2235 $this->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
2236 $this->fk_user_author = $objp->fk_user_author;
2237 $this->fk_user_modif = $objp->fk_user_modif;
2238
2239 $this->db->free($result);
2240 return 1;
2241 } else {
2242 $this->error = $this->db->lasterror();
2243 return -3;
2244 }
2245 }
2246
2247
2255 public function update(User $user, $notrigger = 0)
2256 {
2257 global $conf;
2258
2259 $error = 0;
2260
2261 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2262
2263 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET";
2264 $sql .= " fk_facture = ".((int) $this->fk_facture);
2265 $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
2266 $sql .= ", description='".$this->db->escape($this->desc)."'";
2267 $sql .= ", price=".price2num($this->price);
2268 $sql .= ", qty=".price2num($this->qty);
2269 $sql .= ", tva_tx=".price2num($this->tva_tx);
2270 $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'";
2271 $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
2272 $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
2273 $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
2274 $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
2275 $sql .= ", fk_product=".($this->fk_product > 0 ? $this->fk_product : "null");
2276 $sql .= ", product_type=".((int) $this->product_type);
2277 $sql .= ", remise_percent=".price2num($this->remise_percent);
2278 $sql .= ", subprice=".price2num($this->subprice);
2279 $sql .= ", info_bits=".price2num($this->info_bits);
2280 $sql .= ", date_start_fill=".(int) $this->date_start_fill;
2281 $sql .= ", date_end_fill=".(int) $this->date_end_fill;
2282 if (empty($this->skip_update_total)) {
2283 $sql .= ", total_ht=".price2num($this->total_ht);
2284 $sql .= ", total_tva=".price2num($this->total_tva);
2285 $sql .= ", total_localtax1=".price2num($this->total_localtax1);
2286 $sql .= ", total_localtax2=".price2num($this->total_localtax2);
2287 $sql .= ", total_ttc=".price2num($this->total_ttc);
2288 }
2289 $sql .= ", rang=".((int) $this->rang);
2290 $sql .= ", special_code=".((int) $this->special_code);
2291 $sql .= ", fk_unit=".($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null");
2292 $sql .= ", fk_contract_line=".($this->fk_contract_line ? $this->fk_contract_line : "null");
2293 $sql .= " WHERE rowid = ".((int) $this->id);
2294
2295 $this->db->begin();
2296
2297 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
2298
2299 $resql = $this->db->query($sql);
2300 if ($resql) {
2301 if (!$error) {
2302 $result = $this->insertExtraFields();
2303 if ($result < 0) {
2304 $error++;
2305 }
2306 }
2307
2308 if (!$error && !$notrigger) {
2309 // Call trigger
2310 $result = $this->call_trigger('LINEBILLREC_MODIFY', $user);
2311 if ($result < 0) {
2312 $error++;
2313 }
2314 // End call triggers
2315 }
2316
2317 if ($error) {
2318 $this->db->rollback();
2319 return -2;
2320 } else {
2321 $this->db->commit();
2322 return 1;
2323 }
2324 } else {
2325 $this->error = $this->db->lasterror();
2326 $this->db->rollback();
2327 return -2;
2328 }
2329 }
2330}
$object ref
Definition info.php:78
Superclass for invoices classes.
const TYPE_STANDARD
Standard invoice.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
const STATUS_DRAFT
Draft status.
Parent class of all other business classes for details of elements (invoices, contracts,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
update_price($exclspec=0, $roundingadjust='none', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
Class to manage invoices.
Class to manage invoice lines.
Class to manage invoice lines of templates.
fetch($rowid)
Get line of template invoice.
update(User $user, $notrigger=0)
Update a line to invoice_rec.
Class to manage invoice templates.
create($user, $facid, $notrigger=0)
Create a predefined invoice.
setFrequencyAndUnit($frequency, $unit, $notrigger=0)
Update frequency and unit.
getLibStatut($mode=0, $alreadypaid=-1)
Return label of object status.
LibStatut($recur, $status, $mode=0, $alreadypaid=-1, $type=0)
Return label of a status.
fetch_lines()
Get lines of template invoices into this->lines.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0, $date_start_fill=0, $date_end_fill=0, $fk_fournprice=null, $pa_ht=0)
Add a line to invoice.
getLinesArray()
Create an array of invoice lines.
updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $date_start_fill=0, $date_end_fill=0, $fk_fournprice=null, $pa_ht=0)
Update a line to invoice.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip='', $save_lastsearch_value=-1)
Return clicable name (with picto eventually)
isMaxNbGenReached()
Return if maximum number of generation is reached.
setModelPdf($model, $notrigger=0)
Update the model for documents.
__construct(DoliDB $db)
Constructor.
setNextDate($date, $increment_nb_gen_done=0, $notrigger=0)
Update the next date of execution.
setAutoValidate($validate, $notrigger=0)
Update the auto validate flag of invoice.
initAsSpecimen($option='')
Initialise an instance with random values.
setMaxPeriod($nb, $notrigger=0)
Update the maximum period.
update(User $user, $notrigger=0)
Update a line invoice_rec.
fetch($rowid, $ref='', $ref_ext='')
Load object and lines.
strikeIfMaxNbGenReached($ret)
Format string to output with by striking the string if max number of generation was reached.
setGeneratePdf($validate, $notrigger=0)
Update the auto generate documents.
static replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a product id with another one.
getNextDate()
Return the next date of.
createRecurringInvoices($restrictioninvoiceid=0, $forcevalidation=0, $notrigger=0)
Create all recurrents invoices (for all entities if multicompany is used).
Class to manage products or services.
Class to manage Dolibarr users.
print $langs trans("Ref").' m m m statut
Definition index.php:152
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:123
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:86
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:120