dolibarr 25.0.0-alpha
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-2026 Frédéric France <frederic.france@free.fr>
10 * Copyright (C) 2023 Nick Fragoulis
11 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
12 * Copyright (C) 2026 Joris Le Blansch <ping@apio.systems>
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26 */
27
34require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
35require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
36require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
37require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
38require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/factureligne.class.php';
39require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
40require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
41
42
47{
48 use CommonSubtotal;
49
54 public $TRIGGER_PREFIX = 'BILLREC';
55
59 public $element = 'facturerec';
60
64 public $table_element = 'facture_rec';
65
69 public $table_element_line = 'facturedet_rec';
70
74 public $fk_element = 'fk_facture';
75
79 public $picto = 'bill';
80
84 protected $table_ref_field = 'titre';
85
89 public $title;
90
95 public $titre;
96
100 public $multicurrency_subprice;
104 public $socid;
108 public $number;
112 public $date;
113
119 public $total;
120
126 public $tva;
127
131 public $date_last_gen;
135 public $date_when;
139 public $nb_gen_done;
143 public $nb_gen_max;
144
148 public $user_author;
149
153 public $frequency;
154
158 public $unit_frequency;
159
163 public $rule_for_lines_dates;
164
168 public $rang;
169
173 public $special_code;
174
178 public $usenewprice = 0;
179
183 public $date_lim_reglement;
187 public $cond_reglement_code; // Code in llx_c_paiement
191 public $mode_reglement_code; // Code in llx_c_paiement
192
196 public $fk_societe_rib;
197
201 public $suspended; // status
202
206 public $auto_validate; // 0 to create in draft, 1 to create and validate the new invoice, 2 to create, validate and sending the new invoice
207
211 public $fk_email_template; // Email template for auto sending invoices
212
216 public $generate_pdf; // 1 to generate PDF on invoice generation (default)
217
221 public $usenewcurrencyrate;
222
223
224
225 const PAYMENTCODETOEDITSOCIETERIB = "PRE";
226
227
252 // BEGIN MODULEBUILDER PROPERTIES
256 public $fields = array(
257 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
258 'titre' => array('type' => 'varchar(100)', 'label' => 'Titre', 'enabled' => 1, 'showoncombobox' => 1, 'visible' => -1, 'position' => 15),
259 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20, 'index' => 1),
260 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 25),
261 'subtype' => array('type' => 'smallint(6)', 'label' => 'InvoiceSubtype', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 30),
262 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 35),
263 'total_tva' => array('type' => 'double(24,8)', 'label' => 'Tva', 'enabled' => 1, 'visible' => -1, 'position' => 55, 'isameasure' => 1),
264 'localtax1' => array('type' => 'double(24,8)', 'label' => 'Localtax1', 'enabled' => 1, 'visible' => -1, 'position' => 60, 'isameasure' => 1),
265 'localtax2' => array('type' => 'double(24,8)', 'label' => 'Localtax2', 'enabled' => 1, 'visible' => -1, 'position' => 65, 'isameasure' => 1),
266 'total_ht' => array('type' => 'double(24,8)', 'label' => 'Total', 'enabled' => 1, 'visible' => -1, 'position' => 70, 'isameasure' => 1),
267 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'Total ttc', 'enabled' => 1, 'visible' => -1, 'position' => 75, 'isameasure' => 1),
268 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 80),
269 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 85),
270 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'position' => 90),
271 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 95),
272 'date_lim_reglement' => array('type' => 'date', 'label' => 'Date lim reglement', 'enabled' => 1, 'visible' => -1, 'position' => 100),
273 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 105),
274 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 110),
275 'modelpdf' => array('type' => 'varchar(255)', 'label' => 'Modelpdf', 'enabled' => 1, 'visible' => -1, 'position' => 115),
276 'date_when' => array('type' => 'datetime', 'label' => 'Date when', 'enabled' => 1, 'visible' => -1, 'position' => 130),
277 'date_last_gen' => array('type' => 'datetime', 'label' => 'Date last gen', 'enabled' => 1, 'visible' => -1, 'position' => 135),
278 'nb_gen_done' => array('type' => 'integer', 'label' => 'Nb gen done', 'enabled' => 1, 'visible' => -1, 'position' => 140),
279 'nb_gen_max' => array('type' => 'integer', 'label' => 'Nb gen max', 'enabled' => 1, 'visible' => -1, 'position' => 145),
280 'frequency' => array('type' => 'integer', 'label' => 'Frequency', 'enabled' => 1, 'visible' => -1, 'position' => 150),
281 'unit_frequency' => array('type' => 'varchar(2)', 'label' => 'UnitFrequency', 'enabled' => 1, 'visible' => -1, 'position' => 152),
282 'rule_for_lines_dates' => array('type' => 'varchar(255)', 'label' => 'RuleForLinesDates', 'enabled' => 'getDolGlobalInt("FACTUREREC_SUPPORT_RULE_FOR_LINES")', 'visible' => 1, 'position' => 153, 'arrayofkeyval' => array('prepaid' => "Prepaid", 'postpaid' => "Postpaid"), 'default' => 'prepaid'),
283 'usenewprice' => array('type' => 'integer', 'label' => 'UseNewPrice', 'enabled' => 1, 'visible' => 0, 'position' => 155),
284 'revenuestamp' => array('type' => 'double(24,8)', 'label' => 'RevenueStamp', 'enabled' => 1, 'visible' => -1, 'position' => 160, 'isameasure' => 1),
285 'auto_validate' => array('type' => 'integer', 'label' => 'Auto validate', 'enabled' => 1, 'visible' => -1, 'position' => 165),
286 'fk_email_template' => array('type' => 'integer:CEmailTemplate:core/class/cemailtemplate.class.php', 'label' => "Modèle d'e-mail pour l'envoi automatique", 'enabled' => 1, 'visible' => -1, 'position' => 167),
287 'generate_pdf' => array('type' => 'integer', 'label' => 'Generate pdf', 'enabled' => 1, 'visible' => -1, 'position' => 170),
288 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 175),
289 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 180),
290 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'Multicurrency code', 'enabled' => 1, 'visible' => -1, 'position' => 185),
291 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'Multicurrency tx', 'enabled' => 1, 'visible' => -1, 'position' => 190, 'isameasure' => 1),
292 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total ht', 'enabled' => 1, 'visible' => -1, 'position' => 195, 'isameasure' => 1),
293 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total tva', 'enabled' => 1, 'visible' => -1, 'position' => 200, 'isameasure' => 1),
294 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'Multicurrency total ttc', 'enabled' => 1, 'visible' => -1, 'position' => 205, 'isameasure' => 1),
295 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 210),
296 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 215),
297 'suspended' => array('type' => 'integer', 'label' => 'Suspended', 'enabled' => 1, 'visible' => -1, 'position' => 225),
298 'fk_societe_rib' => array('type' => 'integer', 'label' => 'RIB', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 175),
299 );
300 // END MODULEBUILDER PROPERTIES
301
302 const STATUS_NOTSUSPENDED = 0;
303 const STATUS_SUSPENDED = 1;
304
305
306
312 public function __construct(DoliDB $db)
313 {
314 $this->db = $db;
315 }
316
326 public function create($user, $facid, $notrigger = 0, $onlylines = array())
327 {
328 global $conf;
329
330 $error = 0;
331 $now = dol_now();
332
333 // Clean parameters
334 $this->titre = trim(isset($this->titre) ? $this->titre : $this->title); // deprecated
335 $this->title = trim($this->title);
336 $this->usenewprice = empty($this->usenewprice) ? 0 : $this->usenewprice;
337 if (empty($this->suspended)) {
338 $this->suspended = 0;
339 }
340 if (empty($this->rule_for_lines_dates)) {
341 $this->rule_for_lines_dates = 'prepaid';
342 }
343
344 // No frequency defined then no next date to execution
345 if (empty($this->frequency)) {
346 $this->frequency = 0;
347 $this->date_when = null;
348 }
349
350 $this->frequency = abs($this->frequency);
351 $this->nb_gen_done = 0;
352 $this->nb_gen_max = empty($this->nb_gen_max) ? 0 : $this->nb_gen_max;
353 $this->auto_validate = empty($this->auto_validate) ? 0 : $this->auto_validate;
354 $this->generate_pdf = empty($this->generate_pdf) ? 0 : $this->generate_pdf;
355
356 $this->db->begin();
357
358 // Load invoice template
359 $facsrc = new Facture($this->db);
360 $result = $facsrc->fetch($facid);
361 if ($result > 0) {
362 $this->socid = $facsrc->socid;
363
364 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_rec (";
365 $sql .= "titre";
366 $sql .= ", fk_soc";
367 $sql .= ", subtype";
368 $sql .= ", entity";
369 $sql .= ", datec";
370 $sql .= ", amount";
371 //$sql .= ", remise";
372 $sql .= ", note_private";
373 $sql .= ", note_public";
374 $sql .= ", modelpdf";
375 $sql .= ", fk_user_author";
376 $sql .= ", fk_projet";
377 $sql .= ", fk_account";
378 $sql .= ", fk_cond_reglement";
379 $sql .= ", fk_mode_reglement";
380 $sql .= ", usenewprice";
381 $sql .= ", frequency";
382 $sql .= ", unit_frequency";
383 $sql .= ", date_when";
384 $sql .= ", date_last_gen";
385 $sql .= ", nb_gen_done";
386 $sql .= ", nb_gen_max";
387 $sql .= ", auto_validate";
388 $sql .= ", fk_email_template";
389 $sql .= ", generate_pdf";
390 $sql .= ", fk_multicurrency";
391 $sql .= ", multicurrency_code";
392 $sql .= ", multicurrency_tx";
393 $sql .= ", suspended";
394 $sql .= ", fk_societe_rib";
395 $sql .= ", rule_for_lines_dates";
396 $sql .= ") VALUES (";
397 $sql .= "'".$this->db->escape($this->titre ? $this->titre : $this->title)."'";
398 $sql .= ", ".((int) $this->socid);
399 $sql .= ", ".(isset($this->subtype) ? (int) $this->subtype : "null");
400 $sql .= ", ".((int) $conf->entity);
401 $sql .= ", '".$this->db->idate($now)."'";
402 $sql .= ", ".(!empty($facsrc->total_ttc) ? ((float) $facsrc->total_ttc) : '0');
403 $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
404 $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
405 $sql .= ", ".(!empty($this->model_pdf) ? ("'".$this->db->escape($this->model_pdf)."'") : "NULL");
406 $sql .= ", ".((int) $user->id);
407 $sql .= ", ".(!empty($this->fk_project) ? ((int) $this->fk_project) : "null");
408 $sql .= ", ".(!empty($facsrc->fk_account) ? ((int) $facsrc->fk_account) : "null");
409 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
410 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
411 $sql .= ", ".((int) $this->usenewprice);
412 $sql .= ", ".((int) $this->frequency);
413 $sql .= ", '".$this->db->escape($this->unit_frequency)."'";
414 $sql .= ", ".(!empty($this->date_when) ? "'".$this->db->idate($this->date_when)."'" : 'NULL');
415 $sql .= ", ".(!empty($this->date_last_gen) ? "'".$this->db->idate($this->date_last_gen)."'" : 'NULL');
416 $sql .= ", ".((int) $this->nb_gen_done);
417 $sql .= ", ".((int) $this->nb_gen_max);
418 $sql .= ", ".((int) $this->auto_validate);
419 $sql .= ", ".((int) $this->fk_email_template);
420 $sql .= ", ".((int) $this->generate_pdf);
421 $sql .= ", ".((int) $facsrc->fk_multicurrency);
422 $sql .= ", '".$this->db->escape($facsrc->multicurrency_code)."'";
423 $sql .= ", ".((float) $facsrc->multicurrency_tx);
424 $sql .= ", ".((int) $this->suspended);
425 $sql .= ", ".(!empty($this->fk_societe_rib) ? ((int) $this->fk_societe_rib) : 'NULL');
426 $sql .= ", '".$this->db->escape($this->rule_for_lines_dates)."'";
427 $sql .= ")";
428
429 if ($this->db->query($sql)) {
430 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."facture_rec");
431
432 // Fields used into addline later
433 $this->fk_multicurrency = $facsrc->fk_multicurrency;
434 $this->multicurrency_code = $facsrc->multicurrency_code;
435 $this->multicurrency_tx = $facsrc->multicurrency_tx;
436
437 // Add lines
438 $fk_parent_line = 0;
439
440 $num = count($facsrc->lines);
441 for ($i = 0; $i < $num; $i++) {
442 $facline = $facsrc->lines[$i];
443 '@phan-var-force FactureLigneRec $facline';
444 if (!empty($onlylines) && !in_array($facline->id, $onlylines)) {
445 continue; // Skip unselected lines
446 }
447
448 // Reset fk_parent_line for no child products and special product
449 if (($facline->product_type != 9 && empty($facline->fk_parent_line)) || $facline->product_type == 9) {
450 $fk_parent_line = 0;
451 }
452
453 $tva_tx = $facline->tva_tx;
454 if (!empty($facline->vat_src_code) && !preg_match('/\‍(/', (string) $tva_tx)) {
455 $tva_tx .= ' ('.$facline->vat_src_code.')';
456 }
457
458 $default_start_fill = getDolGlobalInt('INVOICEREC_SET_AUTOFILL_DATE_START');
459 $default_end_fill = getDolGlobalInt('INVOICEREC_SET_AUTOFILL_DATE_END');
460
461 $result_insert = $this->addline(
462 $facline->desc,
463 $facline->subprice,
464 $facline->qty,
465 $tva_tx,
466 $facline->localtax1_tx,
467 $facline->localtax2_tx,
468 $facline->fk_product,
469 $facline->remise_percent,
470 'HT',
471 $facline->info_bits,
472 0,
473 0,
474 $facline->product_type,
475 $facline->rang,
476 $facline->special_code,
477 $facline->label,
478 $facline->fk_unit,
479 $facline->multicurrency_subprice,
480 $default_start_fill,
481 $default_end_fill,
482 0,
483 $facline->pa_ht,
484 $fk_parent_line
485 );
486
487 // Defined the new fk_parent_line
488 if ($result_insert > 0 && $facline->product_type == 9) {
489 $fk_parent_line = $result_insert;
490 }
491
492 if ($result_insert < 0) {
493 $error++;
494 } else {
495 $objectline = new FactureLigneRec($this->db);
496
497 $result2 = $objectline->fetch($result_insert);
498 if ($result2 > 0) {
499 // Extrafields
500 if (method_exists($facline, 'fetch_optionals')) {
501 $facline->fetch_optionals($facline->id);
502 $objectline->array_options = $facline->array_options;
503 }
504
505 $result = $objectline->insertExtraFields();
506 if ($result < 0) {
507 $error++;
508 }
509
510 $objectline->extraparams = $facline->extraparams;
511 $result = $objectline->setExtraParameters();
512 if ($result < 0) {
513 $error++;
514 }
515 } elseif ($result2 < 0) {
516 $this->errors[] = $objectline->error;
517 $error++;
518 }
519 }
520 }
521
522 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
523 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
524 }
525
526 // Add object linked
527 if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
528 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
529 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, ...))
530 foreach ($tmp_origin_id as $origin_id) {
531 $ret = $this->add_object_linked($origin, $origin_id);
532 if (!$ret) {
533 $this->error = $this->db->lasterror();
534 $error++;
535 }
536 }
537 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
538 $origin_id = $tmp_origin_id;
539 $ret = $this->add_object_linked($origin, $origin_id);
540 if (!$ret) {
541 $this->error = $this->db->lasterror();
542 $error++;
543 }
544 }
545 }
546 }
547
548 if (!$error) {
549 $result = $this->insertExtraFields();
550 if ($result < 0) {
551 $error++;
552 }
553 }
554
555 if (!$error && !$notrigger) {
556 // Call trigger
557 $result = $this->call_trigger('BILLREC_CREATE', $user);
558 if ($result < 0) {
559 $this->db->rollback();
560 return -2;
561 }
562 // End call triggers
563 }
564
565 if ($error) {
566 $this->db->rollback();
567 return -3;
568 } else {
569 $this->db->commit();
570 return $this->id;
571 }
572 } else {
573 $this->error = $this->db->lasterror();
574 $this->db->rollback();
575 return -2;
576 }
577 } else {
578 $this->db->rollback();
579 return -1;
580 }
581 }
582
583
591 public function update(User $user, $notrigger = 0)
592 {
593 $error = 0;
594
595 $sql = "UPDATE ".$this->db->prefix()."facture_rec SET";
596 $sql .= " entity = ".((int) $this->entity).",";
597 $sql .= " titre = '".$this->db->escape($this->title)."',";
598 $sql .= " suspended = ".((int) $this->suspended).",";
599 $sql .= " fk_soc = ".((int) $this->socid).",";
600 $sql .= " total_tva = ".((float) $this->total_tva).",";
601 $sql .= " localtax1 = ".((float) $this->total_localtax1).",";
602 $sql .= " localtax2 = ".((float) $this->total_localtax2).",";
603 $sql .= " total_ht = ".((float) $this->total_ht).",";
604 $sql .= " total_ttc = ".((float) $this->total_ttc).",";
605 $sql .= " fk_societe_rib = ".(!empty($this->fk_societe_rib) ? ((int) $this->fk_societe_rib) : 'NULL').",";
606 $sql .= " auto_validate = ".((int) $this->auto_validate).",";
607 $sql .= " fk_email_template = ".((int) $this->fk_email_template);
608
609 // TODO Add missing fields
610 $sql .= " WHERE rowid = ".((int) $this->id);
611
612 $this->db->begin();
613
614 dol_syslog(get_class($this)."::update", LOG_DEBUG);
615
616 $resql = $this->db->query($sql);
617 if ($resql) {
618 if (!$error) {
619 $result = $this->insertExtraFields();
620 if ($result < 0) {
621 $error++;
622 }
623 }
624
625 if (!$error && !$notrigger) {
626 // Call trigger
627 $result = $this->call_trigger('BILLREC_MODIFY', $user);
628 if ($result < 0) {
629 $this->db->rollback();
630 return -2;
631 }
632 // End call triggers
633 }
634 $this->db->commit();
635 return 1;
636 } else {
637 $this->error = $this->db->lasterror();
638 $this->db->rollback();
639 return -1;
640 }
641 }
642
653 public function fetch($rowid, $ref = '', $ref_ext = '', $noextrafields = 0, $nolines = 0)
654 {
655 dol_syslog('FactureRec::fetch', LOG_DEBUG);
656
657 $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc, f.subtype, f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc';
658 $sql .= ', f.date_lim_reglement as dlr';
659 $sql .= ', f.note_private, f.note_public, f.fk_user_author';
660 $sql .= ', f.modelpdf as model_pdf';
661 $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project';
662 $sql .= ', f.fk_account, f.fk_societe_rib';
663 $sql .= ', f.frequency, f.unit_frequency, f.rule_for_lines_dates, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.usenewprice, f.auto_validate';
664 $sql .= ', f.fk_email_template';
665 $sql .= ', f.generate_pdf';
666 $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
667 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
668 $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
669 //$sql.= ', el.fk_source';
670 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f';
671 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
672 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
673 //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'";
674 $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')';
675 if ($rowid) {
676 $sql .= ' AND f.rowid = '.((int) $rowid);
677 } elseif ($ref) {
678 $sql .= " AND f.titre = '".$this->db->escape($ref)."'";
679 } else {
680 $sql .= ' AND f.rowid = 0';
681 }
682 /* This field are not used for template invoice
683 if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
684 */
685
686 $result = $this->db->query($sql);
687 if ($result) {
688 if ($this->db->num_rows($result)) {
689 $obj = $this->db->fetch_object($result);
690
691 $this->id = $obj->rowid;
692 $this->entity = $obj->entity;
693 $this->titre = $obj->title; // deprecated
694 $this->title = $obj->title;
695 $this->ref = $obj->title;
696 $this->subtype = $obj->subtype;
697
698 $this->status = $obj->suspended;
699 $this->suspended = $obj->suspended;
700
701 $this->total_ht = $obj->total_ht;
702 $this->total_tva = $obj->total_tva;
703 $this->total_localtax1 = $obj->localtax1;
704 $this->total_localtax2 = $obj->localtax2;
705 $this->total_ttc = $obj->total_ttc;
706 $this->socid = $obj->fk_soc;
707 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
708 $this->mode_reglement_id = $obj->fk_mode_reglement;
709 $this->mode_reglement_code = $obj->mode_reglement_code;
710 $this->mode_reglement = $obj->mode_reglement_libelle;
711 $this->cond_reglement_id = $obj->fk_cond_reglement;
712 $this->cond_reglement_code = $obj->cond_reglement_code;
713 $this->cond_reglement = $obj->cond_reglement_libelle;
714 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
715 $this->fk_project = $obj->fk_project;
716 $this->fk_account = $obj->fk_account;
717 $this->fk_societe_rib = $obj->fk_societe_rib;
718 $this->note_private = $obj->note_private;
719 $this->note_public = $obj->note_public;
720 $this->user_creation_id = $obj->fk_user_author;
721 $this->model_pdf = $obj->model_pdf;
722 //$this->special_code = $obj->special_code;
723 $this->frequency = $obj->frequency;
724 $this->unit_frequency = $obj->unit_frequency;
725 $this->rule_for_lines_dates = $obj->rule_for_lines_dates;
726 $this->date_when = $this->db->jdate($obj->date_when);
727 $this->date_last_gen = $this->db->jdate($obj->date_last_gen);
728 $this->nb_gen_done = $obj->nb_gen_done;
729 $this->nb_gen_max = $obj->nb_gen_max;
730 $this->usenewprice = $obj->usenewprice;
731 $this->auto_validate = $obj->auto_validate;
732 $this->fk_email_template = $obj->fk_email_template;
733 $this->generate_pdf = $obj->generate_pdf;
734
735 // Multicurrency
736 $this->fk_multicurrency = $obj->fk_multicurrency;
737 $this->multicurrency_code = $obj->multicurrency_code;
738 $this->multicurrency_tx = $obj->multicurrency_tx;
739 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
740 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
741 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
742
743 // Retrieve all extrafield
744 // fetch optionals attributes and labels
745 if (empty($noextrafields)) {
746 $result = $this->fetch_optionals();
747 if ($result < 0) {
748 $this->error = $this->db->lasterror();
749 return -4;
750 }
751 }
752
753 // Retrieve lines
754 if (empty($nolines)) {
755 $result = $this->fetch_lines();
756 if ($result < 0) {
757 $this->error = $this->db->lasterror();
758 return -3;
759 }
760 }
761
762 return 1;
763 } else {
764 $this->error = 'Bill with id '.$rowid.' or ref '.$ref.' not found';
765 dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
766 return -2;
767 }
768 } else {
769 $this->error = $this->db->error();
770 return -1;
771 }
772 }
773
774
780 public function getLinesArray()
781 {
782 return $this->fetch_lines();
783 }
784
785
786 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
792 public function fetch_lines()
793 {
794 // phpcs:enable
795
796 $this->lines = array();
797
798 dol_syslog('FactureRec::fetch_lines', LOG_DEBUG);
799
800 $sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx, ';
801 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
802 $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,';
803 $sql .= ' l.rang, l.special_code,';
804 $sql .= ' l.fk_unit, l.fk_contract_line, l.extraparams,';
805 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
806 $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
807 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
808 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
809 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
810 $sql .= ' ORDER BY l.rang';
811
812 $result = $this->db->query($sql);
813 if ($result) {
814 $num = $this->db->num_rows($result);
815 $i = 0;
816 while ($i < $num) {
817 $objp = $this->db->fetch_object($result);
818 $line = new FactureLigneRec($this->db);
819
820 $line->id = $objp->rowid;
821 $line->rowid = $objp->rowid;
822 $line->fk_facture = $objp->fk_facture;
823 $line->fk_parent_line = $objp->fk_parent_line;
824 $line->desc = $objp->description; // Description line
825 $line->description = $objp->description; // Description line
826 $line->ref = $objp->product_ref; // Ref product
827 $line->product_ref = $objp->product_ref; // Ref product
828 $line->libelle = $objp->product_label; // deprecated
829 $line->product_label = $objp->product_label; // Label product
830 $line->product_desc = $objp->product_desc; // Description product
831 $line->product_type = $objp->product_type; // Type of line
832 $line->fk_product_type = $objp->fk_product_type; // Type of product
833 $line->qty = $objp->qty;
834 $line->subprice = $objp->subprice;
835
836 $line->label = $objp->custom_label; // @deprecated
837
838 $line->vat_src_code = $objp->vat_src_code;
839 $line->tva_tx = $objp->tva_tx;
840 $line->localtax1_tx = $objp->localtax1_tx;
841 $line->localtax2_tx = $objp->localtax2_tx;
842 $line->localtax1_type = $objp->localtax1_type;
843 $line->localtax2_type = $objp->localtax2_type;
844 $line->remise_percent = $objp->remise_percent;
845 //$line->fk_remise_except = $objp->fk_remise_except;
846 $line->fk_product = $objp->fk_product;
847 $line->date_start_fill = $objp->date_start_fill;
848 $line->date_end_fill = $objp->date_end_fill;
849 $line->info_bits = $objp->info_bits;
850 $line->total_ht = $objp->total_ht;
851 $line->total_tva = $objp->total_tva;
852 $line->total_ttc = $objp->total_ttc;
853
854 $line->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
855 $line->fk_fournprice = $objp->fk_product_fournisseur_price; // For backward compatibility
856
857 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_product_fournisseur_price, $objp->pa_ht);
858
859 $line->buyprice = $marginInfos[0];
860 $line->pa_ht = $marginInfos[0]; // For backward compatibility
861 $line->marge_tx = (string) $marginInfos[1];
862 $line->marque_tx = (string) $marginInfos[2];
863 $line->rang = $objp->rang;
864 $line->special_code = $objp->special_code;
865 $line->fk_unit = $objp->fk_unit;
866 $line->fk_contract_line = $objp->fk_contract_line;
867
868 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
869
870 // Ne plus utiliser
871 $line->price = $objp->price;
872 $line->remise = $objp->remise;
873
874 $line->fetch_optionals();
875
876 // Multicurrency
877 $line->fk_multicurrency = $objp->fk_multicurrency;
878 $line->multicurrency_code = $objp->multicurrency_code;
879 $line->multicurrency_subprice = $objp->multicurrency_subprice;
880 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
881 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
882 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
883
884 $this->lines[$i] = $line;
885
886 $i++;
887 }
888
889 $this->db->free($result);
890 return 1;
891 } else {
892 $this->error = $this->db->lasterror();
893 return -3;
894 }
895 }
896
897
906 public function delete(User $user, $notrigger = 0, $idwarehouse = -1)
907 {
908 $rowid = $this->id;
909
910 dol_syslog(get_class($this)."::delete rowid=".((int) $rowid), LOG_DEBUG);
911
912 $error = 0;
913 $this->db->begin();
914
915 $sql_main_table = MAIN_DB_PREFIX.'facturedet_rec';
916 $sql_ef_table = $sql_main_table."_extrafields";
917
918 $sqlef = "DELETE FROM $sql_ef_table WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table." WHERE fk_facture = ".((int) $rowid).")";
919 $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".((int) $rowid);
920
921 if ($this->db->query($sqlef) && $this->db->query($sql)) {
922 $sql = "DELETE FROM ".MAIN_DB_PREFIX."facture_rec WHERE rowid = ".((int) $rowid);
923 dol_syslog($sql);
924 if ($this->db->query($sql)) {
925 // Delete linked object
926 $res = $this->deleteObjectLinked();
927 if ($res < 0) {
928 $error = -3;
929 }
930 // Delete extrafields
931 $res = $this->deleteExtraFields();
932 if ($res < 0) {
933 $error = -4;
934 }
935 } else {
936 $this->error = $this->db->lasterror();
937 $error = -1;
938 }
939 } else {
940 $this->error = $this->db->lasterror();
941 $error = -2;
942 }
943 if (!$error && !$notrigger) {
944 // Call trigger
945 $result = $this->call_trigger('BILLREC_DELETE', $user);
946 if ($result < 0) {
947 $error++;
948 }
949 // End call triggers
950 }
951 if (!$error) {
952 $this->db->commit();
953 return 1;
954 } else {
955 $this->db->rollback();
956 return $error;
957 }
958 }
959
960
990 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 = 0, $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, $fk_parent_line = 0, $array_options = array())
991 {
992 global $mysoc;
993
994 $facid = $this->id;
995
996 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);
997 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
998
999 // Check parameters
1000 if ($type < 0) {
1001 return -1;
1002 }
1003
1004 $localtaxes_type = getLocalTaxesFromRate((float) $txtva, 0, $this->thirdparty, $mysoc);
1005
1006 // Clean vat code
1007 $reg = array();
1008 $vat_src_code = '';
1009 if (preg_match('/\‍((.*)\‍)/', (string) $txtva, $reg)) {
1010 $vat_src_code = $reg[1];
1011 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', (string) $txtva); // Remove code from vatrate.
1012 }
1013
1014
1015 // Clean parameters
1016 $remise_percent = price2num($remise_percent);
1017 if (empty($remise_percent)) {
1018 $remise_percent = 0;
1019 }
1020 $qty = (float) price2num($qty);
1021 $pu_ht = (float) price2num($pu_ht);
1022 $pu_ttc = (float) price2num($pu_ttc);
1023 if (!preg_match('/\‍((.*)\‍)/', $txtva)) {
1024 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
1025 }
1026 $txlocaltax1 = (float) price2num($txlocaltax1);
1027 $txlocaltax2 = (float) price2num($txlocaltax2);
1028 if (empty($txtva)) {
1029 $txtva = 0;
1030 }
1031 if (empty($txlocaltax1)) {
1032 $txlocaltax1 = 0;
1033 }
1034 if (empty($txlocaltax2)) {
1035 $txlocaltax2 = 0;
1036 }
1037 if (empty($info_bits)) {
1038 $info_bits = 0;
1039 }
1040
1041 if ($price_base_type == 'HT') {
1042 $pu = $pu_ht;
1043 } else {
1044 $pu = $pu_ttc;
1045 }
1046
1047 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1048 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1049 // and this is done at the line level, which has its own VAT rate
1050
1051 $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, $this->multicurrency_code);
1052 $total_ht = $tabprice[0];
1053 $total_tva = $tabprice[1];
1054 $total_ttc = $tabprice[2];
1055 $total_localtax1 = $tabprice[9];
1056 $total_localtax2 = $tabprice[10];
1057 $pu_ht = $tabprice[3];
1058
1059 // MultiCurrency
1060 $multicurrency_total_ht = $tabprice[16];
1061 $multicurrency_total_tva = $tabprice[17];
1062 $multicurrency_total_ttc = $tabprice[18];
1063 $pu_ht_devise = $tabprice[19];
1064
1065 $product_type = $type;
1066 if ($fk_product) {
1067 $product = new Product($this->db);
1068 $result = $product->fetch($fk_product);
1069 $product_type = $product->type;
1070 }
1071
1072 if (empty($fk_parent_line) || $fk_parent_line < 0) {
1073 $fk_parent_line = 0;
1074 }
1075
1076 // Rank to use
1077 $ranktouse = $rang;
1078 if ($ranktouse == -1) {
1079 $rangmax = $this->line_max(0);
1080 $ranktouse = $rangmax + 1;
1081 }
1082
1083 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facturedet_rec (";
1084 $sql .= "fk_facture";
1085 $sql .= ", fk_parent_line";
1086 $sql .= ", label";
1087 $sql .= ", description";
1088 $sql .= ", price";
1089 $sql .= ", qty";
1090 $sql .= ", tva_tx";
1091 $sql .= ", vat_src_code";
1092 $sql .= ", localtax1_tx";
1093 $sql .= ", localtax1_type";
1094 $sql .= ", localtax2_tx";
1095 $sql .= ", localtax2_type";
1096 $sql .= ", fk_product";
1097 $sql .= ", product_type";
1098 $sql .= ", remise_percent";
1099 $sql .= ", subprice";
1100 $sql .= ", remise";
1101 $sql .= ", total_ht";
1102 $sql .= ", total_tva";
1103 $sql .= ", total_localtax1";
1104 $sql .= ", total_localtax2";
1105 $sql .= ", total_ttc";
1106 $sql .= ", date_start_fill";
1107 $sql .= ", date_end_fill";
1108 $sql .= ", fk_product_fournisseur_price";
1109 $sql .= ", buy_price_ht";
1110 $sql .= ", info_bits";
1111 $sql .= ", rang";
1112 $sql .= ", special_code";
1113 $sql .= ", fk_unit";
1114 $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
1115 $sql .= ") VALUES (";
1116 $sql .= " ".((int) $facid);
1117 $sql .= ", ".($fk_parent_line > 0 ? ((int) $fk_parent_line) : "null");
1118 $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
1119 $sql .= ", '".$this->db->escape($desc)."'";
1120 $sql .= ", ".price2num($pu_ht);
1121 $sql .= ", ".price2num($qty);
1122 $sql .= ", ".price2num($txtva);
1123 $sql .= ", '".$this->db->escape($vat_src_code)."'";
1124 $sql .= ", ".price2num($txlocaltax1);
1125 $sql .= ", '".$this->db->escape(isset($localtaxes_type[0]) ? $localtaxes_type[0] : '')."'";
1126 $sql .= ", ".price2num($txlocaltax2);
1127 $sql .= ", '".$this->db->escape(isset($localtaxes_type[2]) ? $localtaxes_type[2] : '')."'";
1128 $sql .= ", ".(!empty($fk_product) ? "'".$this->db->escape((string) $fk_product)."'" : "null");
1129 $sql .= ", ".((int) $product_type);
1130 $sql .= ", ".price2num($remise_percent);
1131 $sql .= ", ".price2num($pu_ht);
1132 $sql .= ", null";
1133 $sql .= ", ".price2num($total_ht);
1134 $sql .= ", ".price2num($total_tva);
1135 $sql .= ", ".price2num($total_localtax1);
1136 $sql .= ", ".price2num($total_localtax2);
1137 $sql .= ", ".price2num($total_ttc);
1138 $sql .= ", ".(int) $date_start_fill;
1139 $sql .= ", ".(int) $date_end_fill;
1140 $sql .= ", ".($fk_fournprice > 0 ? ((int) $fk_fournprice) : 'null');
1141 $sql .= ", ".($pa_ht ? price2num($pa_ht) : 0);
1142 $sql .= ", ".((int) $info_bits);
1143 $sql .= ", ".((int) $ranktouse);
1144 $sql .= ", ".((int) $special_code);
1145 $sql .= ", ".($fk_unit ? ((int) $fk_unit) : "null");
1146 $sql .= ", ".(int) $this->fk_multicurrency;
1147 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1148 $sql .= ", ".price2num($pu_ht_devise, 'CU');
1149 $sql .= ", ".price2num($multicurrency_total_ht, 'CT');
1150 $sql .= ", ".price2num($multicurrency_total_tva, 'CT');
1151 $sql .= ", ".price2num($multicurrency_total_ttc, 'CT');
1152 $sql .= ")";
1153
1154 dol_syslog(get_class($this)."::addline", LOG_DEBUG);
1155 if ($this->db->query($sql)) {
1156 $lineId = $this->db->last_insert_id(MAIN_DB_PREFIX."facturedet_rec");
1157 $this->id = $facid;
1158 $this->update_price(1);
1159
1160 if (is_array($array_options) && count($array_options) > 0) {
1161 $factureRecLine = new FactureLigneRec($this->db);
1162 $factureRecLine->id = $lineId;
1163 $factureRecLine->array_options = $array_options;
1164 $result = $factureRecLine->insertExtraFields();
1165 if ($result < 0) {
1166 $this->errors[] = $factureRecLine->error;
1167 return -2;
1168 }
1169 }
1170
1171 return $lineId;
1172 } else {
1173 $this->error = $this->db->lasterror();
1174 return -1;
1175 }
1176 }
1177
1208 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 = 0, $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, $fk_parent_line = 0)
1209 {
1210 global $mysoc;
1211
1212 if (!$this->isLineOfObject($rowid)) {
1213 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1214 return -1;
1215 }
1216
1217 $facid = $this->id;
1218
1219 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);
1220 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1221
1222 // Clean parameters
1223 if (empty($remise_percent)) {
1224 $remise_percent = 0;
1225 }
1226
1227 // Check parameters
1228 if ($type < 0) {
1229 return -1;
1230 }
1231
1232 // Clean parameters
1233 $remise_percent = (float) price2num($remise_percent);
1234 $qty = (float) price2num($qty);
1235 if (empty($info_bits)) {
1236 $info_bits = 0;
1237 }
1238 $pu_ht = (float) price2num($pu_ht);
1239 $pu_ttc = (float) price2num($pu_ttc);
1240 $pu_ht_devise = (float) price2num($pu_ht_devise);
1241 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
1242 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
1243 }
1244 $txlocaltax1 = (float) price2num($txlocaltax1);
1245 $txlocaltax2 = (float) price2num($txlocaltax2);
1246 if (empty($txlocaltax1)) {
1247 $txlocaltax1 = 0;
1248 }
1249 if (empty($txlocaltax2)) {
1250 $txlocaltax2 = 0;
1251 }
1252
1253 if (empty($this->multicurrency_subprice)) {
1254 $this->multicurrency_subprice = 0;
1255 }
1256 if (empty($this->multicurrency_total_ht)) {
1257 $this->multicurrency_total_ht = 0;
1258 }
1259 if (empty($this->multicurrency_total_tva)) {
1260 $this->multicurrency_total_tva = 0;
1261 }
1262 if (empty($this->multicurrency_total_ttc)) {
1263 $this->multicurrency_total_ttc = 0;
1264 }
1265
1266 if ($price_base_type == 'HT') {
1267 $pu = $pu_ht;
1268 } else {
1269 $pu = $pu_ttc;
1270 }
1271
1272 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1273 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1274 // and this is done at the line level, which has its own VAT rate
1275
1276 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
1277
1278 // Clean vat code
1279 $vat_src_code = '';
1280 $reg = array();
1281 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1282 $vat_src_code = $reg[1];
1283 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1284 }
1285
1286 $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, $this->multicurrency_code);
1287
1288 $total_ht = $tabprice[0];
1289 $total_tva = $tabprice[1];
1290 $total_ttc = $tabprice[2];
1291 $total_localtax1 = $tabprice[9];
1292 $total_localtax2 = $tabprice[10];
1293 $pu_ht = $tabprice[3];
1294 $pu_tva = $tabprice[4];
1295 $pu_ttc = $tabprice[5];
1296
1297 // MultiCurrency
1298 $multicurrency_total_ht = $tabprice[16];
1299 $multicurrency_total_tva = $tabprice[17];
1300 $multicurrency_total_ttc = $tabprice[18];
1301 $pu_ht_devise = $tabprice[19];
1302
1303 $product_type = $type;
1304 if ($fk_product) {
1305 $product = new Product($this->db);
1306 $result = $product->fetch($fk_product);
1307 $product_type = $product->type;
1308 }
1309
1310 if (empty($fk_parent_line) || $fk_parent_line < 0) {
1311 $fk_parent_line = 0;
1312 }
1313
1314 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET ";
1315 $sql .= "fk_facture = ".((int) $facid);
1316 $sql .= ", fk_parent_line = ".($fk_parent_line > 0 ? ((int) $fk_parent_line) : "null");
1317 $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
1318 $sql .= ", description='".$this->db->escape($desc)."'";
1319 $sql .= ", price=".price2num($pu_ht);
1320 $sql .= ", qty=".price2num($qty);
1321 $sql .= ", tva_tx=".price2num($txtva);
1322 $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'";
1323 $sql .= ", localtax1_tx=".((float) $txlocaltax1);
1324 $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'";
1325 $sql .= ", localtax2_tx=".((float) $txlocaltax2);
1326 $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'";
1327 $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape((string) $fk_product)."'" : "null");
1328 $sql .= ", product_type=".((int) $product_type);
1329 $sql .= ", remise_percent='".price2num($remise_percent)."'";
1330 $sql .= ", subprice='".price2num($pu_ht)."'";
1331 $sql .= ", total_ht='".price2num($total_ht)."'";
1332 $sql .= ", total_tva='".price2num($total_tva)."'";
1333 $sql .= ", total_localtax1='".price2num($total_localtax1)."'";
1334 $sql .= ", total_localtax2='".price2num($total_localtax2)."'";
1335 $sql .= ", total_ttc='".price2num($total_ttc)."'";
1336 $sql .= ", date_start_fill=".((int) $date_start_fill);
1337 $sql .= ", date_end_fill=".((int) $date_end_fill);
1338 $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? (int) $fk_fournprice : 'null');
1339 $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0);
1340 $sql .= ", info_bits=".((int) $info_bits);
1341 $sql .= ", rang=".((int) $rang);
1342 $sql .= ", special_code=".((int) $special_code);
1343 $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape((string) $fk_unit)."'" : "null");
1344 $sql .= ', multicurrency_subprice = '.price2num($pu_ht_devise);
1345 $sql .= ', multicurrency_total_ht = '.price2num($multicurrency_total_ht);
1346 $sql .= ', multicurrency_total_tva = '.price2num($multicurrency_total_tva);
1347 $sql .= ', multicurrency_total_ttc = '.price2num($multicurrency_total_ttc);
1348 $sql .= " WHERE rowid = ".((int) $rowid);
1349
1350 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1351 if ($this->db->query($sql)) {
1352 $this->id = $facid;
1353 $this->update_price(1);
1354 return 1;
1355 } else {
1356 $this->error = $this->db->lasterror();
1357 return -1;
1358 }
1359 }
1360
1361
1370 public function getNextDate()
1371 {
1372 if (empty($this->date_when)) {
1373 return false;
1374 }
1375
1376 // date_when is read from database in the timezone of the server (jdate), so the delay must be added in this timezone
1377 return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency, 1, 'tzserver');
1378 }
1379
1385 public function isMaxNbGenReached()
1386 {
1387 $ret = false;
1388 if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) {
1389 $ret = true;
1390 }
1391 return $ret;
1392 }
1393
1400 public function strikeIfMaxNbGenReached($ret)
1401 {
1402 return $this->isMaxNbGenReached() ? '<strike>'.$ret.'</strike>' : $ret;
1403 }
1404
1417 public function createRecurringInvoices($restrictioninvoiceid = 0, $forcevalidation = 0, $notrigger = 0, $forcebuilddoc = 0)
1418 {
1419 global $conf, $langs, $user, $hookmanager, $action;
1420
1421 $error = 0;
1422 $nb_create = 0;
1423
1424 // Load translation files required by the page
1425 $langs->loadLangs(array("main", "bills"));
1426
1427 $now = dol_now();
1428 // Creation can be done from UI or from cron, so we must share a common hour, so we use server timezone to get the day, month and year.
1429 $tmparray = dol_getdate($now, false, 'tzserver');
1430 $endofdaytzserver = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], 'tzserver'); // If we print date UTC in string, we got: 'year-mon-mday 22:59:59' if TZ+1
1431
1432 $this->output = '';
1433
1434 dol_syslog("createRecurringInvoices restrictioninvoiceid=".$restrictioninvoiceid." forcevalidation=".$forcevalidation." forcebuilddoc=".$forcebuilddoc, LOG_DEBUG);
1435
1436 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec';
1437 $sql .= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency
1438 $sql .= " AND (date_when IS NULL OR date_when <= '".$this->db->idate($endofdaytzserver)."')"; // we got 'year-mon-mday 23:59:59' because idate convert into TZ server
1439 $sql .= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)';
1440 $sql .= ' AND suspended = 0';
1441 $sql .= ' AND entity = '.((int) $conf->entity); // MUST STAY = $conf->entity here
1442 if ($restrictioninvoiceid > 0) {
1443 $sql .= ' AND rowid = '.((int) $restrictioninvoiceid);
1444 }
1445 $sql .= $this->db->order('entity', 'ASC');
1446 if (getDolGlobalInt('NB_REC_FACT_CUSTOMER_GEN_BY_CALL')) {
1447 $sql .= $this->db->plimit(getDolGlobalInt('NB_REC_FACT_CUSTOMER_GEN_BY_CALL'));
1448 }
1449 //print $sql;exit;
1450 $parameters = array(
1451 'restrictioninvoiceid' => $restrictioninvoiceid,
1452 'forcevalidation' => $forcevalidation,
1453 );
1454 $reshook = $hookmanager->executeHooks('beforeCreationOfRecurringInvoices', $parameters, $sql); // note that $sql might be modified by hooks
1455
1456 $resql = $this->db->query($sql);
1457 if ($resql) {
1458 $i = 0;
1459 $num = $this->db->num_rows($resql);
1460
1461 if ($num) {
1462 $this->output .= $langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n";
1463 } else {
1464 $this->output .= $langs->trans("NoQualifiedRecurringInvoiceTemplateFound");
1465 }
1466
1467 $saventity = $conf->entity;
1468
1469 while ($i < $num) { // Loop on each template invoice. If $num = 0, test is false at first pass.
1470 $line = $this->db->fetch_object($resql);
1471
1472 $this->db->begin();
1473
1474 $errorforinvoice = 0;
1475 $invoiceidgenerated = 0;
1476 $mailHasSent = false;
1477 // Create a loopError that is reset at each loop, this counter is added to the global counter at the end of loop
1478 $loopError = 0;
1479
1480 $facture = null;
1481 $facturerec = new FactureRec($this->db);
1482 $facturerec->fetch($line->rowid);
1483
1484 if ($facturerec->id > 0) {
1485 // Set entity context
1486 $conf->entity = $facturerec->entity;
1487
1488 dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity);
1489
1490 $facture = new Facture($this->db);
1491 $facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice
1492 $facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice
1493
1494 $facture->type = self::TYPE_STANDARD;
1495 $facture->subtype = $facturerec->subtype;
1496 $facture->statut = self::STATUS_DRAFT; // deprecated
1497 $facture->status = self::STATUS_DRAFT;
1498 $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.
1499 $facture->socid = $facturerec->socid;
1500
1501 if (!empty($facturerec->fk_multicurrency)) {
1502 $facture->fk_multicurrency = $facturerec->fk_multicurrency;
1503 $facture->multicurrency_code = $facturerec->multicurrency_code;
1504 $facture->multicurrency_tx = $facturerec->multicurrency_tx;
1505 }
1506
1507 if (isset($facture->array_options) && isset($facturerec->array_options)) {
1508 foreach ($facturerec->array_options as $key => $value) {
1509 if (isset($facture->array_options[$key])) {
1510 $facture->array_options[$key] = $value;
1511 }
1512 }
1513 }
1514
1515 $parameters['facture'] = &$facture;
1516 $reshook = $hookmanager->executeHooks('beforeCreationOfEachRecurringInvoice', $parameters, $facturerec, $action); // note that $facturerec or $facture might be modified by hooks
1517
1518 // Create invoice. This may update prices according to multiplrice rules
1519 $invoiceidgenerated = $facture->create($user, 0, 0, (isModEnabled('multicurrency') ? $facturerec->usenewcurrencyrate : 0));
1520 if ($invoiceidgenerated <= 0) {
1521 $this->setErrorsFromObject($facture);
1522 $error++;
1523 $errorforinvoice++;
1524 }
1525
1526
1527 if (!$errorforinvoice && ($facturerec->auto_validate || $forcevalidation)) {
1528 $result = $facture->validate($user);
1529 if ($result <= 0) {
1530 $this->setErrorsFromObject($facture);
1531 $error++;
1532 $errorforinvoice++;
1533 }
1534 }
1535 if (!$errorforinvoice && ($facturerec->generate_pdf || $forcebuilddoc || $facturerec->auto_validate == 2)) { // ->generate_pdf is 1 by default (can be edited if INVOICE_REC_CAN_DISABLE_DOCUMENT_FILE_GENERATION is set to 1)
1536 // We reload the object in order to have all necessary data (like date_lim_reglement)
1537 $facture->fetch($facture->id);
1538 $facture->fetch_thirdparty();
1539
1540 $outputlangs = $langs;
1541 if (getDolGlobalInt('MAIN_MULTILANGS')) {
1542 if (!empty($facture->thirdparty->default_lang)) {
1543 $outputlangs = new Translate('', $conf);
1544 $outputlangs->setDefaultLang($facture->thirdparty->default_lang);
1545 $outputlangs->loadLangs(array('main', 'bills'));
1546 }
1547 }
1548
1549 $result = 1;
1550 if ($facturerec->generate_pdf || $forcebuilddoc) {
1551 $result = $facture->generateDocument($facturerec->model_pdf, $outputlangs);
1552 if ($result <= 0) {
1553 $this->setErrorsFromObject($facture);
1554 $error++;
1555 $errorforinvoice++;
1556 }
1557 }
1558
1559 // Auto sending of the invoice
1560 if ($result > 0 && $facture->status == Facture::STATUS_VALIDATED && $facturerec->auto_validate == 2) {
1561 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
1562 require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
1563 $formmail = new FormMail($this->db);
1564
1565 // Select email template according to language of recipient
1566 $template = $facturerec->fk_email_template;
1567 $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template), (($template != 0) ? -1 : 1));
1568 if (is_numeric($arraymessage) && $arraymessage <= 0) {
1569 $langs->load("errors");
1570 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template ?? '');
1571 return 0;
1572 }
1573
1574 // PREPARE EMAIL
1575 $errormesg = '';
1576
1577 // Make substitution in email content
1578 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $facture);
1579
1580 complete_substitutions_array($substitutionarray, $outputlangs, $facture);
1581
1582 // Topic
1583 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
1584
1585 // Content
1586 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
1587
1588 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
1589
1590 // Recipient
1591 $to = array();
1592 $res = $facture->fetch_thirdparty();
1593 $recipient = $facture->thirdparty;
1594 if ($res > 0) {
1595 $tmparraycontact = $facture->liste_contact(-1, 'external', 0, 'BILLING');
1596 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
1597 foreach ($tmparraycontact as $data_email) {
1598 if (!empty($data_email['email'])) {
1599 $to[] = $facture->thirdparty->contact_get_property($data_email['id'], 'email');
1600 }
1601 }
1602 }
1603 if (empty($to) && !empty($recipient->email)) {
1604 $to[] = $recipient->email;
1605 }
1606 if (empty($to)) {
1607 $errormesg = "Failed to send invoice to thirdparty id=".$facture->socid.". No email defined for invoice or customer.";
1608 $loopError++;
1609 }
1610 } else {
1611 $errormesg = "Failed to load recipient with thirdparty id=".$facture->socid;
1612 $loopError++;
1613 }
1614
1615 // Sender
1616 $email_from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
1617 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
1618 $email_from = (string) $arraymessage->email_from;
1619 }
1620 if (empty($email_from)) {
1621 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
1622 $loopError++;
1623 }
1624
1625 if (!$loopError && !empty($to)) {
1626 $to = implode(',', $to);
1627 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
1628 $to = $to . ',' . $arraymessage->email_to;
1629 }
1630
1631 // Errors Recipient
1632 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
1633
1634 $trackid = 'inv'.$facture->id;
1635 $sendcontext = 'standard';
1636
1637 // CC
1638 $email_tocc = '';
1639 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
1640 $email_tocc = (string) $arraymessage->email_tocc;
1641 }
1642
1643 // BCC
1644 $email_tobcc = '';
1645 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
1646 $email_tobcc = (string) $arraymessage->email_tobcc;
1647 }
1648
1649 //join file is asked
1650 $joinFile = [];
1651 $joinFileName = [];
1652 $joinFileMime = [];
1653 if ($arraymessage->joinfiles == 1 && !empty($facture->last_main_doc)) {
1654 $joinFile[] = DOL_DATA_ROOT.'/'.$facture->last_main_doc;
1655 $joinFileName[] = basename($facture->last_main_doc);
1656 $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$facture->last_main_doc);
1657 }
1658
1659 // Mail Creation
1660 $cMailFile = new CMailFile($sendTopic, $to, $email_from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
1661
1662 $resultsendmail = $cMailFile->sendfile();
1663
1664 $this->db->begin();
1665
1666 // Sending Mail
1667 if ($resultsendmail) {
1668 $mailHasSent = true;
1669
1670 // Add a line into event table
1671 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1672
1673 // Insert record of emails sent
1674 $actioncomm = new ActionComm($this->db);
1675
1676 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
1677 $actioncomm->socid = $facture->thirdparty->id; // To link to a company
1678 $actioncomm->contact_id = 0;
1679
1680 $actioncomm->code = 'AC_EMAIL';
1681 $actioncomm->label = $langs->trans('MailSentByTo', $email_from, $to);
1682 $actioncomm->note_private = $sendContent;
1683 $actioncomm->fk_project = $facture->fk_project;
1684 $actioncomm->datep = dol_now();
1685 $actioncomm->datef = $actioncomm->datep;
1686 $actioncomm->percentage = -1; // Not applicable
1687 $actioncomm->authorid = $user->id; // User saving action
1688 $actioncomm->userownerid = $user->id; // Owner of action
1689 // Fields when action is an email (content should be added into note)
1690 $actioncomm->email_msgid = $cMailFile->msgid;
1691 $actioncomm->email_subject = $sendTopic;
1692 $actioncomm->email_from = $email_from;
1693 $actioncomm->email_sender = '';
1694 $actioncomm->email_to = $to;
1695 //$actioncomm->email_tocc = $sendtocc;
1696 //$actioncomm->email_tobcc = $sendtobcc;
1697 //$actioncomm->email_subject = $subject;
1698 $actioncomm->errors_to = $errors_to;
1699
1700 $actioncomm->elementtype = 'invoice';
1701 $actioncomm->elementid = $facture->id;
1702
1703 //$actioncomm->extraparams = $extraparams;
1704
1705 $actioncomm->create($user);
1706 } else {
1707 $errormesg = $cMailFile->error.' : '.$to;
1708 $loopError++;
1709
1710 // Add a line into event table
1711 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1712
1713 // Insert record of emails sent
1714 $actioncomm = new ActionComm($this->db);
1715
1716 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
1717 $actioncomm->socid = $facture->thirdparty->id; // To link to a company
1718 $actioncomm->contact_id = 0;
1719
1720 $actioncomm->code = 'AC_EMAIL';
1721 $actioncomm->label = $langs->trans('sendAutoEmailInvoiceKO', $email_from, $to);
1722 $actioncomm->note_private = $errormesg;
1723 $actioncomm->fk_project = $facture->fk_project;
1724 $actioncomm->datep = dol_now();
1725 $actioncomm->datef = $actioncomm->datep;
1726 $actioncomm->percentage = -1; // Not applicable
1727 $actioncomm->authorid = $user->id; // User saving action
1728 $actioncomm->userownerid = $user->id; // Owner of action
1729 // Fields when action is an email (content should be added into note)
1730 $actioncomm->email_msgid = $cMailFile->msgid;
1731 $actioncomm->email_subject = $sendTopic;
1732 $actioncomm->email_from = $email_from;
1733 $actioncomm->email_sender = '';
1734 $actioncomm->email_to = $to;
1735 //$actioncomm->email_tocc = $sendtocc;
1736 //$actioncomm->email_tobcc = $sendtobcc;
1737 //$actioncomm->email_subject = $subject;
1738 $actioncomm->errors_to = $errors_to;
1739
1740 $actioncomm->elementtype = 'invoice';
1741 $actioncomm->elementid = $facture->id;
1742
1743 //$actioncomm->extraparams = $extraparams;
1744
1745 $actioncomm->create($user);
1746 }
1747
1748 $this->db->commit(); // We always commit
1749 }
1750 }
1751 }
1752 } else {
1753 $error++;
1754 $this->error = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity."\n";
1755 $this->errors[] = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity;
1756 dol_syslog("createRecurringInvoices Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity);
1757 }
1758
1759 // Commit or rollback. Only the result of the current template must be tested (not the cumulative $error), so that a failure on one template does not cancel the templates processed after it.
1760 // $invoiceidgenerated must be > 0 (not >= 0): it is still 0 when $facturerec->fetch() failed above, in which case $facture is still null.
1761 if (!$errorforinvoice && $invoiceidgenerated > 0) {
1762 $this->db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
1763 dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation");
1764 $nb_create++;
1765 $this->output .= $langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n";
1766
1767 // Mail error
1768 if ($loopError > 0) {
1769 $this->output .= $langs->trans("InvoiceSentFromTemplateError", $facture->ref, $facturerec->ref, $errormesg ?? '')."\n";
1770 }
1771
1772 // Mail sent
1773 if ($mailHasSent) {
1774 $this->output .= $langs->trans("InvoiceSentFromTemplate", $facture->ref, $facturerec->ref)."\n";
1775 }
1776 } else {
1777 // $facture is still null when $facturerec->fetch() failed above
1778 $this->output .= $langs->trans("InvoiceGeneratedFromTemplateError", (is_object($facture) ? $facture->ref : ''), $facturerec->ref, $this->error)."\n";
1779 $this->db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
1780 }
1781
1782 $parameters = array(
1783 'cpt' => $i,
1784 'total' => $num,
1785 'errorCount' => $error,
1786 'errorForInvoice' => $errorforinvoice,
1787 'invoiceidgenerated' => $invoiceidgenerated,
1788 'facturerec' => $facturerec, // it's an object which PHP passes by "reference", so modifiable by hooks.
1789 'this' => $this, // it's an object which PHP passes by "reference", so modifiable by hooks.
1790 );
1791 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
1792 $reshook = $hookmanager->executeHooks('afterCreationOfRecurringInvoice', $parameters, $facture); // note: $facture can be modified by hooks (warning: $facture can be null)
1793
1794 $i++;
1795 }
1796
1797 $conf->entity = $saventity; // Restore entity context
1798 } else {
1799 dol_print_error($this->db);
1800 }
1801
1802 $this->output = trim($this->output);
1803
1804 return $error ? $error : 0;
1805 }
1806
1819 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
1820 {
1821 global $langs, $hookmanager;
1822
1823 $result = '';
1824
1825 $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("RepeatableInvoice").'</u>';
1826 if (!empty($this->ref)) {
1827 $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1828 }
1829 if ($this->frequency > 0) {
1830 $label .= '<br><b>'.$langs->trans('Frequency').':</b> '.$langs->trans('FrequencyPer_'.$this->unit_frequency, $this->frequency);
1831 }
1832 if (!empty($this->date_last_gen)) {
1833 $label .= '<br><b>'.$langs->trans('DateLastGeneration').':</b> '.dol_print_date($this->date_last_gen, 'dayhour');
1834 }
1835 if ($this->frequency > 0) {
1836 if (!empty($this->date_when)) {
1837 $label .= '<br><b>'.$langs->trans('NextDateToExecution').':</b> ';
1838 $label .= (empty($this->suspended) ? '' : '<strike>').dol_print_date($this->date_when, 'day').(empty($this->suspended) ? '' : '</strike>'); // No hour for this property
1839 if (!empty($this->suspended)) {
1840 $label .= ' ('.$langs->trans("Disabled").')';
1841 }
1842 }
1843 }
1844
1845 $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?id='.$this->id;
1846
1847 if ($short) {
1848 return $url;
1849 }
1850
1851 if ($option != 'nolink') {
1852 // Add param to save lastsearch_values or not
1853 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1854 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1855 $add_save_lastsearch_values = 1;
1856 }
1857 if ($add_save_lastsearch_values) {
1858 $url .= '&save_lastsearch_values=1';
1859 }
1860 }
1861
1862 $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1863 $linkend = '</a>';
1864
1865 $result .= $linkstart;
1866 if ($withpicto) {
1867 $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);
1868 }
1869 if ($withpicto != 2) {
1870 $result .= dol_trunc($this->ref, $max);
1871 }
1872 $result .= $linkend;
1873 global $action;
1874 $hookmanager->initHooks(array($this->element . 'dao'));
1875 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1876 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1877 if ($reshook > 0) {
1878 $result = $hookmanager->resPrint;
1879 } else {
1880 $result .= $hookmanager->resPrint;
1881 }
1882 return $result;
1883 }
1884
1892 public function getLibStatut($mode = 0, $alreadypaid = -1)
1893 {
1894 return $this->LibStatut($this->frequency ? 1 : 0, $this->suspended, $mode, $alreadypaid, empty($this->type) ? 0 : $this->type);
1895 }
1896
1897 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1909 public function LibStatut($recur, $status, $mode = 0, $alreadypaid = -1, $type = 0, $nbofopendirectdebitorcredittransfer = 0)
1910 {
1911 // phpcs:enable
1912 global $langs;
1913 $langs->load('bills');
1914
1915 $labelStatus = $langs->transnoentitiesnoconv('Active');
1916 $statusType = 'status0';
1917
1918 //print "$recur,$status,$mode,$alreadypaid,$type";
1919 if ($mode == 0) {
1920 if ($recur) {
1921 if ($status == self::STATUS_SUSPENDED) {
1922 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1923 } else {
1924 $labelStatus = $langs->transnoentitiesnoconv('Active');
1925 }
1926 } else {
1927 if ($status == self::STATUS_SUSPENDED) {
1928 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1929 } else {
1930 $labelStatus = $langs->transnoentitiesnoconv("Draft");
1931 }
1932 }
1933 } elseif ($mode == 1) {
1934 $prefix = 'Short';
1935 if ($recur) {
1936 if ($status == self::STATUS_SUSPENDED) {
1937 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1938 } else {
1939 $labelStatus = $langs->transnoentitiesnoconv('Active');
1940 }
1941 } else {
1942 if ($status == self::STATUS_SUSPENDED) {
1943 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1944 } else {
1945 $labelStatus = $langs->transnoentitiesnoconv("Draft");
1946 }
1947 }
1948 } elseif ($mode == 2) {
1949 if ($recur) {
1950 if ($status == self::STATUS_SUSPENDED) {
1951 $statusType = 'status6';
1952 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1953 } else {
1954 $statusType = 'status4';
1955 $labelStatus = $langs->transnoentitiesnoconv('Active');
1956 }
1957 } else {
1958 if ($status == self::STATUS_SUSPENDED) {
1959 $statusType = 'status6';
1960 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1961 } else {
1962 $statusType = 'status0';
1963 $labelStatus = $langs->transnoentitiesnoconv('Draft');
1964 }
1965 }
1966 } elseif ($mode == 3) {
1967 if ($recur) {
1968 $prefix = 'Short';
1969 if ($status == self::STATUS_SUSPENDED) {
1970 $statusType = 'status6';
1971 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1972 } else {
1973 $statusType = 'status4';
1974 $labelStatus = $langs->transnoentitiesnoconv('Active');
1975 }
1976 } else {
1977 if ($status == self::STATUS_SUSPENDED) {
1978 $statusType = 'status6';
1979 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1980 } else {
1981 $statusType = 'status0';
1982 $labelStatus = $langs->transnoentitiesnoconv('Draft');
1983 }
1984 }
1985 } elseif ($mode == 4) {
1986 $prefix = '';
1987 if ($recur) {
1988 if ($status == self::STATUS_SUSPENDED) {
1989 $statusType = 'status6';
1990 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1991 } else {
1992 $statusType = 'status4';
1993 $labelStatus = $langs->transnoentitiesnoconv('Active');
1994 }
1995 } else {
1996 if ($status == self::STATUS_SUSPENDED) {
1997 $statusType = 'status6';
1998 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1999 } else {
2000 $statusType = 'status0';
2001 $labelStatus = $langs->transnoentitiesnoconv('Draft');
2002 }
2003 }
2004 } elseif ($mode == 5 || $mode == 6) {
2005 $prefix = '';
2006 if ($mode == 5) {
2007 $prefix = 'Short';
2008 }
2009 if ($recur) {
2010 if ($status == self::STATUS_SUSPENDED) {
2011 $statusType = 'status6';
2012 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
2013 } else {
2014 $statusType = 'status4';
2015 $labelStatus = $langs->transnoentitiesnoconv('Active');
2016 }
2017 } else {
2018 if ($status == self::STATUS_SUSPENDED) {
2019 $statusType = 'status6';
2020 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
2021 } else {
2022 $statusType = 'status0';
2023 $labelStatus = $langs->transnoentitiesnoconv('Draft');
2024 }
2025 }
2026 }
2027
2028 $labelStatusShort = $labelStatus;
2029
2030 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
2031 }
2032
2040 public function getNextNumRef($soc, $mode = 'next')
2041 {
2042 // Not used for recurring invoices
2043 return '';
2044 }
2045
2052 public function info($id)
2053 {
2054 $sql = 'SELECT c.rowid, datec, tms as datem,';
2055 $sql .= ' fk_user_author, fk_user_modif';
2056 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as c';
2057 $sql .= ' WHERE c.rowid = '.((int) $id);
2058
2059 $result = $this->db->query($sql);
2060 if ($result) {
2061 if ($this->db->num_rows($result)) {
2062 $obj = $this->db->fetch_object($result);
2063
2064 $this->id = $obj->rowid;
2065
2066 $this->user_creation_id = $obj->fk_user_author;
2067 $this->user_modification_id = $obj->fk_user_modif;
2068 $this->date_creation = $this->db->jdate($obj->datec);
2069 $this->date_modification = $this->db->jdate($obj->datem);
2070 }
2071 $this->db->free($result);
2072 } else {
2073 dol_print_error($this->db);
2074 }
2075 }
2076
2085 public function initAsSpecimen($option = '')
2086 {
2087 global $langs;
2088
2089 $now = dol_now();
2090 $arraynow = dol_getdate($now);
2091 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
2092
2093 // Load array of products prodids
2094 $num_prods = 0;
2095 $prodids = array();
2096
2097 $sql = "SELECT rowid";
2098 $sql .= " FROM ".MAIN_DB_PREFIX."product";
2099 $sql .= " WHERE entity IN (".getEntity('product').")";
2100 $sql .= $this->db->plimit(100);
2101
2102 $resql = $this->db->query($sql);
2103 if ($resql) {
2104 $num_prods = $this->db->num_rows($resql);
2105 $i = 0;
2106 while ($i < $num_prods) {
2107 $i++;
2108 $row = $this->db->fetch_row($resql);
2109 $prodids[$i] = $row[0];
2110 }
2111 }
2112
2113 // Initialize parameters
2114 $this->id = 0;
2115 $this->ref = 'SPECIMEN';
2116 $this->title = 'SPECIMEN';
2117 $this->specimen = 1;
2118 $this->socid = 1;
2119 $this->date = $nownotime;
2120 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
2121 $this->cond_reglement_id = 1;
2122 $this->cond_reglement_code = 'RECEP';
2123 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
2124 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
2125 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
2126 $this->note_public = 'This is a comment (public)';
2127 $this->note_private = 'This is a comment (private)';
2128 $this->fk_incoterms = 0;
2129 $this->location_incoterms = '';
2130
2131 if (empty($option) || $option != 'nolines') {
2132 // Lines
2133 $nbp = min(1000, GETPOSTINT('nblines') ? GETPOSTINT('nblines') : 5); // We can force the nb of lines to test from command line (but not more than 1000)
2134 $xnbp = 0;
2135 while ($xnbp < $nbp) {
2136 $line = new FactureLigne($this->db);
2137 $line->desc = $langs->trans("Description")." ".$xnbp;
2138 $line->qty = 1;
2139 $line->subprice = 100;
2140 $line->tva_tx = 19.6;
2141 $line->localtax1_tx = 0;
2142 $line->localtax2_tx = 0;
2143 $line->remise_percent = 0;
2144 if ($xnbp == 1) { // Qty is negative (product line)
2145 $prodid = mt_rand(1, $num_prods);
2146 $line->fk_product = $prodids[$prodid];
2147 $line->qty = -1;
2148 $line->total_ht = -100;
2149 $line->total_ttc = -119.6;
2150 $line->total_tva = -19.6;
2151 } elseif ($xnbp == 2) { // UP is negative (free line)
2152 $line->subprice = -100;
2153 $line->total_ht = -100;
2154 $line->total_ttc = -119.6;
2155 $line->total_tva = -19.6;
2156 $line->remise_percent = 0;
2157 } elseif ($xnbp == 3) { // Discount is 50% (product line)
2158 $prodid = mt_rand(1, $num_prods);
2159 $line->fk_product = $prodids[$prodid];
2160 $line->total_ht = 50;
2161 $line->total_ttc = 59.8;
2162 $line->total_tva = 9.8;
2163 $line->remise_percent = 50;
2164 } else { // (product line)
2165 $prodid = mt_rand(1, $num_prods);
2166 $line->fk_product = $prodids[$prodid];
2167 $line->total_ht = 100;
2168 $line->total_ttc = 119.6;
2169 $line->total_tva = 19.6;
2170 $line->remise_percent = 00;
2171 }
2172
2173 $this->lines[$xnbp] = $line;
2174 $xnbp++;
2175
2176 $this->total_ht += $line->total_ht;
2177 $this->total_tva += $line->total_tva;
2178 $this->total_ttc += $line->total_ttc;
2179 }
2180 $this->revenuestamp = 0;
2181
2182 // Add a line "offered"
2183 $line = new FactureLigne($this->db);
2184 $line->desc = $langs->trans("Description")." (offered line)";
2185 $line->qty = 1;
2186 $line->subprice = 100;
2187 $line->tva_tx = 19.6;
2188 $line->localtax1_tx = 0;
2189 $line->localtax2_tx = 0;
2190 $line->remise_percent = 100;
2191 $line->total_ht = 0;
2192 $line->total_ttc = 0; // 90 * 1.196
2193 $line->total_tva = 0;
2194 $prodid = mt_rand(1, $num_prods);
2195 $line->fk_product = $prodids[$prodid];
2196
2197 $this->lines[$xnbp] = $line;
2198 $xnbp++;
2199 }
2200
2201 $this->usenewprice = 0;
2202
2203 return 1;
2204 }
2205
2214 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2215 {
2216 $tables = array(
2217 'facture_rec'
2218 );
2219
2220 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2221 }
2222
2231 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
2232 {
2233 $tables = array(
2234 'facturedet_rec'
2235 );
2236
2237 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
2238 }
2239
2248 public function setFrequencyAndUnit($frequency, $unit, $notrigger = 0)
2249 {
2250 global $user;
2251
2252 if (!$this->table_element) {
2253 dol_syslog(get_class($this)."::setFrequencyAndUnit was called on object with property table_element not defined", LOG_ERR);
2254 return -1;
2255 }
2256
2257 if (!empty($frequency) && empty($unit)) {
2258 dol_syslog(get_class($this)."::setFrequencyAndUnit was called on object with params frequency defined but unit not defined", LOG_ERR);
2259 return -2;
2260 }
2261
2262 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2263 $sql .= ' SET frequency = '.($frequency ? $this->db->escape((string) $frequency) : 'null');
2264 if (!empty($unit)) {
2265 $sql .= ', unit_frequency = \''.$this->db->escape($unit).'\'';
2266 }
2267 $sql .= " WHERE rowid = ".((int) $this->id);
2268
2269 dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG);
2270 if ($this->db->query($sql)) {
2271 $this->frequency = $frequency;
2272 if (!empty($unit)) {
2273 $this->unit_frequency = $unit;
2274 }
2275
2276 if (!$notrigger) {
2277 // Call trigger
2278 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2279 if ($result < 0) {
2280 return $result;
2281 }
2282 // End call triggers
2283 }
2284
2285 return 1;
2286 } else {
2287 dol_print_error($this->db);
2288 return -1;
2289 }
2290 }
2291
2300 public function setNextDate($date, $increment_nb_gen_done = 0, $notrigger = 0)
2301 {
2302 global $user;
2303
2304 if (!$this->table_element) {
2305 dol_syslog(get_class($this)."::setNextDate was called on object with property table_element not defined", LOG_ERR);
2306 return -1;
2307 }
2308 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2309 $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null");
2310 if ($increment_nb_gen_done > 0) {
2311 $sql .= ', nb_gen_done = nb_gen_done + 1';
2312 }
2313 $sql .= " WHERE rowid = ".((int) $this->id);
2314
2315 dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG);
2316 if ($this->db->query($sql)) {
2317 $this->date_when = $date;
2318 if ($increment_nb_gen_done > 0) {
2319 $this->nb_gen_done++;
2320
2321 if (getDolGlobalInt('MAIN_SUSPEND_FACTURE_REC_ON_MAX_GEN_REACHED') && $this->isMaxNbGenReached()) {
2322 $resSuspend = $this->setValueFrom('suspended', 1);
2323
2324 if ($resSuspend <= 0) {
2325 dol_syslog(__METHOD__ . '::setValueFrom Error : ' . $this->error, LOG_ERR);
2326 return -1;
2327 }
2328 }
2329 }
2330
2331 if (!$notrigger) {
2332 if (empty($this->context['actionmsgmore'])) {
2333 $this->context['actionmsgmore'] = 'Trigger called by setNextDate';
2334 }
2335
2336 // Call trigger
2337 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2338 if ($result < 0) {
2339 return $result;
2340 }
2341 // End call triggers
2342 }
2343 return 1;
2344 } else {
2345 dol_print_error($this->db);
2346 return -1;
2347 }
2348 }
2349
2357 public function setMaxPeriod($nb, $notrigger = 0)
2358 {
2359 global $user;
2360
2361 if (!$this->table_element) {
2362 dol_syslog(get_class($this)."::setMaxPeriod was called on object with property table_element not defined", LOG_ERR);
2363 return -1;
2364 }
2365
2366 if (empty($nb)) {
2367 $nb = 0;
2368 }
2369
2370 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2371 $sql .= ' SET nb_gen_max = '.((int) $nb);
2372 $sql .= " WHERE rowid = ".((int) $this->id);
2373
2374 dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG);
2375 if ($this->db->query($sql)) {
2376 $this->nb_gen_max = $nb;
2377
2378 if (!$notrigger) {
2379 // Call trigger
2380 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2381 if ($result < 0) {
2382 return $result;
2383 }
2384 // End call triggers
2385 }
2386
2387 return 1;
2388 } else {
2389 dol_print_error($this->db);
2390 return -1;
2391 }
2392 }
2393
2401 public function setAutoValidate($validate, $notrigger = 0)
2402 {
2403 global $user;
2404
2405 if (!$this->table_element) {
2406 dol_syslog(get_class($this)."::setAutoValidate was called on object with property table_element not defined", LOG_ERR);
2407 return -1;
2408 }
2409
2410 $this->auto_validate = $validate;
2411
2412 $result = $this->update($user);
2413
2414 dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG);
2415 if ($result > 0) {
2416 return 1;
2417 } else {
2418 dol_print_error($this->db);
2419 return -1;
2420 }
2421 }
2422
2430 public function setGeneratePdf($validate, $notrigger = 0)
2431 {
2432 global $user;
2433
2434 if (!$this->table_element) {
2435 dol_syslog(get_class($this)."::setGeneratePdf was called on object with property table_element not defined", LOG_ERR);
2436 return -1;
2437 }
2438
2439 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2440 $sql .= ' SET generate_pdf = '.((int) $validate);
2441 $sql .= " WHERE rowid = ".((int) $this->id);
2442
2443 dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG);
2444 if ($this->db->query($sql)) {
2445 $this->generate_pdf = $validate;
2446
2447 if (!$notrigger) {
2448 // Call trigger
2449 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2450 if ($result < 0) {
2451 return $result;
2452 }
2453 // End call triggers
2454 }
2455
2456 return 1;
2457 } else {
2458 dol_print_error($this->db);
2459 return -1;
2460 }
2461 }
2462
2470 public function setModelPdf($model, $notrigger = 0)
2471 {
2472 global $user;
2473 if (!$this->table_element) {
2474 dol_syslog(get_class($this)."::setModelPdf was called on object with property table_element not defined", LOG_ERR);
2475 return -1;
2476 }
2477
2478 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2479 $sql .= " SET modelpdf = '".$this->db->escape($model)."'";
2480 $sql .= " WHERE rowid = ".((int) $this->id);
2481
2482 dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG);
2483 if ($this->db->query($sql)) {
2484 $this->model_pdf = $model;
2485
2486 if (!$notrigger) {
2487 // Call trigger
2488 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2489 if ($result < 0) {
2490 return $result;
2491 }
2492 // End call triggers
2493 }
2494
2495 return 1;
2496 } else {
2497 dol_print_error($this->db);
2498 return -1;
2499 }
2500 }
2501
2509 public function setMailTemplate($idEmailTemplate, $notrigger = 0): int
2510 {
2511 global $user;
2512 if (!$this->table_element) {
2513 dol_syslog(get_class($this)."::setMailTemplate was called on object with property table_element not defined", LOG_ERR);
2514 return -1;
2515 }
2516
2517 $this->fk_email_template = $idEmailTemplate;
2518 $result = $this->update($user);
2519
2520 dol_syslog(get_class($this)."::setMailTemplate", LOG_DEBUG);
2521 if ($result > 0) {
2522 if (!$notrigger) {
2523 // Call trigger
2524 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2525 if ($result < 0) {
2526 return $result;
2527 }
2528 // End call triggers
2529 }
2530
2531 return 1;
2532 } else {
2533 dol_print_error($this->db);
2534 return -1;
2535 }
2536 }
2537
2545 public function hasUserPermission(User $user, $mode = 'write')
2546 {
2547 if ($mode == 'create') {
2548 $mode = 'write';
2549 }
2550 if (!in_array($mode, array('read', 'write', 'delete'))) {
2551 return false;
2552 }
2553
2554 return (bool) $user->hasRight("facture", $mode);
2555 }
2556}
2557
2558
2559
2565{
2569 public $element = 'facturedetrec';
2570
2574 public $table_element = 'facturedet_rec';
2575
2579 public $parent_element = 'facturerec';
2580
2584 public $fk_parent_attribute = 'fk_facture';
2585
2587
2590 public $fk_facture;
2594 public $fk_parent_line;
2595
2599 public $fk_product_fournisseur_price;
2604 public $fk_fournprice;
2605
2609 public $rang;
2610 //public $situation_percent; // Not supported on recurring invoice line
2611
2615 public $desc;
2619 public $description;
2620
2625 public $fk_product_type;
2626
2630 public $fk_contract_line;
2631
2635 public $skip_update_total;
2636
2644 public function delete(User $user, $notrigger = 0)
2645 {
2646 $error = 0;
2647
2648 $this->db->begin();
2649
2650 if (!$error) {
2651 if (!$notrigger) {
2652 // Call triggers
2653 $result = $this->call_trigger('LINEBILLREC_DELETE', $user);
2654 if ($result < 0) {
2655 $error++;
2656 } // Do also here what you must do to rollback action if trigger fail
2657 // End call triggers
2658 }
2659 }
2660
2661 if (!$error) {
2662 $result = $this->deleteExtraFields();
2663 if ($result < 0) {
2664 $error++;
2665 }
2666 }
2667
2668 if (!$error) {
2669 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
2670
2671 $res = $this->db->query($sql);
2672 if (!$res) {
2673 $error++;
2674 $this->errors[] = $this->db->lasterror();
2675 }
2676 }
2677
2678 // Commit or rollback
2679 if ($error) {
2680 $this->db->rollback();
2681 return -1;
2682 } else {
2683 $this->db->commit();
2684 return 1;
2685 }
2686 }
2687
2688
2695 public function fetch($rowid)
2696 {
2697 $sql = 'SELECT l.rowid, l.fk_facture, l.fk_parent_line, 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,';
2698 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
2699 $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,';
2700 $sql .= ' l.rang, l.special_code,';
2701 $sql .= ' l.fk_unit, l.fk_contract_line,';
2702 $sql .= ' l.import_key, l.fk_multicurrency,';
2703 $sql .= ' l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2704 $sql .= ' l.buy_price_ht, l.fk_product_fournisseur_price,';
2705 $sql .= ' l.fk_user_author, l.fk_user_modif, l.extraparams,';
2706 $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2707 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
2708 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
2709 $sql .= ' WHERE l.rowid = '.((int) $rowid);
2710 $sql .= ' ORDER BY l.rang';
2711
2712 dol_syslog('FactureRec::fetch', LOG_DEBUG);
2713 $result = $this->db->query($sql);
2714 if ($result) {
2715 $objp = $this->db->fetch_object($result);
2716
2717 $this->id = $objp->rowid;
2718 $this->fk_facture = $objp->fk_facture;
2719 $this->fk_parent_line = $objp->fk_parent_line;
2720 $this->label = $objp->custom_label; // Label line
2721 $this->desc = $objp->description; // Description line
2722 $this->description = $objp->description; // Description line
2723 $this->product_type = $objp->product_type; // Type of line
2724 $this->ref = $objp->product_ref; // Ref product
2725 $this->product_ref = $objp->product_ref; // Ref product
2726 $this->libelle = $objp->product_label; // deprecated
2727 $this->product_label = $objp->product_label; // Label product
2728 $this->product_desc = $objp->product_desc; // Description product
2729 $this->fk_product_type = $objp->fk_product_type; // Type of product
2730 $this->qty = $objp->qty;
2731 $this->price = $objp->price;
2732 $this->subprice = $objp->subprice;
2733 $this->vat_src_code = $objp->vat_src_code;
2734 $this->tva_tx = $objp->tva_tx;
2735 $this->localtax1_tx = $objp->localtax1_tx;
2736 $this->localtax2_tx = $objp->localtax2_tx;
2737 $this->localtax1_type = $objp->localtax1_type;
2738 $this->localtax2_type = $objp->localtax2_type;
2739 $this->remise_percent = $objp->remise_percent;
2740 //$this->fk_remise_except = $objp->fk_remise_except;
2741 $this->fk_product = $objp->fk_product;
2742 $this->date_start_fill = $objp->date_start_fill;
2743 $this->date_end_fill = $objp->date_end_fill;
2744 $this->info_bits = $objp->info_bits;
2745 $this->total_ht = $objp->total_ht;
2746 $this->total_tva = $objp->total_tva;
2747 $this->total_ttc = $objp->total_ttc;
2748
2749 $this->rang = $objp->rang;
2750 $this->special_code = $objp->special_code;
2751 $this->fk_unit = $objp->fk_unit;
2752 $this->fk_contract_line = $objp->fk_contract_line;
2753 $this->import_key = $objp->import_key;
2754 $this->fk_multicurrency = $objp->fk_multicurrency;
2755 $this->multicurrency_code = $objp->multicurrency_code;
2756 $this->multicurrency_subprice = $objp->multicurrency_subprice;
2757 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
2758 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
2759 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2760
2761 $this->buy_price_ht = $objp->buy_price_ht;
2762
2763 $this->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
2764 $this->fk_user_author = $objp->fk_user_author;
2765 $this->fk_user_modif = $objp->fk_user_modif;
2766
2767 $this->db->free($result);
2768 return 1;
2769 } else {
2770 $this->error = $this->db->lasterror();
2771 return -3;
2772 }
2773 }
2774
2775
2783 public function update(User $user, $notrigger = 0)
2784 {
2785 $error = 0;
2786
2787 // Clean parameters
2788 if (empty($this->fk_parent_line)) {
2789 $this->fk_parent_line = 0;
2790 }
2791
2792 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2793
2794 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET";
2795 $sql .= " fk_facture = ".((int) $this->fk_facture);
2796 $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? ((int) $this->fk_parent_line) : "null");
2797 $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
2798 $sql .= ", description='".$this->db->escape($this->desc)."'";
2799 $sql .= ", price=".price2num($this->price);
2800 $sql .= ", qty=".price2num($this->qty);
2801 $sql .= ", tva_tx=".price2num($this->tva_tx);
2802 $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'";
2803 $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
2804 $sql .= ", localtax1_type='".$this->db->escape((string) $this->localtax1_type)."'";
2805 $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
2806 $sql .= ", localtax2_type='".$this->db->escape((string) $this->localtax2_type)."'";
2807 $sql .= ", fk_product=".($this->fk_product > 0 ? ((int) $this->fk_product) : "null");
2808 $sql .= ", product_type=".((int) $this->product_type);
2809 $sql .= ", remise_percent=".price2num($this->remise_percent);
2810 $sql .= ", subprice=".price2num($this->subprice);
2811 $sql .= ", info_bits=".price2num($this->info_bits);
2812 $sql .= ", date_start_fill=".(int) $this->date_start_fill;
2813 $sql .= ", date_end_fill=".(int) $this->date_end_fill;
2814 if (empty($this->skip_update_total)) {
2815 $sql .= ", total_ht=".price2num($this->total_ht);
2816 $sql .= ", total_tva=".price2num($this->total_tva);
2817 $sql .= ", total_localtax1=".price2num($this->total_localtax1);
2818 $sql .= ", total_localtax2=".price2num($this->total_localtax2);
2819 $sql .= ", total_ttc=".price2num($this->total_ttc);
2820 }
2821 $sql .= ", rang=".((int) $this->rang);
2822 $sql .= ", special_code=".((int) $this->special_code);
2823 $sql .= ", fk_unit=".($this->fk_unit ? "'".$this->db->escape((string) $this->fk_unit)."'" : "null");
2824 $sql .= ", fk_contract_line=".($this->fk_contract_line ? ((int) $this->fk_contract_line) : "null");
2825 $sql .= " WHERE rowid = ".((int) $this->id);
2826
2827 $this->db->begin();
2828
2829 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
2830
2831 $resql = $this->db->query($sql);
2832 if ($resql) {
2833 if (!$error) {
2834 $result = $this->insertExtraFields();
2835 if ($result < 0) {
2836 $error++;
2837 }
2838 }
2839
2840 if (!$error && !$notrigger) {
2841 // Call trigger
2842 $result = $this->call_trigger('LINEBILLREC_MODIFY', $user);
2843 if ($result < 0) {
2844 $error++;
2845 }
2846 // End call triggers
2847 }
2848
2849 if ($error) {
2850 $this->db->rollback();
2851 return -2;
2852 } else {
2853 $this->db->commit();
2854 return 1;
2855 }
2856 } else {
2857 $this->error = $this->db->lasterror();
2858 $this->db->rollback();
2859 return -2;
2860 }
2861 }
2862}
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice 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...
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
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=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
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.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
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.
Class to manage Dolibarr database access.
Class to manage invoices.
const STATUS_VALIDATED
Validated (need to be paid)
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.
setFrequencyAndUnit($frequency, $unit, $notrigger=0)
Update frequency and unit.
getLibStatut($mode=0, $alreadypaid=-1)
Return label of object status.
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=0, $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, $fk_parent_line=0)
Update a line to invoice.
LibStatut($recur, $status, $mode=0, $alreadypaid=-1, $type=0, $nbofopendirectdebitorcredittransfer=0)
Return label of a status.
fetch_lines()
Get lines of template invoices into this->lines.
info($id)
Load miscellaneous information for tab "Info".
getLinesArray()
Create an array of invoice lines.
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=0, $save_lastsearch_value=-1)
Return clickable name (with picto eventually)
isMaxNbGenReached()
Return if maximum number of generation is reached.
createRecurringInvoices($restrictioninvoiceid=0, $forcevalidation=0, $notrigger=0, $forcebuilddoc=0)
Create all recurrents invoices (for all entities if multicompany is used).
setModelPdf($model, $notrigger=0)
Update the model for documents.
setMailTemplate($idEmailTemplate, $notrigger=0)
Update the email template.
getNextNumRef($soc, $mode='next')
Return next reference of invoice not already used (or last reference)
hasUserPermission(User $user, $mode='write')
Check if user has a permission on template customer invoices.
__construct(DoliDB $db)
Constructor.
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=0, $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, $fk_parent_line=0, $array_options=array())
Add a line to invoice.
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.
create($user, $facid, $notrigger=0, $onlylines=array())
Create a predefined invoice.
strikeIfMaxNbGenReached($ret)
Format string to output with by striking the string if max number of generations was reached.
fetch($rowid, $ref='', $ref_ext='', $noextrafields=0, $nolines=0)
Load object and lines.
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 execution Handles end-of-month scenarios when day >= 28 for monthly recurring...
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage products or services.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
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_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
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.
getDolGlobalInt($key, $default=0)
Return a 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.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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)
Definition html.lib.php:183
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492