dolibarr 24.0.0-beta
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' => 'Fk projet', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 85),
270 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'Fk cond reglement', 'enabled' => 1, 'visible' => -1, 'position' => 90),
271 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'Fk mode reglement', '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' => 'Fk account', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 175),
289 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', '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' => 'Fk Societe 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 $this->suspended = $obj->suspended;
698 $this->total_ht = $obj->total_ht;
699 $this->total_tva = $obj->total_tva;
700 $this->total_localtax1 = $obj->localtax1;
701 $this->total_localtax2 = $obj->localtax2;
702 $this->total_ttc = $obj->total_ttc;
703 $this->socid = $obj->fk_soc;
704 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
705 $this->mode_reglement_id = $obj->fk_mode_reglement;
706 $this->mode_reglement_code = $obj->mode_reglement_code;
707 $this->mode_reglement = $obj->mode_reglement_libelle;
708 $this->cond_reglement_id = $obj->fk_cond_reglement;
709 $this->cond_reglement_code = $obj->cond_reglement_code;
710 $this->cond_reglement = $obj->cond_reglement_libelle;
711 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
712 $this->fk_project = $obj->fk_project;
713 $this->fk_account = $obj->fk_account;
714 $this->fk_societe_rib = $obj->fk_societe_rib;
715 $this->note_private = $obj->note_private;
716 $this->note_public = $obj->note_public;
717 $this->user_creation_id = $obj->fk_user_author;
718 $this->model_pdf = $obj->model_pdf;
719 //$this->special_code = $obj->special_code;
720 $this->frequency = $obj->frequency;
721 $this->unit_frequency = $obj->unit_frequency;
722 $this->rule_for_lines_dates = $obj->rule_for_lines_dates;
723 $this->date_when = $this->db->jdate($obj->date_when);
724 $this->date_last_gen = $this->db->jdate($obj->date_last_gen);
725 $this->nb_gen_done = $obj->nb_gen_done;
726 $this->nb_gen_max = $obj->nb_gen_max;
727 $this->usenewprice = $obj->usenewprice;
728 $this->auto_validate = $obj->auto_validate;
729 $this->fk_email_template = $obj->fk_email_template;
730 $this->generate_pdf = $obj->generate_pdf;
731
732 // Multicurrency
733 $this->fk_multicurrency = $obj->fk_multicurrency;
734 $this->multicurrency_code = $obj->multicurrency_code;
735 $this->multicurrency_tx = $obj->multicurrency_tx;
736 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
737 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
738 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
739
740 // Retrieve all extrafield
741 // fetch optionals attributes and labels
742 if (empty($noextrafields)) {
743 $result = $this->fetch_optionals();
744 if ($result < 0) {
745 $this->error = $this->db->lasterror();
746 return -4;
747 }
748 }
749
750 // Retrieve lines
751 if (empty($nolines)) {
752 $result = $this->fetch_lines();
753 if ($result < 0) {
754 $this->error = $this->db->lasterror();
755 return -3;
756 }
757 }
758
759 return 1;
760 } else {
761 $this->error = 'Bill with id '.$rowid.' or ref '.$ref.' not found';
762 dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
763 return -2;
764 }
765 } else {
766 $this->error = $this->db->error();
767 return -1;
768 }
769 }
770
771
777 public function getLinesArray()
778 {
779 return $this->fetch_lines();
780 }
781
782
783 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
789 public function fetch_lines()
790 {
791 // phpcs:enable
792
793 $this->lines = array();
794
795 dol_syslog('FactureRec::fetch_lines', LOG_DEBUG);
796
797 $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, ';
798 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
799 $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,';
800 $sql .= ' l.rang, l.special_code,';
801 $sql .= ' l.fk_unit, l.fk_contract_line, l.extraparams,';
802 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
803 $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
804 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
805 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
806 $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
807 $sql .= ' ORDER BY l.rang';
808
809 $result = $this->db->query($sql);
810 if ($result) {
811 $num = $this->db->num_rows($result);
812 $i = 0;
813 while ($i < $num) {
814 $objp = $this->db->fetch_object($result);
815 $line = new FactureLigneRec($this->db);
816
817 $line->id = $objp->rowid;
818 $line->rowid = $objp->rowid;
819 $line->fk_facture = $objp->fk_facture;
820 $line->fk_parent_line = $objp->fk_parent_line;
821 $line->desc = $objp->description; // Description line
822 $line->description = $objp->description; // Description line
823 $line->ref = $objp->product_ref; // Ref product
824 $line->product_ref = $objp->product_ref; // Ref product
825 $line->libelle = $objp->product_label; // deprecated
826 $line->product_label = $objp->product_label; // Label product
827 $line->product_desc = $objp->product_desc; // Description product
828 $line->product_type = $objp->product_type; // Type of line
829 $line->fk_product_type = $objp->fk_product_type; // Type of product
830 $line->qty = $objp->qty;
831 $line->subprice = $objp->subprice;
832
833 $line->label = $objp->custom_label; // @deprecated
834
835 $line->vat_src_code = $objp->vat_src_code;
836 $line->tva_tx = $objp->tva_tx;
837 $line->localtax1_tx = $objp->localtax1_tx;
838 $line->localtax2_tx = $objp->localtax2_tx;
839 $line->localtax1_type = $objp->localtax1_type;
840 $line->localtax2_type = $objp->localtax2_type;
841 $line->remise_percent = $objp->remise_percent;
842 //$line->fk_remise_except = $objp->fk_remise_except;
843 $line->fk_product = $objp->fk_product;
844 $line->date_start_fill = $objp->date_start_fill;
845 $line->date_end_fill = $objp->date_end_fill;
846 $line->info_bits = $objp->info_bits;
847 $line->total_ht = $objp->total_ht;
848 $line->total_tva = $objp->total_tva;
849 $line->total_ttc = $objp->total_ttc;
850
851 $line->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
852 $line->fk_fournprice = $objp->fk_product_fournisseur_price; // For backward compatibility
853
854 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_product_fournisseur_price, $objp->pa_ht);
855
856 $line->buyprice = $marginInfos[0];
857 $line->pa_ht = $marginInfos[0]; // For backward compatibility
858 $line->marge_tx = (string) $marginInfos[1];
859 $line->marque_tx = (string) $marginInfos[2];
860 $line->rang = $objp->rang;
861 $line->special_code = $objp->special_code;
862 $line->fk_unit = $objp->fk_unit;
863 $line->fk_contract_line = $objp->fk_contract_line;
864
865 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
866
867 // Ne plus utiliser
868 $line->price = $objp->price;
869 $line->remise = $objp->remise;
870
871 $line->fetch_optionals();
872
873 // Multicurrency
874 $line->fk_multicurrency = $objp->fk_multicurrency;
875 $line->multicurrency_code = $objp->multicurrency_code;
876 $line->multicurrency_subprice = $objp->multicurrency_subprice;
877 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
878 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
879 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
880
881 $this->lines[$i] = $line;
882
883 $i++;
884 }
885
886 $this->db->free($result);
887 return 1;
888 } else {
889 $this->error = $this->db->lasterror();
890 return -3;
891 }
892 }
893
894
903 public function delete(User $user, $notrigger = 0, $idwarehouse = -1)
904 {
905 $rowid = $this->id;
906
907 dol_syslog(get_class($this)."::delete rowid=".((int) $rowid), LOG_DEBUG);
908
909 $error = 0;
910 $this->db->begin();
911
912 $main = MAIN_DB_PREFIX.'facturedet_rec';
913 $ef = $main."_extrafields";
914
915 $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
916 $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".((int) $rowid);
917
918 if ($this->db->query($sqlef) && $this->db->query($sql)) {
919 $sql = "DELETE FROM ".MAIN_DB_PREFIX."facture_rec WHERE rowid = ".((int) $rowid);
920 dol_syslog($sql);
921 if ($this->db->query($sql)) {
922 // Delete linked object
923 $res = $this->deleteObjectLinked();
924 if ($res < 0) {
925 $error = -3;
926 }
927 // Delete extrafields
928 $res = $this->deleteExtraFields();
929 if ($res < 0) {
930 $error = -4;
931 }
932 } else {
933 $this->error = $this->db->lasterror();
934 $error = -1;
935 }
936 } else {
937 $this->error = $this->db->lasterror();
938 $error = -2;
939 }
940 if (!$error && !$notrigger) {
941 // Call trigger
942 $result = $this->call_trigger('BILLREC_DELETE', $user);
943 if ($result < 0) {
944 $error++;
945 }
946 // End call triggers
947 }
948 if (!$error) {
949 $this->db->commit();
950 return 1;
951 } else {
952 $this->db->rollback();
953 return $error;
954 }
955 }
956
957
986 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)
987 {
988 global $mysoc;
989
990 $facid = $this->id;
991
992 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);
993 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
994
995 // Check parameters
996 if ($type < 0) {
997 return -1;
998 }
999
1000 $localtaxes_type = getLocalTaxesFromRate((float) $txtva, 0, $this->thirdparty, $mysoc);
1001
1002 // Clean vat code
1003 $reg = array();
1004 $vat_src_code = '';
1005 if (preg_match('/\‍((.*)\‍)/', (string) $txtva, $reg)) {
1006 $vat_src_code = $reg[1];
1007 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', (string) $txtva); // Remove code from vatrate.
1008 }
1009
1010
1011 // Clean parameters
1012 $remise_percent = price2num($remise_percent);
1013 if (empty($remise_percent)) {
1014 $remise_percent = 0;
1015 }
1016 $qty = (float) price2num($qty);
1017 $pu_ht = (float) price2num($pu_ht);
1018 $pu_ttc = (float) price2num($pu_ttc);
1019 if (!preg_match('/\‍((.*)\‍)/', $txtva)) {
1020 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
1021 }
1022 $txlocaltax1 = (float) price2num($txlocaltax1);
1023 $txlocaltax2 = (float) price2num($txlocaltax2);
1024 if (empty($txtva)) {
1025 $txtva = 0;
1026 }
1027 if (empty($txlocaltax1)) {
1028 $txlocaltax1 = 0;
1029 }
1030 if (empty($txlocaltax2)) {
1031 $txlocaltax2 = 0;
1032 }
1033 if (empty($info_bits)) {
1034 $info_bits = 0;
1035 }
1036
1037 if ($price_base_type == 'HT') {
1038 $pu = $pu_ht;
1039 } else {
1040 $pu = $pu_ttc;
1041 }
1042
1043 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1044 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1045 // and this is done at the line level, which has its own VAT rate
1046
1047 $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);
1048 $total_ht = $tabprice[0];
1049 $total_tva = $tabprice[1];
1050 $total_ttc = $tabprice[2];
1051 $total_localtax1 = $tabprice[9];
1052 $total_localtax2 = $tabprice[10];
1053 $pu_ht = $tabprice[3];
1054
1055 // MultiCurrency
1056 $multicurrency_total_ht = $tabprice[16];
1057 $multicurrency_total_tva = $tabprice[17];
1058 $multicurrency_total_ttc = $tabprice[18];
1059 $pu_ht_devise = $tabprice[19];
1060
1061 $product_type = $type;
1062 if ($fk_product) {
1063 $product = new Product($this->db);
1064 $result = $product->fetch($fk_product);
1065 $product_type = $product->type;
1066 }
1067
1068 if (empty($fk_parent_line) || $fk_parent_line < 0) {
1069 $fk_parent_line = 0;
1070 }
1071
1072 // Rank to use
1073 $ranktouse = $rang;
1074 if ($ranktouse == -1) {
1075 $rangmax = $this->line_max(0);
1076 $ranktouse = $rangmax + 1;
1077 }
1078
1079 $sql = "INSERT INTO ".MAIN_DB_PREFIX."facturedet_rec (";
1080 $sql .= "fk_facture";
1081 $sql .= ", fk_parent_line";
1082 $sql .= ", label";
1083 $sql .= ", description";
1084 $sql .= ", price";
1085 $sql .= ", qty";
1086 $sql .= ", tva_tx";
1087 $sql .= ", vat_src_code";
1088 $sql .= ", localtax1_tx";
1089 $sql .= ", localtax1_type";
1090 $sql .= ", localtax2_tx";
1091 $sql .= ", localtax2_type";
1092 $sql .= ", fk_product";
1093 $sql .= ", product_type";
1094 $sql .= ", remise_percent";
1095 $sql .= ", subprice";
1096 $sql .= ", remise";
1097 $sql .= ", total_ht";
1098 $sql .= ", total_tva";
1099 $sql .= ", total_localtax1";
1100 $sql .= ", total_localtax2";
1101 $sql .= ", total_ttc";
1102 $sql .= ", date_start_fill";
1103 $sql .= ", date_end_fill";
1104 $sql .= ", fk_product_fournisseur_price";
1105 $sql .= ", buy_price_ht";
1106 $sql .= ", info_bits";
1107 $sql .= ", rang";
1108 $sql .= ", special_code";
1109 $sql .= ", fk_unit";
1110 $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
1111 $sql .= ") VALUES (";
1112 $sql .= " ".((int) $facid);
1113 $sql .= ", ".($fk_parent_line > 0 ? ((int) $fk_parent_line) : "null");
1114 $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
1115 $sql .= ", '".$this->db->escape($desc)."'";
1116 $sql .= ", ".price2num($pu_ht);
1117 $sql .= ", ".price2num($qty);
1118 $sql .= ", ".price2num($txtva);
1119 $sql .= ", '".$this->db->escape($vat_src_code)."'";
1120 $sql .= ", ".price2num($txlocaltax1);
1121 $sql .= ", '".$this->db->escape(isset($localtaxes_type[0]) ? $localtaxes_type[0] : '')."'";
1122 $sql .= ", ".price2num($txlocaltax2);
1123 $sql .= ", '".$this->db->escape(isset($localtaxes_type[2]) ? $localtaxes_type[2] : '')."'";
1124 $sql .= ", ".(!empty($fk_product) ? "'".$this->db->escape((string) $fk_product)."'" : "null");
1125 $sql .= ", ".((int) $product_type);
1126 $sql .= ", ".price2num($remise_percent);
1127 $sql .= ", ".price2num($pu_ht);
1128 $sql .= ", null";
1129 $sql .= ", ".price2num($total_ht);
1130 $sql .= ", ".price2num($total_tva);
1131 $sql .= ", ".price2num($total_localtax1);
1132 $sql .= ", ".price2num($total_localtax2);
1133 $sql .= ", ".price2num($total_ttc);
1134 $sql .= ", ".(int) $date_start_fill;
1135 $sql .= ", ".(int) $date_end_fill;
1136 $sql .= ", ".($fk_fournprice > 0 ? $fk_fournprice : 'null');
1137 $sql .= ", ".($pa_ht ? price2num($pa_ht) : 0);
1138 $sql .= ", ".((int) $info_bits);
1139 $sql .= ", ".((int) $ranktouse);
1140 $sql .= ", ".((int) $special_code);
1141 $sql .= ", ".($fk_unit ? ((int) $fk_unit) : "null");
1142 $sql .= ", ".(int) $this->fk_multicurrency;
1143 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1144 $sql .= ", ".price2num($pu_ht_devise, 'CU');
1145 $sql .= ", ".price2num($multicurrency_total_ht, 'CT');
1146 $sql .= ", ".price2num($multicurrency_total_tva, 'CT');
1147 $sql .= ", ".price2num($multicurrency_total_ttc, 'CT');
1148 $sql .= ")";
1149
1150 dol_syslog(get_class($this)."::addline", LOG_DEBUG);
1151 if ($this->db->query($sql)) {
1152 $lineId = $this->db->last_insert_id(MAIN_DB_PREFIX."facturedet_rec");
1153 $this->id = $facid;
1154 $this->update_price(1);
1155 return $lineId;
1156 } else {
1157 $this->error = $this->db->lasterror();
1158 return -1;
1159 }
1160 }
1161
1192 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)
1193 {
1194 global $mysoc;
1195
1196 $facid = $this->id;
1197
1198 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);
1199 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1200
1201 // Clean parameters
1202 if (empty($remise_percent)) {
1203 $remise_percent = 0;
1204 }
1205
1206 // Check parameters
1207 if ($type < 0) {
1208 return -1;
1209 }
1210
1211 // Clean parameters
1212 $remise_percent = (float) price2num($remise_percent);
1213 $qty = (float) price2num($qty);
1214 if (empty($info_bits)) {
1215 $info_bits = 0;
1216 }
1217 $pu_ht = (float) price2num($pu_ht);
1218 $pu_ttc = (float) price2num($pu_ttc);
1219 $pu_ht_devise = (float) price2num($pu_ht_devise);
1220 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
1221 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
1222 }
1223 $txlocaltax1 = (float) price2num($txlocaltax1);
1224 $txlocaltax2 = (float) price2num($txlocaltax2);
1225 if (empty($txlocaltax1)) {
1226 $txlocaltax1 = 0;
1227 }
1228 if (empty($txlocaltax2)) {
1229 $txlocaltax2 = 0;
1230 }
1231
1232 if (empty($this->multicurrency_subprice)) {
1233 $this->multicurrency_subprice = 0;
1234 }
1235 if (empty($this->multicurrency_total_ht)) {
1236 $this->multicurrency_total_ht = 0;
1237 }
1238 if (empty($this->multicurrency_total_tva)) {
1239 $this->multicurrency_total_tva = 0;
1240 }
1241 if (empty($this->multicurrency_total_ttc)) {
1242 $this->multicurrency_total_ttc = 0;
1243 }
1244
1245 if ($price_base_type == 'HT') {
1246 $pu = $pu_ht;
1247 } else {
1248 $pu = $pu_ttc;
1249 }
1250
1251 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1252 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1253 // and this is done at the line level, which has its own VAT rate
1254
1255 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
1256
1257 // Clean vat code
1258 $vat_src_code = '';
1259 $reg = array();
1260 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1261 $vat_src_code = $reg[1];
1262 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1263 }
1264
1265 $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);
1266
1267 $total_ht = $tabprice[0];
1268 $total_tva = $tabprice[1];
1269 $total_ttc = $tabprice[2];
1270 $total_localtax1 = $tabprice[9];
1271 $total_localtax2 = $tabprice[10];
1272 $pu_ht = $tabprice[3];
1273 $pu_tva = $tabprice[4];
1274 $pu_ttc = $tabprice[5];
1275
1276 // MultiCurrency
1277 $multicurrency_total_ht = $tabprice[16];
1278 $multicurrency_total_tva = $tabprice[17];
1279 $multicurrency_total_ttc = $tabprice[18];
1280 $pu_ht_devise = $tabprice[19];
1281
1282 $product_type = $type;
1283 if ($fk_product) {
1284 $product = new Product($this->db);
1285 $result = $product->fetch($fk_product);
1286 $product_type = $product->type;
1287 }
1288
1289 if (empty($fk_parent_line) || $fk_parent_line < 0) {
1290 $fk_parent_line = 0;
1291 }
1292
1293 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET ";
1294 $sql .= "fk_facture = ".((int) $facid);
1295 $sql .= ", fk_parent_line = ".($fk_parent_line > 0 ? ((int) $fk_parent_line) : "null");
1296 $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
1297 $sql .= ", description='".$this->db->escape($desc)."'";
1298 $sql .= ", price=".price2num($pu_ht);
1299 $sql .= ", qty=".price2num($qty);
1300 $sql .= ", tva_tx=".price2num($txtva);
1301 $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'";
1302 $sql .= ", localtax1_tx=".((float) $txlocaltax1);
1303 $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'";
1304 $sql .= ", localtax2_tx=".((float) $txlocaltax2);
1305 $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'";
1306 $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape((string) $fk_product)."'" : "null");
1307 $sql .= ", product_type=".((int) $product_type);
1308 $sql .= ", remise_percent='".price2num($remise_percent)."'";
1309 $sql .= ", subprice='".price2num($pu_ht)."'";
1310 $sql .= ", total_ht='".price2num($total_ht)."'";
1311 $sql .= ", total_tva='".price2num($total_tva)."'";
1312 $sql .= ", total_localtax1='".price2num($total_localtax1)."'";
1313 $sql .= ", total_localtax2='".price2num($total_localtax2)."'";
1314 $sql .= ", total_ttc='".price2num($total_ttc)."'";
1315 $sql .= ", date_start_fill=".((int) $date_start_fill);
1316 $sql .= ", date_end_fill=".((int) $date_end_fill);
1317 $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? (int) $fk_fournprice : 'null');
1318 $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0);
1319 $sql .= ", info_bits=".((int) $info_bits);
1320 $sql .= ", rang=".((int) $rang);
1321 $sql .= ", special_code=".((int) $special_code);
1322 $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape((string) $fk_unit)."'" : "null");
1323 $sql .= ', multicurrency_subprice = '.price2num($pu_ht_devise);
1324 $sql .= ', multicurrency_total_ht = '.price2num($multicurrency_total_ht);
1325 $sql .= ', multicurrency_total_tva = '.price2num($multicurrency_total_tva);
1326 $sql .= ', multicurrency_total_ttc = '.price2num($multicurrency_total_ttc);
1327 $sql .= " WHERE rowid = ".((int) $rowid);
1328
1329 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1330 if ($this->db->query($sql)) {
1331 $this->id = $facid;
1332 $this->update_price(1);
1333 return 1;
1334 } else {
1335 $this->error = $this->db->lasterror();
1336 return -1;
1337 }
1338 }
1339
1340
1349 public function getNextDate()
1350 {
1351 if (empty($this->date_when)) {
1352 return false;
1353 }
1354
1355 // Get the original day of the month from date_when
1356 $dateInfo = dol_getdate($this->date_when);
1357 $originalDay = (int) $dateInfo['mday'];
1358 $originalMonth = (int) $dateInfo['mon'];
1359 $originalYear = (int) $dateInfo['year'];
1360 $originalHour = (int) $dateInfo['hours'];
1361 $originalMin = (int) $dateInfo['minutes'];
1362 $originalSec = (int) $dateInfo['seconds'];
1363
1364 // Special handling for end-of-month: if day >= 28 and frequency is monthly
1365 if ($originalDay >= 28 && $this->unit_frequency == 'm') {
1366 // Get the last day of the original month to determine if this was an "end of month" date
1367 $lastDayOfOriginalMonth = (int) date('t', $this->date_when);
1368
1369 // Calculate target month and year
1370 $targetMonth = $originalMonth + (int) $this->frequency;
1371 $targetYear = $originalYear;
1372
1373 // Handle year rollover
1374 while ($targetMonth > 12) {
1375 $targetMonth -= 12;
1376 $targetYear++;
1377 }
1378 while ($targetMonth < 1) {
1379 $targetMonth += 12;
1380 $targetYear--;
1381 }
1382
1383 // Get the last day of the target month
1384 $lastDayOfTargetMonth = (int) date('t', dol_mktime(0, 0, 0, $targetMonth, 1, $targetYear));
1385
1386 // Determine the target day:
1387 // If original was last day of month, OR original day >= 29, use end-of-month behavior
1388 if ($originalDay >= $lastDayOfOriginalMonth || $originalDay >= 29) {
1389 // End of month mode: use the last day of target month
1390 $targetDay = $lastDayOfTargetMonth;
1391 } else {
1392 // Day is 28 but not end of month in a 30/31 day month
1393 // Keep as 28 or use last day if target month is shorter (like February)
1394 $targetDay = min($originalDay, $lastDayOfTargetMonth);
1395 }
1396
1397 // Return the calculated date
1398 return dol_mktime($originalHour, $originalMin, $originalSec, $targetMonth, $targetDay, $targetYear);
1399 }
1400
1401 // For yearly frequency or days < 28, use standard calculation
1402 return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency);
1403 }
1404
1410 public function isMaxNbGenReached()
1411 {
1412 $ret = false;
1413 if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) {
1414 $ret = true;
1415 }
1416 return $ret;
1417 }
1418
1425 public function strikeIfMaxNbGenReached($ret)
1426 {
1427 return $this->isMaxNbGenReached() ? '<strike>'.$ret.'</strike>' : $ret;
1428 }
1429
1442 public function createRecurringInvoices($restrictioninvoiceid = 0, $forcevalidation = 0, $notrigger = 0, $forcebuilddoc = 0)
1443 {
1444 global $conf, $langs, $user, $hookmanager, $action;
1445
1446 $error = 0;
1447 $nb_create = 0;
1448
1449 // Load translation files required by the page
1450 $langs->loadLangs(array("main", "bills"));
1451
1452 $now = dol_now();
1453 $tmparray = dol_getdate($now);
1454 $today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); // Today is last second of current day
1455
1456 $this->output = '';
1457
1458 dol_syslog("createRecurringInvoices restrictioninvoiceid=".$restrictioninvoiceid." forcevalidation=".$forcevalidation." forcebuilddoc=".$forcebuilddoc, LOG_DEBUG);
1459
1460 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec';
1461 $sql .= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency
1462 $sql .= " AND (date_when IS NULL OR date_when <= '".$this->db->idate($today)."')";
1463 $sql .= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)';
1464 $sql .= ' AND suspended = 0';
1465 $sql .= ' AND entity = '.((int) $conf->entity); // MUST STAY = $conf->entity here
1466 if ($restrictioninvoiceid > 0) {
1467 $sql .= ' AND rowid = '.((int) $restrictioninvoiceid);
1468 }
1469 $sql .= $this->db->order('entity', 'ASC');
1470 //print $sql;exit;
1471 $parameters = array(
1472 'restrictioninvoiceid' => $restrictioninvoiceid,
1473 'forcevalidation' => $forcevalidation,
1474 );
1475 $reshook = $hookmanager->executeHooks('beforeCreationOfRecurringInvoices', $parameters, $sql); // note that $sql might be modified by hooks
1476
1477 $resql = $this->db->query($sql);
1478 if ($resql) {
1479 $i = 0;
1480 $num = $this->db->num_rows($resql);
1481
1482 if ($num) {
1483 $this->output .= $langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n";
1484 } else {
1485 $this->output .= $langs->trans("NoQualifiedRecurringInvoiceTemplateFound");
1486 }
1487
1488 $saventity = $conf->entity;
1489
1490 while ($i < $num) { // Loop on each template invoice. If $num = 0, test is false at first pass.
1491 $line = $this->db->fetch_object($resql);
1492
1493 $this->db->begin();
1494
1495 $errorforinvoice = 0;
1496 $invoiceidgenerated = 0;
1497 $mailHasSent = false;
1498 // Create a loopError that is reset at each loop, this counter is added to the global counter at the end of loop
1499 $loopError = 0;
1500
1501 $facture = null;
1502 $facturerec = new FactureRec($this->db);
1503 $facturerec->fetch($line->rowid);
1504
1505 if ($facturerec->id > 0) {
1506 // Set entity context
1507 $conf->entity = $facturerec->entity;
1508
1509 dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity);
1510
1511 $facture = new Facture($this->db);
1512 $facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice
1513 $facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice
1514
1515 $facture->type = self::TYPE_STANDARD;
1516 $facture->subtype = $facturerec->subtype;
1517 $facture->statut = self::STATUS_DRAFT; // deprecated
1518 $facture->status = self::STATUS_DRAFT;
1519 $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.
1520 $facture->socid = $facturerec->socid;
1521
1522 if (!empty($facturerec->fk_multicurrency)) {
1523 $facture->fk_multicurrency = $facturerec->fk_multicurrency;
1524 $facture->multicurrency_code = $facturerec->multicurrency_code;
1525 $facture->multicurrency_tx = $facturerec->multicurrency_tx;
1526 }
1527
1528 if (isset($facture->array_options) && isset($facturerec->array_options)) {
1529 foreach ($facturerec->array_options as $key => $value) {
1530 if (isset($facture->array_options[$key])) {
1531 $facture->array_options[$key] = $value;
1532 }
1533 }
1534 }
1535
1536 $parameters['facture'] = &$facture;
1537 $reshook = $hookmanager->executeHooks('beforeCreationOfEachRecurringInvoice', $parameters, $facturerec, $action); // note that $facturerec or $facture might be modified by hooks
1538
1539 // Create invoice. This may update prices according to multiplrice rules
1540 $invoiceidgenerated = $facture->create($user, 0, 0, (isModEnabled('multicurrency') ? $facturerec->usenewcurrencyrate : 0));
1541 if ($invoiceidgenerated <= 0) {
1542 $this->setErrorsFromObject($facture);
1543 $error++;
1544 $errorforinvoice++;
1545 }
1546
1547
1548 if (!$errorforinvoice && ($facturerec->auto_validate || $forcevalidation)) {
1549 $result = $facture->validate($user);
1550 if ($result <= 0) {
1551 $this->setErrorsFromObject($facture);
1552 $error++;
1553 $errorforinvoice++;
1554 }
1555 }
1556 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)
1557 // We reload the object in order to have all necessary data (like date_lim_reglement)
1558 $facture->fetch($facture->id);
1559 $facture->fetch_thirdparty();
1560
1561 $outputlangs = $langs;
1562 if (getDolGlobalInt('MAIN_MULTILANGS')) {
1563 if (!empty($facture->thirdparty->default_lang)) {
1564 $outputlangs = new Translate('', $conf);
1565 $outputlangs->setDefaultLang($facture->thirdparty->default_lang);
1566 $outputlangs->loadLangs(array('main', 'bills'));
1567 }
1568 }
1569
1570 $result = 1;
1571 if ($facturerec->generate_pdf || $forcebuilddoc) {
1572 $result = $facture->generateDocument($facturerec->model_pdf, $outputlangs);
1573 if ($result <= 0) {
1574 $this->setErrorsFromObject($facture);
1575 $error++;
1576 $errorforinvoice++;
1577 }
1578 }
1579
1580 // Auto sending of the invoice
1581 if ($result > 0 && $facture->status == Facture::STATUS_VALIDATED && $facturerec->auto_validate == 2) {
1582 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
1583 require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
1584 $formmail = new FormMail($this->db);
1585
1586 // Select email template according to language of recipient
1587 $template = $facturerec->fk_email_template;
1588 $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template), (($template != 0) ? -1 : 1));
1589 if (is_numeric($arraymessage) && $arraymessage <= 0) {
1590 $langs->load("errors");
1591 $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template ?? '');
1592 return 0;
1593 }
1594
1595 // PREPARE EMAIL
1596 $errormesg = '';
1597
1598 // Make substitution in email content
1599 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $facture);
1600
1601 complete_substitutions_array($substitutionarray, $outputlangs, $facture);
1602
1603 // Topic
1604 $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
1605
1606 // Content
1607 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
1608
1609 $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
1610
1611 // Recipient
1612 $to = array();
1613 $res = $facture->fetch_thirdparty();
1614 $recipient = $facture->thirdparty;
1615 if ($res > 0) {
1616 $tmparraycontact = $facture->liste_contact(-1, 'external', 0, 'BILLING');
1617 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
1618 foreach ($tmparraycontact as $data_email) {
1619 if (!empty($data_email['email'])) {
1620 $to[] = $facture->thirdparty->contact_get_property($data_email['id'], 'email');
1621 }
1622 }
1623 }
1624 if (empty($to) && !empty($recipient->email)) {
1625 $to[] = $recipient->email;
1626 }
1627 if (empty($to)) {
1628 $errormesg = "Failed to send invoice to thirdparty id=".$facture->socid.". No email defined for invoice or customer.";
1629 $loopError++;
1630 }
1631 } else {
1632 $errormesg = "Failed to load recipient with thirdparty id=".$facture->socid;
1633 $loopError++;
1634 }
1635
1636 // Sender
1637 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
1638 if (!empty($arraymessage->email_from)) { // If a sender is defined into template, we use it in priority
1639 $from = (string) $arraymessage->email_from;
1640 }
1641 if (empty($from)) {
1642 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
1643 $loopError++;
1644 }
1645
1646 if (!$loopError && !empty($to)) {
1647 $to = implode(',', $to);
1648 if (!empty($arraymessage->email_to)) { // If a recipient is defined into template, we add it
1649 $to = $to . ',' . $arraymessage->email_to;
1650 }
1651
1652 // Errors Recipient
1653 $errors_to = getDolGlobalString('MAIN_MAIL_ERRORS_TO');
1654
1655 $trackid = 'inv'.$facture->id;
1656 $sendcontext = 'standard';
1657
1658 // CC
1659 $email_tocc = '';
1660 if (!empty($arraymessage->email_tocc)) { // If a CC is defined into template, we use it
1661 $email_tocc = (string) $arraymessage->email_tocc;
1662 }
1663
1664 // BCC
1665 $email_tobcc = '';
1666 if (!empty($arraymessage->email_tobcc)) { // If a BCC is defined into template, we use it
1667 $email_tobcc = (string) $arraymessage->email_tobcc;
1668 }
1669
1670 //join file is asked
1671 $joinFile = [];
1672 $joinFileName = [];
1673 $joinFileMime = [];
1674 if ($arraymessage->joinfiles == 1 && !empty($facture->last_main_doc)) {
1675 $joinFile[] = DOL_DATA_ROOT.'/'.$facture->last_main_doc;
1676 $joinFileName[] = basename($facture->last_main_doc);
1677 $joinFileMime[] = dol_mimetype(DOL_DATA_ROOT.'/'.$facture->last_main_doc);
1678 }
1679
1680 // Mail Creation
1681 $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to, '', $trackid, '', $sendcontext, '');
1682
1683 $resultsendmail = $cMailFile->sendfile();
1684
1685 $this->db->begin();
1686
1687 // Sending Mail
1688 if ($resultsendmail) {
1689 $mailHasSent = true;
1690
1691 // Add a line into event table
1692 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1693
1694 // Insert record of emails sent
1695 $actioncomm = new ActionComm($this->db);
1696
1697 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
1698 $actioncomm->socid = $facture->thirdparty->id; // To link to a company
1699 $actioncomm->contact_id = 0;
1700
1701 $actioncomm->code = 'AC_EMAIL';
1702 $actioncomm->label = $langs->trans('MailSentByTo', $from, $to);
1703 $actioncomm->note_private = $sendContent;
1704 $actioncomm->fk_project = $facture->fk_project;
1705 $actioncomm->datep = dol_now();
1706 $actioncomm->datef = $actioncomm->datep;
1707 $actioncomm->percentage = -1; // Not applicable
1708 $actioncomm->authorid = $user->id; // User saving action
1709 $actioncomm->userownerid = $user->id; // Owner of action
1710 // Fields when action is an email (content should be added into note)
1711 $actioncomm->email_msgid = $cMailFile->msgid;
1712 $actioncomm->email_subject = $sendTopic;
1713 $actioncomm->email_from = $from;
1714 $actioncomm->email_sender = '';
1715 $actioncomm->email_to = $to;
1716 //$actioncomm->email_tocc = $sendtocc;
1717 //$actioncomm->email_tobcc = $sendtobcc;
1718 //$actioncomm->email_subject = $subject;
1719 $actioncomm->errors_to = $errors_to;
1720
1721 $actioncomm->elementtype = 'invoice';
1722 $actioncomm->elementid = $facture->id;
1723
1724 //$actioncomm->extraparams = $extraparams;
1725
1726 $actioncomm->create($user);
1727 } else {
1728 $errormesg = $cMailFile->error.' : '.$to;
1729 $loopError++;
1730
1731 // Add a line into event table
1732 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1733
1734 // Insert record of emails sent
1735 $actioncomm = new ActionComm($this->db);
1736
1737 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
1738 $actioncomm->socid = $facture->thirdparty->id; // To link to a company
1739 $actioncomm->contact_id = 0;
1740
1741 $actioncomm->code = 'AC_EMAIL';
1742 $actioncomm->label = $langs->trans('sendAutoEmailInvoiceKO', $from, $to);
1743 $actioncomm->note_private = $errormesg;
1744 $actioncomm->fk_project = $facture->fk_project;
1745 $actioncomm->datep = dol_now();
1746 $actioncomm->datef = $actioncomm->datep;
1747 $actioncomm->percentage = -1; // Not applicable
1748 $actioncomm->authorid = $user->id; // User saving action
1749 $actioncomm->userownerid = $user->id; // Owner of action
1750 // Fields when action is an email (content should be added into note)
1751 $actioncomm->email_msgid = $cMailFile->msgid;
1752 $actioncomm->email_subject = $sendTopic;
1753 $actioncomm->email_from = $from;
1754 $actioncomm->email_sender = '';
1755 $actioncomm->email_to = $to;
1756 //$actioncomm->email_tocc = $sendtocc;
1757 //$actioncomm->email_tobcc = $sendtobcc;
1758 //$actioncomm->email_subject = $subject;
1759 $actioncomm->errors_to = $errors_to;
1760
1761 $actioncomm->elementtype = 'invoice';
1762 $actioncomm->elementid = $facture->id;
1763
1764 //$actioncomm->extraparams = $extraparams;
1765
1766 $actioncomm->create($user);
1767 }
1768
1769 $this->db->commit(); // We always commit
1770 }
1771 }
1772 }
1773 } else {
1774 $error++;
1775 $this->error = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity."\n";
1776 $this->errors[] = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity;
1777 dol_syslog("createRecurringInvoices Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity);
1778 }
1779
1780 // Commit or rollback
1781 if (!$error && $invoiceidgenerated >= 0) {
1782 $this->db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
1783 dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation");
1784 $nb_create++;
1785 $this->output .= $langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n";
1786
1787 // Mail error
1788 if ($loopError > 0) {
1789 $this->output .= $langs->trans("InvoiceSentFromTemplateError", $facture->ref, $facturerec->ref, $errormesg ?? '')."\n";
1790 }
1791
1792 // Mail sent
1793 if ($mailHasSent) {
1794 $this->output .= $langs->trans("InvoiceSentFromTemplate", $facture->ref, $facturerec->ref)."\n";
1795 }
1796 } else {
1797 $this->output .= $langs->trans("InvoiceGeneratedFromTemplateError", $facture->ref, $facturerec->ref, $this->error)."\n";
1798 $this->db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
1799 }
1800
1801 $parameters = array(
1802 'cpt' => $i,
1803 'total' => $num,
1804 'errorCount' => $error,
1805 'errorForInvoice' => $errorforinvoice,
1806 'invoiceidgenerated' => $invoiceidgenerated,
1807 'facturerec' => $facturerec, // it's an object which PHP passes by "reference", so modifiable by hooks.
1808 'this' => $this, // it's an object which PHP passes by "reference", so modifiable by hooks.
1809 );
1810 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
1811 $reshook = $hookmanager->executeHooks('afterCreationOfRecurringInvoice', $parameters, $facture); // note: $facture can be modified by hooks (warning: $facture can be null)
1812
1813 $i++;
1814 }
1815
1816 $conf->entity = $saventity; // Restore entity context
1817 } else {
1818 dol_print_error($this->db);
1819 }
1820
1821 $this->output = trim($this->output);
1822
1823 return $error ? $error : 0;
1824 }
1825
1838 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
1839 {
1840 global $langs, $hookmanager;
1841
1842 $result = '';
1843
1844 $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("RepeatableInvoice").'</u>';
1845 if (!empty($this->ref)) {
1846 $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1847 }
1848 if ($this->frequency > 0) {
1849 $label .= '<br><b>'.$langs->trans('Frequency').':</b> '.$langs->trans('FrequencyPer_'.$this->unit_frequency, $this->frequency);
1850 }
1851 if (!empty($this->date_last_gen)) {
1852 $label .= '<br><b>'.$langs->trans('DateLastGeneration').':</b> '.dol_print_date($this->date_last_gen, 'dayhour');
1853 }
1854 if ($this->frequency > 0) {
1855 if (!empty($this->date_when)) {
1856 $label .= '<br><b>'.$langs->trans('NextDateToExecution').':</b> ';
1857 $label .= (empty($this->suspended) ? '' : '<strike>').dol_print_date($this->date_when, 'day').(empty($this->suspended) ? '' : '</strike>'); // No hour for this property
1858 if (!empty($this->suspended)) {
1859 $label .= ' ('.$langs->trans("Disabled").')';
1860 }
1861 }
1862 }
1863
1864 $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?id='.$this->id;
1865
1866 if ($short) {
1867 return $url;
1868 }
1869
1870 if ($option != 'nolink') {
1871 // Add param to save lastsearch_values or not
1872 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1873 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1874 $add_save_lastsearch_values = 1;
1875 }
1876 if ($add_save_lastsearch_values) {
1877 $url .= '&save_lastsearch_values=1';
1878 }
1879 }
1880
1881 $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1882 $linkend = '</a>';
1883
1884 $result .= $linkstart;
1885 if ($withpicto) {
1886 $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);
1887 }
1888 if ($withpicto != 2) {
1889 $result .= dol_trunc($this->ref, $max);
1890 }
1891 $result .= $linkend;
1892 global $action;
1893 $hookmanager->initHooks(array($this->element . 'dao'));
1894 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1895 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1896 if ($reshook > 0) {
1897 $result = $hookmanager->resPrint;
1898 } else {
1899 $result .= $hookmanager->resPrint;
1900 }
1901 return $result;
1902 }
1903
1911 public function getLibStatut($mode = 0, $alreadypaid = -1)
1912 {
1913 return $this->LibStatut($this->frequency ? 1 : 0, $this->suspended, $mode, $alreadypaid, empty($this->type) ? 0 : $this->type);
1914 }
1915
1916 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1928 public function LibStatut($recur, $status, $mode = 0, $alreadypaid = -1, $type = 0, $nbofopendirectdebitorcredittransfer = 0)
1929 {
1930 // phpcs:enable
1931 global $langs;
1932 $langs->load('bills');
1933
1934 $labelStatus = $langs->transnoentitiesnoconv('Active');
1935 $statusType = 'status0';
1936
1937 //print "$recur,$status,$mode,$alreadypaid,$type";
1938 if ($mode == 0) {
1939 if ($recur) {
1940 if ($status == self::STATUS_SUSPENDED) {
1941 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1942 } else {
1943 $labelStatus = $langs->transnoentitiesnoconv('Active');
1944 }
1945 } else {
1946 if ($status == self::STATUS_SUSPENDED) {
1947 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1948 } else {
1949 $labelStatus = $langs->transnoentitiesnoconv("Draft");
1950 }
1951 }
1952 } elseif ($mode == 1) {
1953 $prefix = 'Short';
1954 if ($recur) {
1955 if ($status == self::STATUS_SUSPENDED) {
1956 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1957 } else {
1958 $labelStatus = $langs->transnoentitiesnoconv('Active');
1959 }
1960 } else {
1961 if ($status == self::STATUS_SUSPENDED) {
1962 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
1963 } else {
1964 $labelStatus = $langs->transnoentitiesnoconv("Draft");
1965 }
1966 }
1967 } elseif ($mode == 2) {
1968 if ($recur) {
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 == 3) {
1986 if ($recur) {
1987 $prefix = 'Short';
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 == 4) {
2005 $prefix = '';
2006 if ($recur) {
2007 if ($status == self::STATUS_SUSPENDED) {
2008 $statusType = 'status6';
2009 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
2010 } else {
2011 $statusType = 'status4';
2012 $labelStatus = $langs->transnoentitiesnoconv('Active');
2013 }
2014 } else {
2015 if ($status == self::STATUS_SUSPENDED) {
2016 $statusType = 'status6';
2017 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
2018 } else {
2019 $statusType = 'status0';
2020 $labelStatus = $langs->transnoentitiesnoconv('Draft');
2021 }
2022 }
2023 } elseif ($mode == 5 || $mode == 6) {
2024 $prefix = '';
2025 if ($mode == 5) {
2026 $prefix = 'Short';
2027 }
2028 if ($recur) {
2029 if ($status == self::STATUS_SUSPENDED) {
2030 $statusType = 'status6';
2031 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
2032 } else {
2033 $statusType = 'status4';
2034 $labelStatus = $langs->transnoentitiesnoconv('Active');
2035 }
2036 } else {
2037 if ($status == self::STATUS_SUSPENDED) {
2038 $statusType = 'status6';
2039 $labelStatus = $langs->transnoentitiesnoconv('Disabled');
2040 } else {
2041 $statusType = 'status0';
2042 $labelStatus = $langs->transnoentitiesnoconv('Draft');
2043 }
2044 }
2045 }
2046
2047 $labelStatusShort = $labelStatus;
2048
2049 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
2050 }
2051
2059 public function getNextNumRef($soc, $mode = 'next')
2060 {
2061 // Not used for recurring invoices
2062 return '';
2063 }
2064
2071 public function info($id)
2072 {
2073 $sql = 'SELECT c.rowid, datec, tms as datem,';
2074 $sql .= ' fk_user_author, fk_user_modif';
2075 $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as c';
2076 $sql .= ' WHERE c.rowid = '.((int) $id);
2077
2078 $result = $this->db->query($sql);
2079 if ($result) {
2080 if ($this->db->num_rows($result)) {
2081 $obj = $this->db->fetch_object($result);
2082
2083 $this->id = $obj->rowid;
2084
2085 $this->user_creation_id = $obj->fk_user_author;
2086 $this->user_modification_id = $obj->fk_user_modif;
2087 $this->date_creation = $this->db->jdate($obj->datec);
2088 $this->date_modification = $this->db->jdate($obj->datem);
2089 }
2090 $this->db->free($result);
2091 } else {
2092 dol_print_error($this->db);
2093 }
2094 }
2095
2104 public function initAsSpecimen($option = '')
2105 {
2106 global $langs;
2107
2108 $now = dol_now();
2109 $arraynow = dol_getdate($now);
2110 $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
2111
2112 // Load array of products prodids
2113 $num_prods = 0;
2114 $prodids = array();
2115
2116 $sql = "SELECT rowid";
2117 $sql .= " FROM ".MAIN_DB_PREFIX."product";
2118 $sql .= " WHERE entity IN (".getEntity('product').")";
2119 $sql .= $this->db->plimit(100);
2120
2121 $resql = $this->db->query($sql);
2122 if ($resql) {
2123 $num_prods = $this->db->num_rows($resql);
2124 $i = 0;
2125 while ($i < $num_prods) {
2126 $i++;
2127 $row = $this->db->fetch_row($resql);
2128 $prodids[$i] = $row[0];
2129 }
2130 }
2131
2132 // Initialize parameters
2133 $this->id = 0;
2134 $this->ref = 'SPECIMEN';
2135 $this->title = 'SPECIMEN';
2136 $this->specimen = 1;
2137 $this->socid = 1;
2138 $this->date = $nownotime;
2139 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
2140 $this->cond_reglement_id = 1;
2141 $this->cond_reglement_code = 'RECEP';
2142 $this->date_lim_reglement = $this->calculate_date_lim_reglement();
2143 $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
2144 $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
2145 $this->note_public = 'This is a comment (public)';
2146 $this->note_private = 'This is a comment (private)';
2147 $this->fk_incoterms = 0;
2148 $this->location_incoterms = '';
2149
2150 if (empty($option) || $option != 'nolines') {
2151 // Lines
2152 $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)
2153 $xnbp = 0;
2154 while ($xnbp < $nbp) {
2155 $line = new FactureLigne($this->db);
2156 $line->desc = $langs->trans("Description")." ".$xnbp;
2157 $line->qty = 1;
2158 $line->subprice = 100;
2159 $line->tva_tx = 19.6;
2160 $line->localtax1_tx = 0;
2161 $line->localtax2_tx = 0;
2162 $line->remise_percent = 0;
2163 if ($xnbp == 1) { // Qty is negative (product line)
2164 $prodid = mt_rand(1, $num_prods);
2165 $line->fk_product = $prodids[$prodid];
2166 $line->qty = -1;
2167 $line->total_ht = -100;
2168 $line->total_ttc = -119.6;
2169 $line->total_tva = -19.6;
2170 } elseif ($xnbp == 2) { // UP is negative (free line)
2171 $line->subprice = -100;
2172 $line->total_ht = -100;
2173 $line->total_ttc = -119.6;
2174 $line->total_tva = -19.6;
2175 $line->remise_percent = 0;
2176 } elseif ($xnbp == 3) { // Discount is 50% (product line)
2177 $prodid = mt_rand(1, $num_prods);
2178 $line->fk_product = $prodids[$prodid];
2179 $line->total_ht = 50;
2180 $line->total_ttc = 59.8;
2181 $line->total_tva = 9.8;
2182 $line->remise_percent = 50;
2183 } else { // (product line)
2184 $prodid = mt_rand(1, $num_prods);
2185 $line->fk_product = $prodids[$prodid];
2186 $line->total_ht = 100;
2187 $line->total_ttc = 119.6;
2188 $line->total_tva = 19.6;
2189 $line->remise_percent = 00;
2190 }
2191
2192 $this->lines[$xnbp] = $line;
2193 $xnbp++;
2194
2195 $this->total_ht += $line->total_ht;
2196 $this->total_tva += $line->total_tva;
2197 $this->total_ttc += $line->total_ttc;
2198 }
2199 $this->revenuestamp = 0;
2200
2201 // Add a line "offered"
2202 $line = new FactureLigne($this->db);
2203 $line->desc = $langs->trans("Description")." (offered line)";
2204 $line->qty = 1;
2205 $line->subprice = 100;
2206 $line->tva_tx = 19.6;
2207 $line->localtax1_tx = 0;
2208 $line->localtax2_tx = 0;
2209 $line->remise_percent = 100;
2210 $line->total_ht = 0;
2211 $line->total_ttc = 0; // 90 * 1.196
2212 $line->total_tva = 0;
2213 $prodid = mt_rand(1, $num_prods);
2214 $line->fk_product = $prodids[$prodid];
2215
2216 $this->lines[$xnbp] = $line;
2217 $xnbp++;
2218 }
2219
2220 $this->usenewprice = 0;
2221
2222 return 1;
2223 }
2224
2233 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2234 {
2235 $tables = array(
2236 'facture_rec'
2237 );
2238
2239 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2240 }
2241
2250 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
2251 {
2252 $tables = array(
2253 'facturedet_rec'
2254 );
2255
2256 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
2257 }
2258
2267 public function setFrequencyAndUnit($frequency, $unit, $notrigger = 0)
2268 {
2269 global $user;
2270
2271 if (!$this->table_element) {
2272 dol_syslog(get_class($this)."::setFrequencyAndUnit was called on object with property table_element not defined", LOG_ERR);
2273 return -1;
2274 }
2275
2276 if (!empty($frequency) && empty($unit)) {
2277 dol_syslog(get_class($this)."::setFrequencyAndUnit was called on object with params frequency defined but unit not defined", LOG_ERR);
2278 return -2;
2279 }
2280
2281 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2282 $sql .= ' SET frequency = '.($frequency ? $this->db->escape((string) $frequency) : 'null');
2283 if (!empty($unit)) {
2284 $sql .= ', unit_frequency = \''.$this->db->escape($unit).'\'';
2285 }
2286 $sql .= " WHERE rowid = ".((int) $this->id);
2287
2288 dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG);
2289 if ($this->db->query($sql)) {
2290 $this->frequency = $frequency;
2291 if (!empty($unit)) {
2292 $this->unit_frequency = $unit;
2293 }
2294
2295 if (!$notrigger) {
2296 // Call trigger
2297 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2298 if ($result < 0) {
2299 return $result;
2300 }
2301 // End call triggers
2302 }
2303
2304 return 1;
2305 } else {
2306 dol_print_error($this->db);
2307 return -1;
2308 }
2309 }
2310
2319 public function setNextDate($date, $increment_nb_gen_done = 0, $notrigger = 0)
2320 {
2321 global $user;
2322
2323 if (!$this->table_element) {
2324 dol_syslog(get_class($this)."::setNextDate was called on object with property table_element not defined", LOG_ERR);
2325 return -1;
2326 }
2327 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2328 $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null");
2329 if ($increment_nb_gen_done > 0) {
2330 $sql .= ', nb_gen_done = nb_gen_done + 1';
2331 }
2332 $sql .= " WHERE rowid = ".((int) $this->id);
2333
2334 dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG);
2335 if ($this->db->query($sql)) {
2336 $this->date_when = $date;
2337 if ($increment_nb_gen_done > 0) {
2338 $this->nb_gen_done++;
2339
2340 if (getDolGlobalInt('MAIN_SUSPEND_FACTURE_REC_ON_MAX_GEN_REACHED') && $this->isMaxNbGenReached()) {
2341 $resSuspend = $this->setValueFrom('suspended', 1);
2342
2343 if ($resSuspend <= 0) {
2344 dol_syslog(__METHOD__ . '::setValueFrom Error : ' . $this->error, LOG_ERR);
2345 return -1;
2346 }
2347 }
2348 }
2349
2350 if (!$notrigger) {
2351 if (empty($this->context['actionmsgmore'])) {
2352 $this->context['actionmsgmore'] = 'Trigger called by setNextDate';
2353 }
2354
2355 // Call trigger
2356 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2357 if ($result < 0) {
2358 return $result;
2359 }
2360 // End call triggers
2361 }
2362 return 1;
2363 } else {
2364 dol_print_error($this->db);
2365 return -1;
2366 }
2367 }
2368
2376 public function setMaxPeriod($nb, $notrigger = 0)
2377 {
2378 global $user;
2379
2380 if (!$this->table_element) {
2381 dol_syslog(get_class($this)."::setMaxPeriod was called on object with property table_element not defined", LOG_ERR);
2382 return -1;
2383 }
2384
2385 if (empty($nb)) {
2386 $nb = 0;
2387 }
2388
2389 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2390 $sql .= ' SET nb_gen_max = '.((int) $nb);
2391 $sql .= " WHERE rowid = ".((int) $this->id);
2392
2393 dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG);
2394 if ($this->db->query($sql)) {
2395 $this->nb_gen_max = $nb;
2396
2397 if (!$notrigger) {
2398 // Call trigger
2399 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2400 if ($result < 0) {
2401 return $result;
2402 }
2403 // End call triggers
2404 }
2405
2406 return 1;
2407 } else {
2408 dol_print_error($this->db);
2409 return -1;
2410 }
2411 }
2412
2420 public function setAutoValidate($validate, $notrigger = 0)
2421 {
2422 global $user;
2423
2424 if (!$this->table_element) {
2425 dol_syslog(get_class($this)."::setAutoValidate was called on object with property table_element not defined", LOG_ERR);
2426 return -1;
2427 }
2428
2429 $this->auto_validate = $validate;
2430
2431 $result = $this->update($user);
2432
2433 dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG);
2434 if ($result > 0) {
2435 return 1;
2436 } else {
2437 dol_print_error($this->db);
2438 return -1;
2439 }
2440 }
2441
2449 public function setGeneratePdf($validate, $notrigger = 0)
2450 {
2451 global $user;
2452
2453 if (!$this->table_element) {
2454 dol_syslog(get_class($this)."::setGeneratePdf was called on object with property table_element not defined", LOG_ERR);
2455 return -1;
2456 }
2457
2458 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2459 $sql .= ' SET generate_pdf = '.((int) $validate);
2460 $sql .= " WHERE rowid = ".((int) $this->id);
2461
2462 dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG);
2463 if ($this->db->query($sql)) {
2464 $this->generate_pdf = $validate;
2465
2466 if (!$notrigger) {
2467 // Call trigger
2468 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2469 if ($result < 0) {
2470 return $result;
2471 }
2472 // End call triggers
2473 }
2474
2475 return 1;
2476 } else {
2477 dol_print_error($this->db);
2478 return -1;
2479 }
2480 }
2481
2489 public function setModelPdf($model, $notrigger = 0)
2490 {
2491 global $user;
2492 if (!$this->table_element) {
2493 dol_syslog(get_class($this)."::setModelPdf was called on object with property table_element not defined", LOG_ERR);
2494 return -1;
2495 }
2496
2497 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2498 $sql .= " SET modelpdf = '".$this->db->escape($model)."'";
2499 $sql .= " WHERE rowid = ".((int) $this->id);
2500
2501 dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG);
2502 if ($this->db->query($sql)) {
2503 $this->model_pdf = $model;
2504
2505 if (!$notrigger) {
2506 // Call trigger
2507 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2508 if ($result < 0) {
2509 return $result;
2510 }
2511 // End call triggers
2512 }
2513
2514 return 1;
2515 } else {
2516 dol_print_error($this->db);
2517 return -1;
2518 }
2519 }
2520
2528 public function setMailTemplate($idEmailTemplate, $notrigger = 0): int
2529 {
2530 global $user;
2531 if (!$this->table_element) {
2532 dol_syslog(get_class($this)."::setMailTemplate was called on object with property table_element not defined", LOG_ERR);
2533 return -1;
2534 }
2535
2536 $this->fk_email_template = $idEmailTemplate;
2537 $result = $this->update($user);
2538
2539 dol_syslog(get_class($this)."::setMailTemplate", LOG_DEBUG);
2540 if ($result > 0) {
2541 if (!$notrigger) {
2542 // Call trigger
2543 $result = $this->call_trigger('BILLREC_MODIFY', $user);
2544 if ($result < 0) {
2545 return $result;
2546 }
2547 // End call triggers
2548 }
2549
2550 return 1;
2551 } else {
2552 dol_print_error($this->db);
2553 return -1;
2554 }
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
2632
2640 public function delete(User $user, $notrigger = 0)
2641 {
2642 $error = 0;
2643
2644 $this->db->begin();
2645
2646 if (!$error) {
2647 if (!$notrigger) {
2648 // Call triggers
2649 $result = $this->call_trigger('LINEBILLREC_DELETE', $user);
2650 if ($result < 0) {
2651 $error++;
2652 } // Do also here what you must do to rollback action if trigger fail
2653 // End call triggers
2654 }
2655 }
2656
2657 if (!$error) {
2658 $result = $this->deleteExtraFields();
2659 if ($result < 0) {
2660 $error++;
2661 }
2662 }
2663
2664 if (!$error) {
2665 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
2666
2667 $res = $this->db->query($sql);
2668 if (!$res) {
2669 $error++;
2670 $this->errors[] = $this->db->lasterror();
2671 }
2672 }
2673
2674 // Commit or rollback
2675 if ($error) {
2676 $this->db->rollback();
2677 return -1;
2678 } else {
2679 $this->db->commit();
2680 return 1;
2681 }
2682 }
2683
2684
2691 public function fetch($rowid)
2692 {
2693 $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,';
2694 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
2695 $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,';
2696 $sql .= ' l.rang, l.special_code,';
2697 $sql .= ' l.fk_unit, l.fk_contract_line,';
2698 $sql .= ' l.import_key, l.fk_multicurrency,';
2699 $sql .= ' l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2700 $sql .= ' l.buy_price_ht, l.fk_product_fournisseur_price,';
2701 $sql .= ' l.fk_user_author, l.fk_user_modif, l.extraparams,';
2702 $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2703 $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
2704 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
2705 $sql .= ' WHERE l.rowid = '.((int) $rowid);
2706 $sql .= ' ORDER BY l.rang';
2707
2708 dol_syslog('FactureRec::fetch', LOG_DEBUG);
2709 $result = $this->db->query($sql);
2710 if ($result) {
2711 $objp = $this->db->fetch_object($result);
2712
2713 $this->id = $objp->rowid;
2714 $this->fk_facture = $objp->fk_facture;
2715 $this->fk_parent_line = $objp->fk_parent_line;
2716 $this->label = $objp->custom_label; // Label line
2717 $this->desc = $objp->description; // Description line
2718 $this->description = $objp->description; // Description line
2719 $this->product_type = $objp->product_type; // Type of line
2720 $this->ref = $objp->product_ref; // Ref product
2721 $this->product_ref = $objp->product_ref; // Ref product
2722 $this->libelle = $objp->product_label; // deprecated
2723 $this->product_label = $objp->product_label; // Label product
2724 $this->product_desc = $objp->product_desc; // Description product
2725 $this->fk_product_type = $objp->fk_product_type; // Type of product
2726 $this->qty = $objp->qty;
2727 $this->price = $objp->price;
2728 $this->subprice = $objp->subprice;
2729 $this->vat_src_code = $objp->vat_src_code;
2730 $this->tva_tx = $objp->tva_tx;
2731 $this->localtax1_tx = $objp->localtax1_tx;
2732 $this->localtax2_tx = $objp->localtax2_tx;
2733 $this->localtax1_type = $objp->localtax1_type;
2734 $this->localtax2_type = $objp->localtax2_type;
2735 $this->remise_percent = $objp->remise_percent;
2736 //$this->fk_remise_except = $objp->fk_remise_except;
2737 $this->fk_product = $objp->fk_product;
2738 $this->date_start_fill = $objp->date_start_fill;
2739 $this->date_end_fill = $objp->date_end_fill;
2740 $this->info_bits = $objp->info_bits;
2741 $this->total_ht = $objp->total_ht;
2742 $this->total_tva = $objp->total_tva;
2743 $this->total_ttc = $objp->total_ttc;
2744
2745 $this->rang = $objp->rang;
2746 $this->special_code = $objp->special_code;
2747 $this->fk_unit = $objp->fk_unit;
2748 $this->fk_contract_line = $objp->fk_contract_line;
2749 $this->import_key = $objp->import_key;
2750 $this->fk_multicurrency = $objp->fk_multicurrency;
2751 $this->multicurrency_code = $objp->multicurrency_code;
2752 $this->multicurrency_subprice = $objp->multicurrency_subprice;
2753 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
2754 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
2755 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2756
2757 $this->buy_price_ht = $objp->buy_price_ht;
2758
2759 $this->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
2760 $this->fk_user_author = $objp->fk_user_author;
2761 $this->fk_user_modif = $objp->fk_user_modif;
2762
2763 $this->db->free($result);
2764 return 1;
2765 } else {
2766 $this->error = $this->db->lasterror();
2767 return -3;
2768 }
2769 }
2770
2771
2779 public function update(User $user, $notrigger = 0)
2780 {
2781 global $conf;
2782
2783 $error = 0;
2784
2785 // Clean parameters
2786 if (empty($this->fk_parent_line)) {
2787 $this->fk_parent_line = 0;
2788 }
2789
2790 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2791
2792 $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET";
2793 $sql .= " fk_facture = ".((int) $this->fk_facture);
2794 $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
2795 $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
2796 $sql .= ", description='".$this->db->escape($this->desc)."'";
2797 $sql .= ", price=".price2num($this->price);
2798 $sql .= ", qty=".price2num($this->qty);
2799 $sql .= ", tva_tx=".price2num($this->tva_tx);
2800 $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'";
2801 $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
2802 $sql .= ", localtax1_type='".$this->db->escape((string) $this->localtax1_type)."'";
2803 $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
2804 $sql .= ", localtax2_type='".$this->db->escape((string) $this->localtax2_type)."'";
2805 $sql .= ", fk_product=".($this->fk_product > 0 ? $this->fk_product : "null");
2806 $sql .= ", product_type=".((int) $this->product_type);
2807 $sql .= ", remise_percent=".price2num($this->remise_percent);
2808 $sql .= ", subprice=".price2num($this->subprice);
2809 $sql .= ", info_bits=".price2num($this->info_bits);
2810 $sql .= ", date_start_fill=".(int) $this->date_start_fill;
2811 $sql .= ", date_end_fill=".(int) $this->date_end_fill;
2812 if (empty($this->skip_update_total)) {
2813 $sql .= ", total_ht=".price2num($this->total_ht);
2814 $sql .= ", total_tva=".price2num($this->total_tva);
2815 $sql .= ", total_localtax1=".price2num($this->total_localtax1);
2816 $sql .= ", total_localtax2=".price2num($this->total_localtax2);
2817 $sql .= ", total_ttc=".price2num($this->total_ttc);
2818 }
2819 $sql .= ", rang=".((int) $this->rang);
2820 $sql .= ", special_code=".((int) $this->special_code);
2821 $sql .= ", fk_unit=".($this->fk_unit ? "'".$this->db->escape((string) $this->fk_unit)."'" : "null");
2822 $sql .= ", fk_contract_line=".($this->fk_contract_line ? $this->fk_contract_line : "null");
2823 $sql .= " WHERE rowid = ".((int) $this->id);
2824
2825 $this->db->begin();
2826
2827 dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
2828
2829 $resql = $this->db->query($sql);
2830 if ($resql) {
2831 if (!$error) {
2832 $result = $this->insertExtraFields();
2833 if ($result < 0) {
2834 $error++;
2835 }
2836 }
2837
2838 if (!$error && !$notrigger) {
2839 // Call trigger
2840 $result = $this->call_trigger('LINEBILLREC_MODIFY', $user);
2841 if ($result < 0) {
2842 $error++;
2843 }
2844 // End call triggers
2845 }
2846
2847 if ($error) {
2848 $this->db->rollback();
2849 return -2;
2850 } else {
2851 $this->db->commit();
2852 return 1;
2853 }
2854 } else {
2855 $this->error = $this->db->lasterror();
2856 $this->db->rollback();
2857 return -2;
2858 }
2859 }
2860}
$object ref
Definition info.php:90
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
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.
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)
Add a line to invoice.
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)
__construct(DoliDB $db)
Constructor.
setNextDate($date, $increment_nb_gen_done=0, $notrigger=0)
Update the next date of execution.
setAutoValidate($validate, $notrigger=0)
Update the auto validate flag of invoice.
initAsSpecimen($option='')
Initialise an instance with random values.
setMaxPeriod($nb, $notrigger=0)
Update the maximum period.
update(User $user, $notrigger=0)
Update a line invoice_rec.
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.
global $mysoc
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:126
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
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...
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
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, $remise_percent_global, $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:487
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:130