dolibarr 23.0.4
commande.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
6 * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2011 Jean Heimburger <jean@tiaris.info>
8 * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
9 * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
12 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
13 * Copyright (C) 2016-2022 Ferran Marcet <fmarcet@2byte.es>
14 * Copyright (C) 2021-2025 Frédéric France <frederic.france@free.fr>
15 * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
16 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
17 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
18 * Copyright (C) 2026 Nick Fragoulis
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
40require_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
41require_once DOL_DOCUMENT_ROOT.'/commande/class/orderline.class.php';
42require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
43require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
44require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
45require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
46require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
47
48
52class Commande extends CommonOrder
53{
54 use CommonSubtotal;
55
59 public $element = 'commande';
60
65 public $TRIGGER_PREFIX = 'ORDER';
66
70 public $table_element = 'commande';
71
75 public $table_element_line = 'commandedet';
76
80 public $class_element_line = 'OrderLine';
81
85 public $fk_element = 'fk_commande';
86
90 public $picto = 'order';
91
96 public $restrictiononfksoc = 1;
97
101 protected $table_ref_field = 'ref';
102
106 public $socid;
107
111 public $ref_client;
112
116 public $ref_customer;
117
121 public $contactid;
122
128 public $statut;
129
134 public $status;
135
139 public $billed;
140
144 public $date_lim_reglement;
148 public $cond_reglement_code;
149
153 public $cond_reglement_doc;
154
158 public $cond_reglement_label;
159
164 public $deposit_percent;
165
169 public $fk_account;
170
174 public $mode_reglement;
175
179 public $mode_reglement_id;
180
184 public $mode_reglement_code;
185
190 public $availability_id;
191
196 public $availability_code;
197
202 public $availability;
203
207 public $demand_reason_id;
208
212 public $demand_reason_code;
213
217 public $date;
218
224 public $date_commande;
225
229 public $delivery_date;
230
234 public $fk_remise_except;
235
240 public $remise_percent;
241
245 public $source;
246
251 public $signed_status = 0;
252
256 public $warehouse_id;
257
261 public $extraparams = array();
262
266 public $user_author_id;
267
271 public $line;
272
276 public $lines = array();
277
278
282 public $module_source;
286 public $pos_source;
287
291 public $expeditions;
292
296 public $online_payment_url;
297
298
299
325 // BEGIN MODULEBUILDER PROPERTIES
329 public $fields = array(
330 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
331 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20, 'index' => 1),
332 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 25),
333 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 26),
334 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 28),
335 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 20),
336 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 25),
337 'date_commande' => array('type' => 'date', 'label' => 'Date', 'enabled' => 1, 'visible' => 1, 'position' => 60, 'csslist' => 'nowraponall'),
338 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 62, 'csslist' => 'nowraponall'),
339 'date_cloture' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 65, 'csslist' => 'nowraponall'),
340 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 85),
341 'fk_user_cloture' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => -1, 'position' => 90),
342 'source' => array('type' => 'smallint(6)', 'label' => 'Source', 'enabled' => 1, 'visible' => -1, 'position' => 95),
343 'total_tva' => array('type' => 'double(24,8)', 'label' => 'VAT', 'enabled' => 1, 'visible' => -1, 'position' => 125, 'isameasure' => 1),
344 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LocalTax1', 'enabled' => 1, 'visible' => -1, 'position' => 130, 'isameasure' => 1),
345 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LocalTax2', 'enabled' => 1, 'visible' => -1, 'position' => 135, 'isameasure' => 1),
346 'total_ht' => array('type' => 'double(24,8)', 'label' => 'TotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 140, 'isameasure' => 1),
347 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'TotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 145, 'isameasure' => 1),
348 'signed_status' => array('type' => 'smallint(6)', 'label' => 'SignedStatus', 'enabled' => 1, 'visible' => -1, 'position' => 146, 'arrayofkeyval' => array(0 => 'NoSignature', 1 => 'SignedSender', 2 => 'SignedReceiver', 9 => 'SignedAll')),
349 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 150),
350 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 155),
351 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'PDFTemplate', 'enabled' => 1, 'visible' => 0, 'position' => 160),
352 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 170),
353 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'MulticurrencyID', 'enabled' => 1, 'visible' => -1, 'position' => 175),
354 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'position' => 180),
355 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 181),
356 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 185),
357 'date_livraison' => array('type' => 'date', 'label' => 'DateDeliveryPlanned', 'enabled' => 1, 'visible' => -1, 'position' => 190, 'csslist' => 'nowraponall'),
358 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMethod', 'enabled' => 1, 'visible' => -1, 'position' => 195),
359 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'DefaultWarehouse', 'enabled' => 'isModEnabled("stock")', 'visible' => -1, 'position' => 200, 'nodepth' => 1),
360 'fk_availability' => array('type' => 'integer', 'label' => 'Availability', 'enabled' => 1, 'visible' => -1, 'position' => 205),
361 'fk_input_reason' => array('type' => 'integer', 'label' => 'InputReason', 'enabled' => 1, 'visible' => -1, 'position' => 210),
362 //'fk_delivery_address' =>array('type'=>'integer', 'label'=>'DeliveryAddress', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
363 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 225),
364 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 230),
365 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 235),
366 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240),
367 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'MulticurrencyCurrency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 245),
368 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 250, 'isameasure' => 1),
369 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 255, 'isameasure' => 1),
370 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 260, 'isameasure' => 1),
371 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 265, 'isameasure' => 1),
372 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
373 'module_source' => array('type' => 'varchar(32)', 'label' => 'POSModule', 'enabled' => 1, 'visible' => -1, 'position' => 275),
374 'pos_source' => array('type' => 'varchar(32)', 'label' => 'POSTerminal', 'enabled' => 1, 'visible' => -1, 'position' => 280),
375 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 300),
376 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 302),
377 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -2, 'position' => 304, 'csslist' => 'nowraponall'),
378 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 306),
379 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 400),
380 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
381 );
382 // END MODULEBUILDER PROPERTIES
383
388
392 const STATUS_CANCELED = -1;
396 const STATUS_DRAFT = 0;
404 const STATUS_SHIPMENTONPROCESS = 2; // We set this status when a shipment is validated
405
411
415 const STATUS_CLOSED = 3;
416
417 /*
418 * No signature
419 */
420 const STATUS_NO_SIGNATURE = 0;
421
422 /*
423 * Signed by sender
424 */
425 const STATUS_SIGNED_SENDER = 1;
426
427 /*
428 * Signed by receiver
429 */
430 const STATUS_SIGNED_RECEIVER = 2;
431
432 /*
433 * Signed by all
434 */
435 const STATUS_SIGNED_ALL = 9; // To handle future kind of signature (ex: tripartite contract)
436
437
443 public function __construct($db)
444 {
445 $this->db = $db;
446
447 $this->ismultientitymanaged = 1;
448 $this->isextrafieldmanaged = 1;
449
450 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
451 }
452
460 public function getNextNumRef($soc)
461 {
462 global $langs, $conf;
463 $langs->load("order");
464
465 if (getDolGlobalString('COMMANDE_ADDON')) {
466 $mybool = false;
467
468 $file = getDolGlobalString('COMMANDE_ADDON') . ".php";
469 $classname = getDolGlobalString('COMMANDE_ADDON');
470
471 // Include file with class
472 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
473 foreach ($dirmodels as $reldir) {
474 $dir = dol_buildpath($reldir."core/modules/commande/");
475
476 // Load file with numbering class (if found)
477 $mybool = ((bool) @include_once $dir.$file) || $mybool;
478 }
479
480 if (!$mybool) {
481 dol_print_error(null, "Failed to include file ".$file);
482 return '';
483 }
484
485 $obj = new $classname();
487 '@phan-var-force ModeleNumRefCommandes $obj';
488
489 $numref = $obj->getNextValue($soc, $this);
490
491 if ($numref != "") {
492 return $numref;
493 } else {
494 $this->error = $obj->error;
495 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
496 return "";
497 }
498 } else {
499 print $langs->trans("Error")." ".$langs->trans("Error_COMMANDE_ADDON_NotDefined");
500 return "";
501 }
502 }
503
504
513 public function valid($user, $idwarehouse = 0, $notrigger = 0)
514 {
515 global $conf, $langs;
516
517 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
518
519 $error = 0;
520
521 // Protection
522 if ($this->status == self::STATUS_VALIDATED) {
523 dol_syslog(get_class($this)."::valid action abandoned: already validated", LOG_WARNING);
524 return 0;
525 }
526
527 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
528 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')))) {
529 $this->error = 'NotEnoughPermissions';
530 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
531 return -1;
532 }
533 if (empty($this->socid)) {
534 $this->error = 'ErrorWrongParameters';
535 return -1;
536 }
537 if (!getDolGlobalBool('ORDER_NOCHECK_ONSALE_PRODUCTS_ONVALID') && !$this->checkActiveProductInLines()) {
538 dol_syslog(get_class($this)."::valid checkActiveProductInLines ".$this->error, LOG_INFO);
539 return -1;
540 }
541 $now = dol_now();
542
543 $this->db->begin();
544
545 // Definition du nom de module de numerotation de commande
546 $soc = new Societe($this->db);
547 $soc->fetch($this->socid);
548
549 // Class of company linked to order
550 $result = $soc->setAsCustomer();
551
552 // Define new ref
553 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
554 $num = $this->getNextNumRef($soc);
555 } else {
556 $num = (string) $this->ref;
557 }
558 $this->newref = dol_sanitizeFileName($num);
559
560 // Validate
561 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
562 $sql .= " SET ref = '".$this->db->escape($num)."',";
563 $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
564 $sql .= " date_valid = '".$this->db->idate($now)."',";
565 $sql .= " fk_user_valid = ".($user->id > 0 ? (int) $user->id : "null").",";
566 $sql .= " fk_user_modif = ".((int) $user->id);
567 $sql .= " WHERE rowid = ".((int) $this->id);
568
569 dol_syslog(get_class($this)."::valid", LOG_DEBUG);
570 $resql = $this->db->query($sql);
571 if (!$resql) {
572 dol_print_error($this->db);
573 $this->error = $this->db->lasterror();
574 $error++;
575 }
576
577 if (!$error) {
578 // If stock is incremented on validate order, we must increment it
579 if ($result >= 0 && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
580 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
581 $langs->load("agenda");
582
583 // Loop on each line
584 $cpt = count($this->lines);
585 for ($i = 0; $i < $cpt; $i++) {
586 if ($this->lines[$i]->fk_product > 0) {
587 $mouvP = new MouvementStock($this->db);
588 $mouvP->origin = &$this;
589 $mouvP->setOrigin($this->element, $this->id);
590 // We decrement stock of product (and sub-products)
591 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr", $num));
592 if ($result < 0) {
593 $error++;
594 $this->setErrorsFromObject($mouvP);
595 }
596 }
597 if ($error) {
598 break;
599 }
600 }
601 }
602 }
603
604 if (!$error && !$notrigger) {
605 // Call trigger
606 $result = $this->call_trigger('ORDER_VALIDATE', $user);
607 if ($result < 0) {
608 $error++;
609 }
610 // End call triggers
611 }
612
613 if (!$error) {
614 $this->oldref = $this->ref;
615
616 // Rename directory if dir was a temporary ref
617 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
618 // Now we rename also files into index
619 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'commande/".$this->db->escape($this->newref)."'";
620 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
621 $resql = $this->db->query($sql);
622 if (!$resql) {
623 $error++;
624 $this->error = $this->db->lasterror();
625 }
626 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'commande/".$this->db->escape($this->newref)."'";
627 $sql .= " WHERE filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
628 $resql = $this->db->query($sql);
629 if (!$resql) {
630 $error++;
631 $this->error = $this->db->lasterror();
632 }
633
634 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
635 $oldref = dol_sanitizeFileName($this->ref);
636 $newref = dol_sanitizeFileName($num);
637 $dirsource = $conf->commande->multidir_output[$this->entity].'/'.$oldref;
638 $dirdest = $conf->commande->multidir_output[$this->entity].'/'.$newref;
639 if (!$error && file_exists($dirsource)) {
640 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
641
642 if (@rename($dirsource, $dirdest)) {
643 dol_syslog("Rename ok");
644 // Rename docs starting with $oldref with $newref
645 $listoffiles = dol_dir_list($conf->commande->multidir_output[$this->entity].'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
646 foreach ($listoffiles as $fileentry) {
647 $dirsource = $fileentry['name'];
648 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
649 $dirsource = $fileentry['path'].'/'.$dirsource;
650 $dirdest = $fileentry['path'].'/'.$dirdest;
651 @rename($dirsource, $dirdest);
652 }
653 }
654 }
655 }
656 }
657
658 // Set new ref and current status
659 if (!$error) {
660 $this->ref = $num;
661 $this->statut = self::STATUS_VALIDATED; // deprecated
663 }
664
665 if (!$error) {
666 $this->db->commit();
667 return 1;
668 } else {
669 $this->db->rollback();
670 return -1;
671 }
672 }
673
674 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
682 public function setDraft($user, $idwarehouse = -1)
683 {
684 //phpcs:enable
685 global $langs;
686
687 $error = 0;
688
689 // Protection
690 if ($this->status <= self::STATUS_DRAFT && !getDolGlobalInt('ORDER_REOPEN_TO_DRAFT')) {
691 return 0;
692 }
693
694 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
695 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')))) {
696 $this->error = 'Permission denied';
697 return -1;
698 }
699
700 dol_syslog(__METHOD__, LOG_DEBUG);
701
702 $this->db->begin();
703
704 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
705 $sql .= " SET fk_statut = ".((int) self::STATUS_DRAFT).",";
706 $sql .= " fk_user_modif = ".((int) $user->id);
707 $sql .= " WHERE rowid = ".((int) $this->id);
708
709 if ($this->db->query($sql)) {
710 $this->oldcopy = clone $this;
711
712 // If stock is decremented on validate order, we must reincrement it
713 if (isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
714 $result = 0;
715
716 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
717 $langs->load("agenda");
718
719 $num = count($this->lines);
720 for ($i = 0; $i < $num; $i++) {
721 if ($this->lines[$i]->fk_product > 0) {
722 $mouvP = new MouvementStock($this->db);
723 $mouvP->origin = &$this;
724 $mouvP->setOrigin($this->element, $this->id);
725 // We increment stock of product (and sub-products)
726 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv("OrderBackToDraftInDolibarr", $this->ref));
727 if ($result < 0) {
728 $error++;
729 $this->setErrorsFromObject($mouvP);
730 break;
731 }
732 }
733 }
734 }
735
736 if (!$error) {
737 // Call trigger
738 $result = $this->call_trigger('ORDER_UNVALIDATE', $user);
739 if ($result < 0) {
740 $error++;
741 }
742 }
743
744 if (!$error) {
745 $this->statut = self::STATUS_DRAFT; // deprecated
746 $this->status = self::STATUS_DRAFT;
747 $this->db->commit();
748 return 1;
749 } else {
750 $this->db->rollback();
751 return -1;
752 }
753 } else {
754 $this->error = $this->db->error();
755 $this->db->rollback();
756 return -1;
757 }
758 }
759
760
761 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
769 public function set_reopen($user)
770 {
771 // phpcs:enable
772 $error = 0;
773
774 if ($this->status != self::STATUS_CANCELED && $this->status != self::STATUS_CLOSED) {
775 dol_syslog(get_class($this)."::set_reopen order has not status closed", LOG_WARNING);
776 return 0;
777 }
778
779 $this->db->begin();
780
781 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
782 $sql .= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0,';
783 $sql .= " fk_user_modif = ".((int) $user->id);
784 $sql .= " WHERE rowid = ".((int) $this->id);
785
786 dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG);
787 $resql = $this->db->query($sql);
788 if ($resql) {
789 // Call trigger
790 $result = $this->call_trigger('ORDER_REOPEN', $user);
791 if ($result < 0) {
792 $error++;
793 }
794 // End call triggers
795 } else {
796 $error++;
797 $this->error = $this->db->lasterror();
798 dol_print_error($this->db);
799 }
800
801 if (!$error) {
802 $this->statut = self::STATUS_VALIDATED; // deprecated
804 $this->billed = 0;
805
806 $this->db->commit();
807 return 1;
808 } else {
809 foreach ($this->errors as $errmsg) {
810 dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR);
811 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
812 }
813 $this->db->rollback();
814 return -1 * $error;
815 }
816 }
817
826 public function cloture($user, $notrigger = 0, $checkpermission = 1)
827 {
828 $error = 0;
829
830 $usercanclose = (!$checkpermission
831 || (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
832 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'close')));
833
834 if ($usercanclose) {
835 if ($this->status == self::STATUS_CLOSED) {
836 return 0;
837 }
838 $this->db->begin();
839
840 $now = dol_now();
841
842 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
843 $sql .= ' SET fk_statut = '.self::STATUS_CLOSED.',';
844 $sql .= ' fk_user_cloture = '.((int) $user->id).',';
845 $sql .= " date_cloture = '".$this->db->idate($now)."',";
846 $sql .= " fk_user_modif = ".((int) $user->id);
847 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
848
849 if ($this->db->query($sql)) {
850 if (!$notrigger) {
851 // Call trigger
852 $result = $this->call_trigger('ORDER_CLOSE', $user);
853 if ($result < 0) {
854 $error++;
855 }
856 // End call triggers
857 }
858
859 if (!$error) {
860 $this->statut = self::STATUS_CLOSED; // deprecated
862
863 $this->db->commit();
864 return 1;
865 } else {
866 $this->db->rollback();
867 return -1;
868 }
869 } else {
870 $this->error = $this->db->lasterror();
871
872 $this->db->rollback();
873 return -1;
874 }
875 }
876 return 0;
877 }
878
890 public function setCategories($categories)
891 {
892 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
893 return parent::setCategoriesCommon($categories, Categorie::TYPE_ORDER);
894 }
895
904 public function cancel($user, $idwarehouse = -1)
905 {
906 global $user, $langs;
907
908 $error = 0;
909
910 $this->db->begin();
911
912 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
913 $sql .= " SET fk_statut = ".self::STATUS_CANCELED.",";
914 $sql .= " fk_user_modif = ".((int) $user->id);
915 $sql .= " WHERE rowid = ".((int) $this->id);
916 $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
917
918 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
919 if ($this->db->query($sql)) {
920 // If stock is decremented on validate order, we must reincrement it
921 if (isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
922 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
923 $langs->load("agenda");
924
925 $num = count($this->lines);
926 for ($i = 0; $i < $num; $i++) {
927 if ($this->lines[$i]->fk_product > 0) {
928 $mouvP = new MouvementStock($this->db);
929 $mouvP->setOrigin($this->element, $this->id);
930 // We increment stock of product (and sub-products)
931 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr", $this->ref)); // price is 0, we don't want WAP to be changed
932 if ($result < 0) {
933 $error++;
934 $this->setErrorsFromObject($mouvP);
935 break;
936 }
937 }
938 }
939 }
940
941 if (!$error) {
942 // Call trigger
943 $result = $this->call_trigger('ORDER_CANCEL', $user);
944 if ($result < 0) {
945 $error++;
946 }
947 // End call triggers
948 }
949
950 if (!$error) {
951 $this->statut = self::STATUS_CANCELED; // deprecated
953 $this->db->commit();
954 return 1;
955 } else {
956 foreach ($this->errors as $errmsg) {
957 dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
958 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
959 }
960 $this->db->rollback();
961 return -1 * $error;
962 }
963 } else {
964 $this->error = $this->db->error();
965 $this->db->rollback();
966 return -1;
967 }
968 }
969
978 public function create($user, $notrigger = 0)
979 {
980 global $conf, $langs, $mysoc;
981 $error = 0;
982
983 // Clean parameters
984
985 if (empty($this->socid)) {
986 $this->error = 'ErrorWrongParameters';
987 return -1;
988 }
989
990 // Set tmp vars
991 $date = ($this->date_commande ? $this->date_commande : $this->date);
992 $this->import_key = trim((string) $this->import_key);
993 $delivery_date = $this->delivery_date;
994
995 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
996 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
997 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
998 } else {
999 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1000 }
1001 if (empty($this->fk_multicurrency)) {
1002 $this->multicurrency_code = $conf->currency;
1003 $this->fk_multicurrency = 0;
1004 $this->multicurrency_tx = 1;
1005 }
1006 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
1007 $this->entity = setEntity($this);
1008
1009 dol_syslog(get_class($this)."::create user=".$user->id);
1010
1011 // Check parameters
1012 if (!empty($this->ref)) { // We check that ref is not already used
1013 $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
1014 if ($result > 0) {
1015 $this->error = 'ErrorRefAlreadyExists';
1016 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1017 $this->db->rollback();
1018 return -1;
1019 }
1020 }
1021
1022 $soc = new Societe($this->db);
1023 $result = $soc->fetch($this->socid);
1024 if ($result < 0) {
1025 $this->error = "Failed to fetch company";
1026 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1027 return -2;
1028 }
1029 if (getDolGlobalString('ORDER_REQUIRE_SOURCE') && $this->source < 0) {
1030 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Source"));
1031 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1032 return -1;
1033 }
1034
1035 $this->date_creation = dol_now();
1036
1037 $this->db->begin();
1038
1039 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1040 $sql .= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client";
1041 $sql .= ", model_pdf, fk_cond_reglement, deposit_percent, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
1042 $sql .= ", fk_shipping_method";
1043 $sql .= ", fk_warehouse";
1044 $sql .= ", fk_incoterms, location_incoterms";
1045 $sql .= ", entity, module_source, pos_source";
1046 $sql .= ", fk_multicurrency";
1047 $sql .= ", multicurrency_code";
1048 $sql .= ", multicurrency_tx";
1049 $sql .= ", import_key";
1050 $sql .= ")";
1051 $sql .= " VALUES ('(PROV)', ".((int) $this->socid).", '".$this->db->idate($this->date_creation)."', ".($user->id > 0 ? ((int) $user->id) : "null");
1052 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1053 $sql .= ", '".$this->db->idate($date)."'";
1054 $sql .= ", ".($this->source >= 0 && $this->source != '' ? $this->db->escape((string) $this->source) : 'null');
1055 $sql .= ", '".$this->db->escape($this->note_private)."'";
1056 $sql .= ", '".$this->db->escape($this->note_public)."'";
1057 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1058 $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
1059 $sql .= ", '".$this->db->escape($this->model_pdf)."'";
1060 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
1061 $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1062 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
1063 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1064 $sql .= ", ".($this->availability_id > 0 ? ((int) $this->availability_id) : "null");
1065 $sql .= ", ".($this->demand_reason_id > 0 ? ((int) $this->demand_reason_id) : "null");
1066 $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
1067 $sql .= ", ".($this->fk_delivery_address > 0 ? ((int) $this->fk_delivery_address) : 'NULL');
1068 $sql .= ", ".(!empty($this->shipping_method_id) && $this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : 'NULL');
1069 $sql .= ", ".(!empty($this->warehouse_id) && $this->warehouse_id > 0 ? ((int) $this->warehouse_id) : 'NULL');
1070 $sql .= ", ".(int) $this->fk_incoterms;
1071 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1072 $sql .= ", ".(int) $this->entity;
1073 $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
1074 $sql .= ", ".((!is_null($this->pos_source) && $this->pos_source != '') ? "'".$this->db->escape($this->pos_source)."'" : "null"); // Can be null, '', '0', '1'
1075 $sql .= ", ".(int) $this->fk_multicurrency;
1076 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1077 $sql .= ", ".(float) $this->multicurrency_tx;
1078 $sql .= ", '".$this->db->escape($this->import_key)."'";
1079 $sql .= ")";
1080
1081 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1082 $resql = $this->db->query($sql);
1083 if ($resql) {
1084 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande');
1085
1086 if ($this->id) {
1087 $fk_parent_line = 0;
1088 $num = count($this->lines);
1089
1090 /*
1091 * Insert products details into db
1092 */
1093 for ($i = 0; $i < $num; $i++) {
1094 $line = $this->lines[$i];
1095
1096 // Test and convert into OrderLine object this->lines[$i]. When coming from REST API, we may still have an array
1097 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
1098 if (!is_object($line)) {
1099 $lineobj = new OrderLine($this->db);
1100 foreach ($line as $key => $val) {
1101 $lineobj->$key = $val;
1102 }
1103 $line = $lineobj;
1104 $this->lines[$i] = $line;
1105 }
1106
1107 // Reset fk_parent_line for no child products and special product
1108 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1109 $fk_parent_line = 0;
1110 }
1111
1112 // Complete vat rate with code
1113 $vatrate = $line->tva_tx;
1114 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
1115 $vatrate .= ' ('.$line->vat_src_code.')';
1116 }
1117
1118 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
1119 $originid = $line->origin_id;
1120 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
1121 } else {
1122 $originid = $line->id;
1123 $origintype = $this->element;
1124 }
1125
1126 // ref_ext
1127 if (empty($line->ref_ext)) {
1128 $line->ref_ext = '';
1129 }
1130
1131 $result = $this->addline(
1132 $line->desc,
1133 $line->subprice,
1134 $line->qty,
1135 $vatrate,
1136 $line->localtax1_tx,
1137 $line->localtax2_tx,
1138 $line->fk_product,
1139 $line->remise_percent,
1140 $line->info_bits,
1141 $line->fk_remise_except,
1142 'HT',
1143 0,
1144 $line->date_start,
1145 $line->date_end,
1146 $line->product_type,
1147 $line->rang,
1148 $line->special_code,
1149 $fk_parent_line,
1150 $line->fk_fournprice,
1151 $line->pa_ht,
1152 $line->label,
1153 $line->array_options,
1154 $line->fk_unit,
1155 (string) $origintype,
1156 $originid,
1157 0,
1158 $line->ref_ext,
1159 1
1160 );
1161
1162 if ($result < 0) {
1163 if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER) {
1164 $this->error = $this->db->lasterror();
1165 $this->errors[] = $this->error;
1166 dol_print_error($this->db);
1167 }
1168 $this->db->rollback();
1169 return -1;
1170 }
1171 // Defined the new fk_parent_line
1172 if ($result > 0 && $line->product_type == 9) {
1173 $fk_parent_line = $result;
1174 }
1175 }
1176
1177 $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1178
1179 // update ref
1180 $initialref = '(PROV'.$this->id.')';
1181 if (!empty($this->ref)) {
1182 $initialref = $this->ref;
1183 }
1184
1185 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id);
1186 if ($this->db->query($sql)) {
1187 $this->ref = $initialref;
1188
1189 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1190 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1191 }
1192
1193 // Add object linked
1194 if (!empty($this->linked_objects) && is_array($this->linked_objects)) {
1195 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1196 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, ...))
1197 foreach ($tmp_origin_id as $origin_id) {
1198 $ret = $this->add_object_linked($origin, $origin_id);
1199 if (!$ret) {
1200 $this->error = $this->db->lasterror();
1201 $error++;
1202 }
1203 }
1204 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1205 $origin_id = $tmp_origin_id;
1206 $ret = $this->add_object_linked($origin, $origin_id);
1207 if (!$ret) {
1208 $this->error = $this->db->lasterror();
1209 $error++;
1210 }
1211 }
1212 }
1213 }
1214
1215 if (!$error && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1216 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
1217 $originidforcontact = $this->origin_id;
1218 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1219 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1220 $exp = new Expedition($this->db);
1221 $exp->fetch($this->origin_id);
1222 $exp->fetchObjectLinked();
1223 if (count($exp->linkedObjectsIds['commande']) > 0) {
1224 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1225 $originforcontact = 'commande';
1226 if (is_object($value)) {
1227 $originidforcontact = $value->id;
1228 } else {
1229 $originidforcontact = $value;
1230 }
1231 break; // We take first one
1232 }
1233 }
1234 }
1235
1236 $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
1237 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1238
1239 $resqlcontact = $this->db->query($sqlcontact);
1240 if ($resqlcontact) {
1241 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1242 //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1243 $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
1244 }
1245 } else {
1246 dol_print_error($this->db);
1247 }
1248 }
1249
1250 if (!$error) {
1251 $result = $this->insertExtraFields();
1252 if ($result < 0) {
1253 $error++;
1254 }
1255 }
1256
1257 if (!$error && !$notrigger) {
1258 // Call trigger
1259 $result = $this->call_trigger('ORDER_CREATE', $user);
1260 if ($result < 0) {
1261 $error++;
1262 }
1263 // End call triggers
1264 }
1265
1266 if (!$error) {
1267 $this->db->commit();
1268 return $this->id;
1269 } else {
1270 $this->db->rollback();
1271 return -1 * $error;
1272 }
1273 } else {
1274 $this->error = $this->db->lasterror();
1275 $this->db->rollback();
1276 return -1;
1277 }
1278 }
1279
1280 return 0;
1281 } else {
1282 $this->error = $this->db->lasterror();
1283 $this->db->rollback();
1284 return -1;
1285 }
1286 }
1287
1288
1296 public function createFromClone(User $user, $socid = 0)
1297 {
1298 global $user, $hookmanager;
1299
1300 $error = 0;
1301
1302 $this->db->begin();
1303
1304 // get lines so they will be clone
1305 foreach ($this->lines as $line) {
1306 $line->fetch_optionals();
1307 }
1308
1309 // Load source object
1310 $objFrom = clone $this;
1311
1312 // Change socid if needed
1313 if (!empty($socid) && $socid != $this->socid) {
1314 $objsoc = new Societe($this->db);
1315
1316 if ($objsoc->fetch($socid) > 0) {
1317 $this->socid = $objsoc->id;
1318 $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1319 $this->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : '0');
1320 $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1321 $this->fk_project = 0;
1322 $this->fk_delivery_address = 0;
1323 }
1324
1325 // TODO Change product price if multi-prices
1326 }
1327
1328 $this->id = 0;
1329 $this->ref = '';
1330 $this->statut = self::STATUS_DRAFT; // deprecated
1331 $this->status = self::STATUS_DRAFT;
1332
1333 // Clear fields
1334 $this->user_author_id = $user->id;
1335 $this->user_validation_id = 0;
1336 $this->date = dol_now();
1337 $this->date_commande = dol_now();
1338 $this->date_creation = '';
1339 $this->date_validation = '';
1340 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1341 $this->ref_client = '';
1342 $this->ref_customer = '';
1343 }
1344
1345 // Do not clone ref_ext
1346 $num = count($this->lines);
1347 for ($i = 0; $i < $num; $i++) {
1348 $this->lines[$i]->ref_ext = '';
1349 }
1350
1351 // Create clone
1352 $this->context['createfromclone'] = 'createfromclone';
1353 $result = $this->create($user);
1354 if ($result < 0) {
1355 $error++;
1356 }
1357
1358 if (!$error) {
1359 // copy internal contacts
1360 if ($this->copy_linked_contact($objFrom, 'internal') < 0) {
1361 $error++;
1362 }
1363 }
1364
1365 if (!$error) {
1366 // copy external contacts if same company
1367 if ($this->socid == $objFrom->socid) {
1368 if ($this->copy_linked_contact($objFrom, 'external') < 0) {
1369 $error++;
1370 }
1371 }
1372 }
1373
1374 if (!$error) {
1375 // Hook of thirdparty module
1376 if (is_object($hookmanager)) {
1377 $parameters = array('objFrom' => $objFrom);
1378 $action = '';
1379 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1380 if ($reshook < 0) {
1381 $this->setErrorsFromObject($hookmanager);
1382 $error++;
1383 }
1384 }
1385 }
1386
1387 unset($this->context['createfromclone']);
1388
1389 // End
1390 if (!$error) {
1391 $this->db->commit();
1392 return $this->id;
1393 } else {
1394 $this->db->rollback();
1395 return -1;
1396 }
1397 }
1398
1399
1407 public function createFromProposal($object, User $user)
1408 {
1409 global $conf, $hookmanager;
1410
1411 require_once DOL_DOCUMENT_ROOT . '/multicurrency/class/multicurrency.class.php';
1412 require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
1413
1414 $error = 0;
1415
1416 $this->date_commande = dol_now();
1417 $this->date = dol_now();
1418 $this->source = 0;
1419
1420 $num = count($object->lines);
1421 for ($i = 0; $i < $num; $i++) {
1422 $line = new OrderLine($this->db);
1423
1424 $line->libelle = $object->lines[$i]->libelle;
1425 $line->label = $object->lines[$i]->label;
1426 $line->desc = $object->lines[$i]->desc;
1427 $line->price = $object->lines[$i]->price;
1428 $line->subprice = $object->lines[$i]->subprice;
1429 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1430 $line->tva_tx = $object->lines[$i]->tva_tx;
1431 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1432 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1433 $line->qty = $object->lines[$i]->qty;
1434 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1435 $line->remise_percent = $object->lines[$i]->remise_percent;
1436 $line->fk_product = $object->lines[$i]->fk_product;
1437 $line->info_bits = $object->lines[$i]->info_bits;
1438 $line->product_type = $object->lines[$i]->product_type;
1439 $line->rang = $object->lines[$i]->rang;
1440 $line->special_code = $object->lines[$i]->special_code;
1441 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1442 $line->fk_unit = $object->lines[$i]->fk_unit;
1443
1444 $line->date_start = $object->lines[$i]->date_start;
1445 $line->date_end = $object->lines[$i]->date_end;
1446
1447 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1448 $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
1449 $line->pa_ht = $marginInfos[0];
1450 $line->marge_tx = $marginInfos[1];
1451 $line->marque_tx = $marginInfos[2];
1452
1453 $line->origin = $object->element;
1454 $line->origin_id = $object->lines[$i]->id;
1455
1456 // get extrafields from original line
1457 $object->lines[$i]->fetch_optionals();
1458 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1459 $line->array_options[$options_key] = $value;
1460 }
1461
1462 $this->lines[$i] = $line;
1463 }
1464
1465 $this->entity = $object->entity;
1466 $this->socid = $object->socid;
1467 $this->fk_project = $object->fk_project;
1468 $this->cond_reglement_id = $object->cond_reglement_id;
1469 $this->deposit_percent = $object->deposit_percent;
1470 $this->mode_reglement_id = $object->mode_reglement_id;
1471 $this->fk_account = $object->fk_account;
1472 $this->availability_id = $object->availability_id;
1473 $this->demand_reason_id = $object->demand_reason_id;
1474 $this->delivery_date = $object->delivery_date;
1475 $this->shipping_method_id = $object->shipping_method_id;
1476 $this->warehouse_id = $object->warehouse_id;
1477 $this->fk_delivery_address = $object->fk_delivery_address;
1478 $this->contact_id = $object->contact_id;
1479 $this->ref_client = $object->ref_client;
1480 $this->ref_customer = $object->ref_client;
1481
1482 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1483 $this->note_private = $object->note_private;
1484 $this->note_public = $object->note_public;
1485 }
1486
1487 $this->origin = $object->element;
1488 $this->origin_id = $object->id;
1489
1490 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1491 if (isModEnabled('multicurrency')) {
1492 if (!empty($object->multicurrency_code)) {
1493 $this->multicurrency_code = $object->multicurrency_code;
1494 }
1495 if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($object->multicurrency_tx)) {
1496 $this->multicurrency_tx = $object->multicurrency_tx;
1497 }
1498
1499 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1500 $tmparray = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date_commande);
1501 $this->fk_multicurrency = $tmparray[0];
1502 $this->multicurrency_tx = $tmparray[1];
1503 } else {
1504 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1505 }
1506 if (empty($this->fk_multicurrency)) {
1507 $this->multicurrency_code = $conf->currency;
1508 $this->fk_multicurrency = 0;
1509 $this->multicurrency_tx = 1;
1510 }
1511 }
1512
1513 // get extrafields from original line
1514 $object->fetch_optionals();
1515
1516 $e = new ExtraFields($this->db);
1517 $element_extrafields = $e->fetch_name_optionals_label($this->table_element);
1518
1519 foreach ($object->array_options as $options_key => $value) {
1520 if (array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)) {
1521 $this->array_options[$options_key] = $value;
1522 }
1523 }
1524 // Possibility to add external linked objects with hooks
1525 $this->linked_objects[$this->origin] = $this->origin_id;
1526 if (isset($object->other_linked_objects) && is_array($object->other_linked_objects) && !empty($object->other_linked_objects)) {
1527 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1528 }
1529
1530 $ret = $this->create($user);
1531
1532 if ($ret > 0) {
1533 // Actions hooked (by external module)
1534 $hookmanager->initHooks(array('orderdao'));
1535
1536 $parameters = array('objFrom' => $object);
1537 $action = '';
1538 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1539 if ($reshook < 0) {
1540 $this->setErrorsFromObject($hookmanager);
1541 $error++;
1542 }
1543
1544 if (!$error) {
1545 // Validate immediately the order
1546 if (getDolGlobalString('ORDER_VALID_AFTER_CLOSE_PROPAL')) {
1547 $this->fetch($ret);
1548 $this->valid($user);
1549 }
1550 return $ret;
1551 } else {
1552 return -1;
1553 }
1554 } else {
1555 return -1;
1556 }
1557 }
1558
1559
1600 public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $info_bits = 0, $fk_remise_except = 0, $price_base_type = 'HT', $pu_ttc = 0, $date_start = '', $date_end = '', $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $array_options = array(), $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $ref_ext = '', $noupdateafterinsertline = 0)
1601 {
1602 global $mysoc, $langs, $user;
1603
1604 $logtext = "::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent";
1605 $logtext .= ", info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start";
1606 $logtext .= ", date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise, ref_ext=$ref_ext rang=$rang";
1607 dol_syslog(get_class($this).$logtext, LOG_DEBUG);
1608
1609 if ($this->status == self::STATUS_DRAFT) {
1610 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1611
1612 // Clean parameters
1613
1614 if (empty($remise_percent)) {
1615 $remise_percent = 0;
1616 }
1617 if (empty($qty)) {
1618 $qty = 0;
1619 }
1620 if (empty($info_bits)) {
1621 $info_bits = 0;
1622 }
1623 if (empty($rang)) {
1624 $rang = 0;
1625 }
1626 if (empty($txtva)) {
1627 $txtva = 0;
1628 }
1629 if (empty($txlocaltax1)) {
1630 $txlocaltax1 = 0;
1631 }
1632 if (empty($txlocaltax2)) {
1633 $txlocaltax2 = 0;
1634 }
1635 if (empty($fk_parent_line) || $fk_parent_line < 0) {
1636 $fk_parent_line = 0;
1637 }
1638 if (empty($this->fk_multicurrency)) {
1639 $this->fk_multicurrency = 0;
1640 }
1641 if (empty($ref_ext)) {
1642 $ref_ext = '';
1643 }
1644
1645 $remise_percent = (float) price2num($remise_percent);
1646 $qty = (float) price2num($qty);
1647 $pu_ht = price2num($pu_ht);
1648 $pu_ht_devise = price2num($pu_ht_devise);
1649 $pu_ttc = price2num($pu_ttc);
1650 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
1651 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
1652 $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
1653 }
1654 $txlocaltax1 = price2num($txlocaltax1);
1655 $txlocaltax2 = price2num($txlocaltax2);
1656 if ($price_base_type == 'HT') {
1657 $pu = $pu_ht;
1658 } else {
1659 $pu = $pu_ttc;
1660 }
1661 $label = trim($label);
1662 $desc = trim($desc);
1663
1664 // Check parameters
1665 if ($type < 0) {
1666 return -1;
1667 }
1668
1669 if ($date_start && $date_end && $date_start > $date_end) {
1670 $langs->load("errors");
1671 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1672 return -1;
1673 }
1674
1675 $this->db->begin();
1676
1677 $product_type = $type;
1678 if (!empty($fk_product) && $fk_product > 0) {
1679 $product = new Product($this->db);
1680 $result = $product->fetch($fk_product);
1681 $product_type = $product->type;
1682
1683 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_ORDER') && $product->isStockManaged()) {
1684 // get real stock
1685 $productChildrenNb = 0;
1686 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
1687 $productChildrenNb = $product->hasFatherOrChild(1);
1688 }
1689 if ($productChildrenNb > 0) {
1690 // compute real stock from each subcomponent
1691 $product_stock = null;
1692 $product->loadStockForVirtualProduct('warehouseopen', $qty);
1693 foreach ($product->stock_warehouse as $componentStockWarehouse) {
1694 if ($product_stock === null) {
1695 $product_stock = $componentStockWarehouse->real;
1696 } else {
1697 $product_stock = min($product_stock, $componentStockWarehouse->real);
1698 }
1699 }
1700 if ($product_stock === null) {
1701 $product_stock = 0;
1702 }
1703 } else {
1704 $product_stock = $product->stock_reel;
1705 }
1706
1707 if ($product_stock < $qty) {
1708 $langs->load("errors");
1709 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
1710 $this->errors[] = $this->error;
1711 dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
1712 $this->db->rollback();
1714 }
1715 }
1716 }
1717 // Calcul du total TTC et de la TVA pour la ligne a partir de
1718 // qty, pu, remise_percent et txtva
1719 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1720 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1721
1722 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
1723
1724 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
1725 $tmpproduct = new Product($this->db);
1726 $result = $tmpproduct->fetch($fk_product);
1727 $newqty = $this->roundQtyToPackaging($qty, $tmpproduct->packaging);
1728 if ($newqty != $qty) {
1729 $qty = $newqty;
1730 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
1731 }
1732 }
1733
1734 // Clean vat code
1735 $reg = array();
1736 $vat_src_code = '';
1737 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1738 $vat_src_code = $reg[1];
1739 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1740 }
1741
1742 $tabprice = calcul_price_total($qty, (float) $pu, $remise_percent, $txtva, (float) $txlocaltax1, (float) $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_ht_devise);
1743
1744 /*var_dump($txlocaltax1);
1745 var_dump($txlocaltax2);
1746 var_dump($localtaxes_type);
1747 var_dump($tabprice);
1748 var_dump($tabprice[9]);
1749 var_dump($tabprice[10]);
1750 exit;*/
1751
1752 $total_ht = $tabprice[0];
1753 $total_tva = $tabprice[1];
1754 $total_ttc = $tabprice[2];
1755 $total_localtax1 = $tabprice[9];
1756 $total_localtax2 = $tabprice[10];
1757 $pu_ht = $tabprice[3];
1758
1759 // MultiCurrency
1760 $multicurrency_total_ht = $tabprice[16];
1761 $multicurrency_total_tva = $tabprice[17];
1762 $multicurrency_total_ttc = $tabprice[18];
1763 $pu_ht_devise = $tabprice[19];
1764
1765 // Rang to use
1766 $ranktouse = $rang;
1767
1768 if (empty($ranktouse) || $ranktouse == -1) {
1769 $rangmax = $this->line_max($fk_parent_line);
1770 $ranktouse = $rangmax + 1;
1771 }
1772
1773 // Insert line
1774 $this->line = new OrderLine($this->db);
1775
1776 $this->line->context = $this->context;
1777
1778 $this->line->fk_commande = $this->id;
1779 $this->line->label = $label;
1780 $this->line->desc = $desc;
1781 $this->line->qty = (float) $qty;
1782 $this->line->ref_ext = $ref_ext;
1783
1784 $this->line->vat_src_code = $vat_src_code;
1785 $this->line->tva_tx = $txtva;
1786 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
1787 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
1788 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
1789 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
1790 $this->line->fk_product = $fk_product;
1791 $this->line->product_type = $product_type;
1792 $this->line->fk_remise_except = $fk_remise_except;
1793 $this->line->remise_percent = $remise_percent;
1794 $this->line->subprice = (float) $pu_ht;
1795 $this->line->rang = $ranktouse;
1796 $this->line->info_bits = $info_bits;
1797 $this->line->total_ht = (float) $total_ht;
1798 $this->line->total_tva = (float) $total_tva;
1799 $this->line->total_localtax1 = (float) $total_localtax1;
1800 $this->line->total_localtax2 = (float) $total_localtax2;
1801 $this->line->total_ttc = (float) $total_ttc;
1802 $this->line->special_code = $special_code;
1803 if (empty($qty) && empty($special_code)) {
1804 $this->line->special_code = 3;
1805 }
1806 $this->line->origin = $origin;
1807 $this->line->origin_id = $origin_id;
1808 $this->line->fk_parent_line = $fk_parent_line;
1809 $this->line->fk_unit = $fk_unit;
1810
1811 $this->line->date_start = $date_start;
1812 $this->line->date_end = $date_end;
1813
1814 $this->line->fk_fournprice = $fk_fournprice;
1815 $this->line->pa_ht = $pa_ht; // Can be '' when not defined or 0 if defined to 0 or a price value
1816
1817 // Multicurrency
1818 $this->line->fk_multicurrency = $this->fk_multicurrency;
1819 $this->line->multicurrency_code = $this->multicurrency_code;
1820 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
1821 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
1822 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
1823 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
1824
1825 if (is_array($array_options) && count($array_options) > 0) {
1826 $this->line->array_options = $array_options;
1827 }
1828
1829 $result = $this->line->insert($user);
1830 if ($result > 0) {
1831 // Update denormalized fields at the order level
1832 if (empty($noupdateafterinsertline)) {
1833 $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
1834 }
1835
1836 if ($result > 0) {
1837 if (!isset($this->context['createfromclone'])) {
1838 if (!empty($fk_parent_line)) {
1839 // Always reorder if child line
1840 $this->line_order(true, 'DESC');
1841 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
1842 // Update all rank of all other lines starting from the same $ranktouse
1843 foreach ($this->lines as $tmpline) {
1844 if ($tmpline->rang >= $ranktouse) {
1845 if (!empty($tmpline->id)) {
1846 $this->updateRangOfLine($tmpline->id, $tmpline->rang + 1);
1847 }
1848 }
1849 }
1850 }
1851
1852 $this->lines[] = $this->line;
1853 } else {
1854 foreach ($this->lines as $line) {
1855 if ($line->id == $origin_id) {
1856 $this->line->extraparams = $line->extraparams;
1857 $this->line->setExtraParameters();
1858 }
1859 }
1860 }
1861
1862 $this->db->commit();
1863 return $this->line->id;
1864 } else {
1865 $this->db->rollback();
1866 return -1;
1867 }
1868 } else {
1869 $this->setErrorsFromObject($this->line);
1870 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1871 $this->db->rollback();
1872 return -2;
1873 }
1874 } else {
1875 dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR);
1876 return -3;
1877 }
1878 }
1879
1880
1881 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1895 public function add_product($idproduct, $qty, $remise_percent = 0.0, $date_start = '', $date_end = '')
1896 {
1897 // phpcs:enable
1898 global $conf, $mysoc;
1899
1900 if (!$qty) {
1901 $qty = 1;
1902 }
1903
1904 if ($idproduct > 0) {
1905 $prod = new Product($this->db);
1906 $prod->fetch($idproduct);
1907
1908 $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
1909 $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
1910 if (empty($tva_tx)) {
1911 $tva_npr = 0;
1912 }
1913 $vat_src_code = ''; // May be defined into tva_tx
1914
1915 $localtax1_tx = get_localtax($tva_tx, 1, $this->thirdparty, $mysoc, $tva_npr);
1916 $localtax2_tx = get_localtax($tva_tx, 2, $this->thirdparty, $mysoc, $tva_npr);
1917
1918 // multiprix
1919 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $this->thirdparty->price_level) {
1920 $price = $prod->multiprices[$this->thirdparty->price_level];
1921 $price_ttc = $prod->multiprices_ttc[$this->thirdparty->price_level];
1922 } else {
1923 $price = $prod->price;
1924 $price_ttc = $prod->price_ttc;
1925 }
1926
1927 $line = new OrderLine($this->db);
1928
1929 $line->context = $this->context;
1930
1931 $line->fk_product = $idproduct;
1932 $line->desc = $prod->description;
1933 $line->qty = $qty;
1934 $line->subprice = $price;
1935 $line->subprice_ttc = $price_ttc;
1936 $line->remise_percent = $remise_percent;
1937 $line->vat_src_code = $vat_src_code;
1938 $line->tva_tx = $tva_tx;
1939 $line->localtax1_tx = $localtax1_tx;
1940 $line->localtax2_tx = $localtax2_tx;
1941
1942 $line->product_ref = $prod->ref;
1943 $line->product_label = $prod->label;
1944 $line->product_desc = $prod->description;
1945 $line->fk_unit = $prod->fk_unit;
1946
1947 // Save the start and end date of the line in the object
1948 if ($date_start) {
1949 $line->date_start = $date_start;
1950 }
1951 if ($date_end) {
1952 $line->date_end = $date_end;
1953 }
1954
1955 $this->lines[] = $line;
1956
1974 }
1975 }
1976
1977
1987 public function fetch($id, $ref = '', $ref_ext = '', $notused = '')
1988 {
1989 // Check parameters
1990 if (empty($id) && empty($ref) && empty($ref_ext)) {
1991 return -1;
1992 }
1993
1994 $sql = 'SELECT c.rowid, c.entity, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_user_modif, c.fk_statut as status';
1995 $sql .= ', c.amount_ht, c.total_ht, c.total_ttc, c.total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.deposit_percent, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
1996 $sql .= ', c.fk_account';
1997 $sql .= ', c.date_commande, c.date_valid, c.tms';
1998 $sql .= ', c.date_livraison as delivery_date';
1999 $sql .= ', c.fk_shipping_method';
2000 $sql .= ', c.fk_warehouse';
2001 $sql .= ', c.fk_projet as fk_project, c.source, c.facture as billed';
2002 $sql .= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.model_pdf, c.last_main_doc, c.fk_delivery_address, c.extraparams';
2003 $sql .= ', c.fk_incoterms, c.location_incoterms';
2004 $sql .= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
2005 $sql .= ", c.module_source, c.pos_source";
2006 $sql .= ", i.libelle as label_incoterms";
2007 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2008 $sql .= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
2009 $sql .= ', ca.code as availability_code, ca.label as availability_label';
2010 $sql .= ', dr.code as demand_reason_code';
2011 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as c';
2012 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid';
2013 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id';
2014 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
2015 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = dr.rowid';
2016 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
2017
2018 if ($id) {
2019 $sql .= " WHERE c.rowid = ".((int) $id);
2020 } else {
2021 $sql .= " WHERE c.entity IN (".getEntity('commande').")"; // Don't use entity if you use rowid
2022 }
2023
2024 if ($ref) {
2025 $sql .= " AND c.ref = '".$this->db->escape($ref)."'";
2026 }
2027 if ($ref_ext) {
2028 $sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'";
2029 }
2030
2031 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2032 $result = $this->db->query($sql);
2033 if ($result) {
2034 $obj = $this->db->fetch_object($result);
2035 if ($obj) {
2036 $this->id = $obj->rowid;
2037 $this->entity = $obj->entity;
2038
2039 $this->ref = $obj->ref;
2040 $this->ref_client = $obj->ref_client;
2041 $this->ref_customer = $obj->ref_client;
2042 $this->ref_ext = $obj->ref_ext;
2043
2044 $this->socid = $obj->fk_soc;
2045 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2046
2047 $this->fk_project = $obj->fk_project;
2048 $this->project = null; // Clear if another value was already set by fetch_projet
2049
2050 $this->statut = $obj->status; // deprecated
2051 $this->status = $obj->status;
2052
2053 $this->user_author_id = $obj->fk_user_author;
2054 $this->user_creation_id = $obj->fk_user_author;
2055 $this->user_validation_id = $obj->fk_user_valid;
2056 $this->user_modification_id = $obj->fk_user_modif;
2057 $this->total_ht = $obj->total_ht;
2058 $this->total_tva = $obj->total_tva;
2059 $this->total_localtax1 = $obj->total_localtax1;
2060 $this->total_localtax2 = $obj->total_localtax2;
2061 $this->total_ttc = $obj->total_ttc;
2062 $this->date = $this->db->jdate($obj->date_commande);
2063 $this->date_commande = $this->db->jdate($obj->date_commande);
2064 $this->date_creation = $this->db->jdate($obj->date_creation);
2065 $this->date_validation = $this->db->jdate($obj->date_valid);
2066 $this->date_modification = $this->db->jdate($obj->tms);
2067 $this->source = $obj->source;
2068 $this->billed = $obj->billed;
2069 $this->note = $obj->note_private; // deprecated
2070 $this->note_private = $obj->note_private;
2071 $this->note_public = $obj->note_public;
2072 $this->model_pdf = $obj->model_pdf;
2073 $this->last_main_doc = $obj->last_main_doc;
2074 $this->mode_reglement_id = $obj->fk_mode_reglement;
2075 $this->mode_reglement_code = $obj->mode_reglement_code;
2076 $this->mode_reglement = $obj->mode_reglement_libelle;
2077 $this->cond_reglement_id = $obj->fk_cond_reglement;
2078 $this->cond_reglement_code = $obj->cond_reglement_code;
2079 $this->cond_reglement = $obj->cond_reglement_libelle;
2080 $this->cond_reglement_label = $obj->cond_reglement_libelle;
2081 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2082 $this->deposit_percent = $obj->deposit_percent;
2083 $this->fk_account = $obj->fk_account;
2084 $this->availability_id = $obj->fk_availability;
2085 $this->availability_code = $obj->availability_code;
2086 $this->availability = $obj->availability_label;
2087 $this->demand_reason_id = $obj->fk_input_reason;
2088 $this->demand_reason_code = $obj->demand_reason_code;
2089 $this->delivery_date = $this->db->jdate($obj->delivery_date);
2090 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2091 $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
2092 $this->fk_delivery_address = $obj->fk_delivery_address;
2093 $this->module_source = $obj->module_source;
2094 $this->pos_source = $obj->pos_source;
2095
2096 //Incoterms
2097 $this->fk_incoterms = $obj->fk_incoterms;
2098 $this->location_incoterms = $obj->location_incoterms;
2099 $this->label_incoterms = $obj->label_incoterms;
2100
2101 // Multicurrency
2102 $this->fk_multicurrency = $obj->fk_multicurrency;
2103 $this->multicurrency_code = $obj->multicurrency_code;
2104 $this->multicurrency_tx = $obj->multicurrency_tx;
2105 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2106 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2107 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2108
2109 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2110
2111 $this->lines = array();
2112
2113 // Retrieve all extrafield
2114 // fetch optionals attributes and labels
2115 $this->fetch_optionals();
2116
2117 $this->db->free($result);
2118
2119 // Lines
2120 $result = $this->fetch_lines();
2121 if ($result < 0) {
2122 return -3;
2123 }
2124 return 1;
2125 } else {
2126 $this->error = 'Order with id '.$id.' not found sql='.$sql;
2127 return 0;
2128 }
2129 } else {
2130 $this->error = $this->db->error();
2131 return -1;
2132 }
2133 }
2134
2135
2136 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2143 public function insert_discount($idremise)
2144 {
2145 // phpcs:enable
2146 global $langs;
2147
2148 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2149 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2150
2151 $this->db->begin();
2152
2153 $remise = new DiscountAbsolute($this->db);
2154 $result = $remise->fetch($idremise);
2155
2156 if ($result > 0) {
2157 if ($remise->fk_facture) { // Protection against multiple submission
2158 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2159 $this->db->rollback();
2160 return -5;
2161 }
2162
2163 $line = new OrderLine($this->db);
2164
2165 $line->fk_commande = $this->id;
2166 $line->fk_remise_except = $remise->id;
2167 $line->desc = $remise->description; // Description ligne
2168 $line->vat_src_code = $remise->vat_src_code;
2169 $line->tva_tx = $remise->tva_tx;
2170 $line->subprice = -(float) $remise->amount_ht;
2171 $line->price = -(float) $remise->amount_ht;
2172 $line->fk_product = 0; // Id produit predefini
2173 $line->qty = 1;
2174 $line->remise_percent = 0;
2175 $line->rang = -1;
2176 $line->info_bits = 2;
2177
2178 $line->total_ht = -(float) $remise->amount_ht;
2179 $line->total_tva = -(float) $remise->amount_tva;
2180 $line->total_ttc = -(float) $remise->amount_ttc;
2181
2182 $result = $line->insert();
2183 if ($result > 0) {
2184 $result = $this->update_price(1);
2185 if ($result > 0) {
2186 $this->db->commit();
2187 return 1;
2188 } else {
2189 $this->db->rollback();
2190 return -1;
2191 }
2192 } else {
2193 $this->setErrorsFromObject($line);
2194 $this->db->rollback();
2195 return -2;
2196 }
2197 } else {
2198 $this->db->rollback();
2199 return -2;
2200 }
2201 }
2202
2203
2204 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2212 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2213 {
2214 // phpcs:enable
2215 $this->lines = array();
2216
2217 $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx, l.ref_ext,';
2218 $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.subprice_ttc, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
2219 $sql .= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
2220 $sql .= ' l.fk_unit, l.extraparams,';
2221 $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_subprice_ttc, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2222 $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tosell as product_tosell, p.tobuy as product_tobuy, p.tobatch as product_tobatch, p.barcode as product_barcode,';
2223 $sql .= ' p.customcode, p.fk_country as country_id, c.code as country_code,';
2224 $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units, p.packaging';
2225 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as l';
2226 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
2227 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON c.rowid = p.fk_country';
2228 $sql .= ' WHERE l.fk_commande = '.((int) $this->id);
2229 if ($only_product) {
2230 $sql .= ' AND p.fk_product_type = 0';
2231 }
2232 $sql .= ' ORDER BY l.rang, l.rowid';
2233
2234 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
2235 $result = $this->db->query($sql);
2236 if ($result) {
2237 $num = $this->db->num_rows($result);
2238
2239 $i = 0;
2240 while ($i < $num) {
2241 $objp = $this->db->fetch_object($result);
2242
2243 $line = new OrderLine($this->db);
2244
2245 $line->rowid = $objp->rowid;
2246 $line->id = $objp->rowid;
2247 $line->fk_commande = $objp->fk_commande;
2248 $line->commande_id = $objp->fk_commande;
2249 $line->label = $objp->custom_label;
2250 $line->desc = $objp->description;
2251 $line->description = $objp->description; // Description line
2252 $line->product_type = $objp->product_type;
2253 $line->qty = $objp->qty;
2254 $line->ref_ext = $objp->ref_ext;
2255
2256 $line->vat_src_code = $objp->vat_src_code;
2257 $line->tva_tx = $objp->tva_tx;
2258 $line->localtax1_tx = $objp->localtax1_tx;
2259 $line->localtax2_tx = $objp->localtax2_tx;
2260 $line->localtax1_type = $objp->localtax1_type;
2261 $line->localtax2_type = $objp->localtax2_type;
2262 $line->total_ht = $objp->total_ht;
2263 $line->total_ttc = $objp->total_ttc;
2264 $line->total_tva = $objp->total_tva;
2265 $line->total_localtax1 = $objp->total_localtax1;
2266 $line->total_localtax2 = $objp->total_localtax2;
2267 $line->subprice = (float) $objp->subprice;
2268 $line->subprice_ttc = (float) $objp->subprice_ttc;
2269 $line->fk_remise_except = $objp->fk_remise_except;
2270 $line->remise_percent = $objp->remise_percent;
2271 $line->price = $objp->price;
2272 $line->fk_product = $objp->fk_product;
2273 $line->fk_fournprice = $objp->fk_fournprice;
2274 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2275 $line->pa_ht = $marginInfos[0];
2276 $line->marge_tx = $marginInfos[1];
2277 $line->marque_tx = $marginInfos[2];
2278 $line->rang = $objp->rang;
2279 $line->info_bits = $objp->info_bits;
2280 $line->special_code = $objp->special_code;
2281 $line->fk_parent_line = $objp->fk_parent_line;
2282
2283 $line->ref = $objp->product_ref;
2284 $line->libelle = $objp->product_label;
2285
2286 $line->product_ref = $objp->product_ref;
2287 $line->product_label = $objp->product_label;
2288 $line->product_tosell = $objp->product_tosell;
2289 $line->product_tobuy = $objp->product_tobuy;
2290 $line->product_desc = $objp->product_desc;
2291 $line->product_tobatch = $objp->product_tobatch;
2292 $line->product_barcode = $objp->product_barcode;
2293 $line->product_custom_code = $objp->customcode;
2294 $line->product_custom_country_id = $objp->country_id;
2295 $line->product_custom_country_code = $objp->country_code;
2296
2297 $line->fk_product_type = $objp->fk_product_type; // Produit ou service
2298 $line->fk_unit = $objp->fk_unit;
2299
2300 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2301
2302 $line->weight = $objp->weight;
2303 $line->weight_units = $objp->weight_units;
2304 $line->volume = $objp->volume;
2305 $line->volume_units = $objp->volume_units;
2306 $line->packaging = $objp->packaging;
2307
2308 $line->date_start = $this->db->jdate($objp->date_start);
2309 $line->date_end = $this->db->jdate($objp->date_end);
2310
2311 // Multicurrency
2312 $line->fk_multicurrency = $objp->fk_multicurrency;
2313 $line->multicurrency_code = $objp->multicurrency_code;
2314 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2315 $line->multicurrency_subprice_ttc = $objp->multicurrency_subprice_ttc;
2316 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2317 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2318 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2319
2320 $line->fetch_optionals();
2321
2322 // multilangs
2323 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2324 $tmpproduct = new Product($this->db);
2325 $tmpproduct->fetch($objp->fk_product);
2326 $tmpproduct->getMultiLangs();
2327
2328 $line->multilangs = $tmpproduct->multilangs;
2329 }
2330
2331 $this->lines[$i] = $line;
2332
2333 $i++;
2334 }
2335
2336 $this->db->free($result);
2337
2338 return 1;
2339 } else {
2340 $this->error = $this->db->error();
2341 return -3;
2342 }
2343 }
2344
2345
2351 public function getNbOfProductsLines()
2352 {
2353 $nb = 0;
2354 foreach ($this->lines as $line) {
2355 if ($line->product_type == 0) {
2356 $nb++;
2357 }
2358 }
2359 return $nb;
2360 }
2361
2367 public function getNbOfServicesLines()
2368 {
2369 $nb = 0;
2370 foreach ($this->lines as $line) {
2371 if ($line->product_type == 1) {
2372 $nb++;
2373 }
2374 }
2375 return $nb;
2376 }
2377
2383 public function getNbOfShipments()
2384 {
2385 $nb = 0;
2386
2387 $sql = 'SELECT COUNT(DISTINCT ed.fk_expedition) as nb';
2388 $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
2389 $sql .= ' '.MAIN_DB_PREFIX.$this->table_element_line.' as cd';
2390 $sql .= ' WHERE';
2391 $sql .= ' ed.fk_elementdet = cd.rowid';
2392 $sql .= ' AND cd.fk_commande = '.((int) $this->id);
2393 //print $sql;
2394
2395 dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG);
2396 $resql = $this->db->query($sql);
2397 if ($resql) {
2398 $obj = $this->db->fetch_object($resql);
2399 if ($obj) {
2400 $nb = (int) $obj->nb;
2401 }
2402
2403 $this->db->free($resql);
2404 return $nb;
2405 } else {
2406 $this->error = $this->db->lasterror();
2407 return -1;
2408 }
2409 }
2410
2419 public function loadExpeditions($filtre_statut = -1, $fk_product = 0)
2420 {
2421 $this->expeditions = array();
2422
2423 $sql = 'SELECT cd.rowid, cd.fk_product,';
2424 $sql .= ' sum(ed.qty) as qty';
2425 $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
2426 if ($filtre_statut >= 0) {
2427 $sql .= ' '.MAIN_DB_PREFIX.'expedition as e,';
2428 }
2429 $sql .= ' '.MAIN_DB_PREFIX.$this->table_element_line.' as cd';
2430 $sql .= ' WHERE';
2431 if ($filtre_statut >= 0) {
2432 $sql .= ' ed.fk_expedition = e.rowid AND';
2433 }
2434 $sql .= ' ed.fk_elementdet = cd.rowid';
2435 $sql .= ' AND cd.fk_commande = '.((int) $this->id);
2436 if ($fk_product > 0) {
2437 $sql .= ' AND cd.fk_product = '.((int) $fk_product);
2438 }
2439 if ($filtre_statut >= 0) {
2440 $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut);
2441 }
2442 $sql .= ' GROUP BY cd.rowid, cd.fk_product';
2443 //print $sql;
2444
2445 dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG);
2446 $resql = $this->db->query($sql);
2447 if ($resql) {
2448 $num = $this->db->num_rows($resql);
2449 $i = 0;
2450 while ($i < $num) {
2451 $obj = $this->db->fetch_object($resql);
2452 $this->expeditions[$obj->rowid] = $obj->qty;
2453 $i++;
2454 }
2455 $this->db->free($resql);
2456 return $num;
2457 } else {
2458 $this->error = $this->db->lasterror();
2459 return -1;
2460 }
2461 }
2462
2468 public function countNbOfShipments()
2469 {
2470 $sql = 'SELECT count(*)';
2471 $sql .= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
2472 $sql .= ', '.MAIN_DB_PREFIX.'element_element as el';
2473 $sql .= ' WHERE el.fk_source = '.((int) $this->id);
2474 $sql .= " AND el.sourcetype = 'commande'";
2475 $sql .= " AND el.fk_target = e.rowid";
2476 $sql .= " AND el.targettype = 'shipping'";
2477
2478 $resql = $this->db->query($sql);
2479 if ($resql) {
2480 $row = $this->db->fetch_row($resql);
2481 return $row[0];
2482 } else {
2483 dol_print_error($this->db);
2484 }
2485
2486 return 0;
2487 }
2488
2497 public function deleteLine($user = null, $lineid = 0, $id = 0)
2498 {
2499 if ($this->status == self::STATUS_DRAFT) {
2500 $this->db->begin();
2501
2502 // Delete line
2503 $line = new OrderLine($this->db);
2504
2505 $line->context = $this->context;
2506
2507 // Load data
2508 $line->fetch($lineid);
2509
2510 if ($id <= 0) {
2511 $id = $this->id;
2512 }
2513 if ($id > 0 && (int) $line->fk_commande !== (int) $id) {
2514 $this->db->rollback();
2515 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2516 return -1;
2517 }
2518
2519 // Memorize previous line for triggers
2520 $staticline = clone $line;
2521 $line->oldline = $staticline;
2522
2523 if ($line->delete($user) > 0) {
2524 $result = $this->update_price(1);
2525
2526 if ($result > 0) {
2527 $this->db->commit();
2528 return 1;
2529 } else {
2530 $this->db->rollback();
2531 $this->error = $this->db->lasterror();
2532 return -1;
2533 }
2534 } else {
2535 $this->db->rollback();
2536 $this->setErrorsFromObject($line);
2537 return -1;
2538 }
2539 } else {
2540 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
2541 return -1;
2542 }
2543 }
2544
2545 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2556 public function set_remise($user, $remise, $notrigger = 0)
2557 {
2558 // phpcs:enable
2559 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
2560 // @phan-suppress-next-line PhanDeprecatedFunction
2561 return $this->setDiscount($user, $remise, $notrigger);
2562 }
2563
2572 public function setDiscount($user, $remise, $notrigger = 0)
2573 {
2574 $remise = trim((string) $remise) ? trim((string) $remise) : 0;
2575
2576 if ($user->hasRight('commande', 'creer')) {
2577 $error = 0;
2578
2579 $this->db->begin();
2580
2581 $remise = price2num($remise, 2);
2582
2583 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2584 $sql .= ' SET remise_percent = '.((float) $remise);
2585 $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_DRAFT);
2586
2587 dol_syslog(__METHOD__, LOG_DEBUG);
2588 $resql = $this->db->query($sql);
2589 if (!$resql) {
2590 $this->errors[] = $this->db->error();
2591 $error++;
2592 }
2593
2594 if (!$error) {
2595 $this->oldcopy = clone $this;
2596 $this->remise_percent = $remise;
2597 $this->update_price(1);
2598 }
2599
2600 if (!$notrigger && empty($error)) {
2601 // Call trigger
2602 $result = $this->call_trigger('ORDER_MODIFY', $user);
2603 if ($result < 0) {
2604 $error++;
2605 }
2606 // End call triggers
2607 }
2608
2609 if (!$error) {
2610 $this->db->commit();
2611 return 1;
2612 } else {
2613 foreach ($this->errors as $errmsg) {
2614 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2615 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2616 }
2617 $this->db->rollback();
2618 return -1 * $error;
2619 }
2620 }
2621
2622 return 0;
2623 }
2624
2625
2626 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2635 public function set_date($user, $date, $notrigger = 0)
2636 {
2637 // phpcs:enable
2638 if ($user->hasRight('commande', 'creer')) {
2639 $error = 0;
2640
2641 $this->db->begin();
2642
2643 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2644 $sql .= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
2645 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".((int) self::STATUS_DRAFT);
2646
2647 dol_syslog(__METHOD__, LOG_DEBUG);
2648 $resql = $this->db->query($sql);
2649 if (!$resql) {
2650 $this->errors[] = $this->db->error();
2651 $error++;
2652 }
2653
2654 if (!$error) {
2655 $this->oldcopy = clone $this;
2656 $this->date = $date;
2657 }
2658
2659 if (!$notrigger && empty($error)) {
2660 // Call trigger
2661 $result = $this->call_trigger('ORDER_MODIFY', $user);
2662 if ($result < 0) {
2663 $error++;
2664 }
2665 // End call triggers
2666 }
2667
2668 if (!$error) {
2669 $this->db->commit();
2670 return 1;
2671 } else {
2672 foreach ($this->errors as $errmsg) {
2673 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2674 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2675 }
2676 $this->db->rollback();
2677 return -1 * $error;
2678 }
2679 } else {
2680 return -2;
2681 }
2682 }
2683
2684 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2694 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2695 {
2696 // phpcs:enable
2697 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2698 }
2699
2708 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2709 {
2710 if ($user->hasRight('commande', 'creer')) {
2711 $error = 0;
2712
2713 $this->db->begin();
2714
2715 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2716 $sql .= " SET date_livraison = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2717 $sql .= " WHERE rowid = ".((int) $this->id);
2718
2719 dol_syslog(__METHOD__, LOG_DEBUG);
2720 $resql = $this->db->query($sql);
2721 if (!$resql) {
2722 $this->errors[] = $this->db->error();
2723 $error++;
2724 }
2725
2726 if (!$error) {
2727 $this->oldcopy = clone $this;
2728 $this->delivery_date = $delivery_date;
2729 }
2730
2731 if (!$notrigger && empty($error)) {
2732 // Call trigger
2733 $result = $this->call_trigger('ORDER_MODIFY', $user);
2734 if ($result < 0) {
2735 $error++;
2736 }
2737 // End call triggers
2738 }
2739
2740 if (!$error) {
2741 $this->db->commit();
2742 return 1;
2743 } else {
2744 foreach ($this->errors as $errmsg) {
2745 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2746 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2747 }
2748 $this->db->rollback();
2749 return -1 * $error;
2750 }
2751 } else {
2752 return -2;
2753 }
2754 }
2755
2756 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2770 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'c.date_commande', $sortorder = 'DESC')
2771 {
2772 // phpcs:enable
2773 global $user;
2774
2775 $ga = array();
2776
2777 $sql = "SELECT s.rowid, s.nom as name, s.client,";
2778 $sql .= " c.rowid as cid, c.ref";
2779 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2780 $sql .= ", sc.fk_soc, sc.fk_user";
2781 }
2782 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX.$this->table_element." as c";
2783 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2784 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2785 }
2786 $sql .= " WHERE c.entity IN (".getEntity('commande').")";
2787 $sql .= " AND c.fk_soc = s.rowid";
2788 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2789 $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2790 }
2791 if ($socid) {
2792 $sql .= " AND s.rowid = ".((int) $socid);
2793 }
2794 if ($draft) {
2795 $sql .= " AND c.fk_statut = ".self::STATUS_DRAFT;
2796 }
2797 if (is_object($excluser)) {
2798 $sql .= " AND c.fk_user_author <> ".((int) $excluser->id);
2799 }
2800 $sql .= $this->db->order($sortfield, $sortorder);
2801 $sql .= $this->db->plimit($limit, $offset);
2802
2803 $result = $this->db->query($sql);
2804 if ($result) {
2805 $numc = $this->db->num_rows($result);
2806 if ($numc) {
2807 $i = 0;
2808 while ($i < $numc) {
2809 $obj = $this->db->fetch_object($result);
2810
2811 if ($shortlist == 1) {
2812 $ga[$obj->cid] = $obj->ref;
2813 } elseif ($shortlist == 2) {
2814 $ga[$obj->cid] = $obj->ref.' ('.$obj->name.')';
2815 } else {
2816 $ga[$i]['id'] = $obj->cid;
2817 $ga[$i]['ref'] = $obj->ref;
2818 $ga[$i]['name'] = $obj->name;
2819 }
2820 $i++;
2821 }
2822 }
2823 return $ga;
2824 } else {
2825 dol_print_error($this->db);
2826 return -1;
2827 }
2828 }
2829
2837 public function availability($availability_id, $notrigger = 0)
2838 {
2839 global $user;
2840
2841 dol_syslog('Commande::availability('.$availability_id.')');
2842 if ($this->status >= self::STATUS_DRAFT) {
2843 $error = 0;
2844
2845 $this->db->begin();
2846
2847 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2848 $sql .= ' SET fk_availability = '.((int) $availability_id);
2849 $sql .= ' WHERE rowid='.((int) $this->id);
2850
2851 dol_syslog(__METHOD__, LOG_DEBUG);
2852 $resql = $this->db->query($sql);
2853 if (!$resql) {
2854 $this->errors[] = $this->db->error();
2855 $error++;
2856 }
2857
2858 if (!$error) {
2859 $this->oldcopy = clone $this;
2860 $this->availability_id = $availability_id;
2861 }
2862
2863 if (!$notrigger && empty($error)) {
2864 // Call trigger
2865 $result = $this->call_trigger('ORDER_MODIFY', $user);
2866 if ($result < 0) {
2867 $error++;
2868 }
2869 // End call triggers
2870 }
2871
2872 if (!$error) {
2873 $this->db->commit();
2874 return 1;
2875 } else {
2876 foreach ($this->errors as $errmsg) {
2877 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2878 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2879 }
2880 $this->db->rollback();
2881 return -1 * $error;
2882 }
2883 } else {
2884 $error_str = 'Command status do not meet requirement '.$this->status;
2885 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2886 $this->error = $error_str;
2887 $this->errors[] = $this->error;
2888 return -2;
2889 }
2890 }
2891
2892 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2900 public function demand_reason($demand_reason_id, $notrigger = 0)
2901 {
2902 // phpcs:enable
2903 global $user;
2904
2905 dol_syslog('Commande::demand_reason('.$demand_reason_id.')');
2906 if ($this->status >= self::STATUS_DRAFT) {
2907 $error = 0;
2908
2909 $this->db->begin();
2910
2911 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2912 $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
2913 $sql .= ' WHERE rowid='.((int) $this->id);
2914
2915 dol_syslog(__METHOD__, LOG_DEBUG);
2916 $resql = $this->db->query($sql);
2917 if (!$resql) {
2918 $this->errors[] = $this->db->error();
2919 $error++;
2920 }
2921
2922 if (!$error) {
2923 $this->oldcopy = clone $this;
2924 $this->demand_reason_id = $demand_reason_id;
2925 }
2926
2927 if (!$notrigger && empty($error)) {
2928 // Call trigger
2929 $result = $this->call_trigger('ORDER_MODIFY', $user);
2930 if ($result < 0) {
2931 $error++;
2932 }
2933 // End call triggers
2934 }
2935
2936 if (!$error) {
2937 $this->db->commit();
2938 return 1;
2939 } else {
2940 foreach ($this->errors as $errmsg) {
2941 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2942 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2943 }
2944 $this->db->rollback();
2945 return -1 * $error;
2946 }
2947 } else {
2948 $error_str = 'order status do not meet requirement '.$this->status;
2949 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2950 $this->error = $error_str;
2951 $this->errors[] = $this->error;
2952 return -2;
2953 }
2954 }
2955
2956 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2965 public function set_ref_client($user, $ref_client, $notrigger = 0)
2966 {
2967 // phpcs:enable
2968 if ($user->hasRight('commande', 'creer')) {
2969 $error = 0;
2970
2971 $this->db->begin();
2972
2973 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
2974 $sql .= ' ref_client = '.(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
2975 $sql .= ' WHERE rowid = '.((int) $this->id);
2976
2977 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
2978 $resql = $this->db->query($sql);
2979 if (!$resql) {
2980 $this->errors[] = $this->db->error();
2981 $error++;
2982 }
2983
2984 if (!$error) {
2985 $this->oldcopy = clone $this;
2986 $this->ref_client = $ref_client;
2987 $this->ref_customer = $ref_client;
2988 }
2989
2990 if (!$notrigger && empty($error)) {
2991 // Call trigger
2992 $result = $this->call_trigger('ORDER_MODIFY', $user);
2993 if ($result < 0) {
2994 $error++;
2995 }
2996 // End call triggers
2997 }
2998 if (!$error) {
2999 $this->db->commit();
3000 return 1;
3001 } else {
3002 foreach ($this->errors as $errmsg) {
3003 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3004 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3005 }
3006 $this->db->rollback();
3007 return -1 * $error;
3008 }
3009 } else {
3010 return -1;
3011 }
3012 }
3013
3021 public function classifyBilled(User $user, $notrigger = 0)
3022 {
3023 $error = 0;
3024
3025 if ($this->billed) {
3026 return 0;
3027 }
3028
3029 $this->db->begin();
3030
3031 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET facture = 1';
3032 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
3033
3034 dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
3035 if ($this->db->query($sql)) {
3036 $this->oldcopy = clone $this;
3037 $this->billed = 1;
3038
3039 if (!$notrigger && empty($error)) {
3040 // Call trigger
3041 $result = $this->call_trigger('ORDER_CLASSIFY_BILLED', $user);
3042 if ($result < 0) {
3043 $error++;
3044 }
3045 // End call triggers
3046 }
3047
3048 if (!$error) {
3049 $this->db->commit();
3050 return 1;
3051 } else {
3052 foreach ($this->errors as $errmsg) {
3053 dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR);
3054 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3055 }
3056 $this->db->rollback();
3057 return -1 * $error;
3058 }
3059 } else {
3060 $this->error = $this->db->error();
3061 $this->db->rollback();
3062 return -1;
3063 }
3064 }
3065
3073 public function classifyUnBilled(User $user, $notrigger = 0)
3074 {
3075 $error = 0;
3076
3077 $this->db->begin();
3078
3079 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET facture = 0';
3080 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
3081
3082 dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG);
3083 if ($this->db->query($sql)) {
3084 $this->oldcopy = clone $this;
3085 $this->billed = 1;
3086
3087 if (!$notrigger && empty($error)) {
3088 // Call trigger
3089 $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user);
3090 if ($result < 0) {
3091 $error++;
3092 }
3093 // End call triggers
3094 }
3095
3096 if (!$error) {
3097 $this->billed = 0;
3098
3099 $this->db->commit();
3100 return 1;
3101 } else {
3102 foreach ($this->errors as $errmsg) {
3103 dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR);
3104 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3105 }
3106 $this->db->rollback();
3107 return -1 * $error;
3108 }
3109 } else {
3110 $this->error = $this->db->error();
3111 $this->db->rollback();
3112 return -1;
3113 }
3114 }
3115
3116
3147 public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $price_base_type = 'HT', $info_bits = 0, $date_start = '', $date_end = '', $type = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = array(), $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '', $rang = 0)
3148 {
3149 global $mysoc, $langs, $user;
3150
3151 if (!$this->isLineOfObject($rowid)) {
3152 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
3153 return -1;
3154 }
3155
3156 dol_syslog(get_class($this)."::updateline id=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, date_start=$date_start, date_end=$date_end, type=$type, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, special_code=$special_code, ref_ext=$ref_ext");
3157 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3158
3159 if ($this->status == Commande::STATUS_DRAFT) {
3160 // Clean parameters
3161 if (empty($qty)) {
3162 $qty = 0;
3163 }
3164 if (empty($info_bits)) {
3165 $info_bits = 0;
3166 }
3167 if (empty($txtva)) {
3168 $txtva = 0;
3169 }
3170 if (empty($txlocaltax1)) {
3171 $txlocaltax1 = 0;
3172 }
3173 if (empty($txlocaltax2)) {
3174 $txlocaltax2 = 0;
3175 }
3176 if (empty($remise_percent)) {
3177 $remise_percent = 0;
3178 }
3179 if (empty($qty) && empty($special_code)) {
3180 $special_code = 3; // Set option tag
3181 }
3182 if (!empty($qty) && $special_code == 3) {
3183 $special_code = 0; // Remove option tag
3184 }
3185 if (empty($ref_ext)) {
3186 $ref_ext = '';
3187 }
3188
3189 if ($date_start && $date_end && $date_start > $date_end) {
3190 $langs->load("errors");
3191 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3192 return -1;
3193 }
3194
3195 $remise_percent = (float) price2num($remise_percent);
3196 $qty = (float) price2num($qty);
3197 $pu = price2num($pu);
3198 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
3199 $pu_ht_devise = price2num($pu_ht_devise);
3200 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
3201 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3202 }
3203 $txlocaltax1 = (float) price2num($txlocaltax1);
3204 $txlocaltax2 = (float) price2num($txlocaltax2);
3205
3206 $this->db->begin();
3207
3208 // Calcul du total TTC et de la TVA pour la ligne a partir de
3209 // qty, pu, remise_percent et txtva
3210 // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
3211 // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
3212
3213 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3214
3215 // Clean vat code
3216 $vat_src_code = '';
3217 $reg = array();
3218 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3219 $vat_src_code = $reg[1];
3220 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3221 }
3222
3223 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
3224 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
3225 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
3226 $tmpline = new OrderLine($this->db);
3227 if ($tmpline->fetch($rowid) > 0) {
3228 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
3229 if ($newqty != $qty) {
3230 $qty = $newqty;
3231 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
3232 }
3233 }
3234 }
3235
3236 $tabprice = calcul_price_total($qty, (float) $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, (float) $pu_ht_devise);
3237
3238 $total_ht = $tabprice[0];
3239 $total_tva = $tabprice[1];
3240 $total_ttc = $tabprice[2];
3241 $total_localtax1 = $tabprice[9];
3242 $total_localtax2 = $tabprice[10];
3243 $pu_ht = $tabprice[3];
3244 $pu_tva = $tabprice[4];
3245 $pu_ttc = $tabprice[5];
3246
3247 // MultiCurrency
3248 $multicurrency_total_ht = $tabprice[16];
3249 $multicurrency_total_tva = $tabprice[17];
3250 $multicurrency_total_ttc = $tabprice[18];
3251 $pu_ht_devise = $tabprice[19];
3252
3253 // Fetch current line from the database and then clone the object and set it in $oldline property
3254 $line = new OrderLine($this->db);
3255 $line->fetch($rowid);
3256 $line->fetch_optionals();
3257
3258 if (!empty($line->fk_product)) {
3259 $product = new Product($this->db);
3260 $result = $product->fetch($line->fk_product);
3261 $product_type = $product->type;
3262
3263 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_ORDER') && $product->isStockManaged()) {
3264 // get real stock
3265 $productChildrenNb = 0;
3266 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
3267 $productChildrenNb = $product->hasFatherOrChild(1);
3268 }
3269 if ($productChildrenNb > 0) {
3270 // compute real stock from each subcomponent
3271 $product_stock = null;
3272 $product->loadStockForVirtualProduct('warehouseopen', $qty);
3273 foreach ($product->stock_warehouse as $componentStockWarehouse) {
3274 if ($product_stock === null) {
3275 $product_stock = $componentStockWarehouse->real;
3276 } else {
3277 $product_stock = min($product_stock, $componentStockWarehouse->real);
3278 }
3279 }
3280 if ($product_stock === null) {
3281 $product_stock = 0;
3282 }
3283 } else {
3284 $product_stock = $product->stock_reel;
3285 }
3286
3287 if ($product_stock < $qty) {
3288 $langs->load("errors");
3289 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', (string) $product->ref);
3290 $this->errors[] = $this->error;
3291
3292 dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
3293
3294 $this->db->rollback();
3296 }
3297 }
3298 }
3299
3300 $staticline = clone $line;
3301
3302 $line->oldline = $staticline;
3303 $this->line = $line;
3304 $this->line->context = $this->context;
3305 $this->line->rang = $rang;
3306
3307 // Reorder if fk_parent_line change
3308 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
3309 $rangmax = $this->line_max($fk_parent_line);
3310 $this->line->rang = $rangmax + 1;
3311 }
3312
3313
3314 $this->line->id = $rowid;
3315 $this->line->label = $label;
3316 $this->line->desc = $desc;
3317 $this->line->qty = $qty;
3318 $this->line->ref_ext = $ref_ext;
3319
3320 $this->line->vat_src_code = $vat_src_code;
3321 $this->line->tva_tx = $txtva;
3322 $this->line->localtax1_tx = $txlocaltax1;
3323 $this->line->localtax2_tx = $txlocaltax2;
3324 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3325 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3326 $this->line->remise_percent = $remise_percent;
3327 $this->line->subprice = (float) $pu_ht;
3328 $this->line->info_bits = $info_bits;
3329 $this->line->special_code = $special_code;
3330 $this->line->total_ht = (float) $total_ht;
3331 $this->line->total_tva = (float) $total_tva;
3332 $this->line->total_localtax1 = (float) $total_localtax1;
3333 $this->line->total_localtax2 = (float) $total_localtax2;
3334 $this->line->total_ttc = (float) $total_ttc;
3335 $this->line->date_start = $date_start;
3336 $this->line->date_end = $date_end;
3337 $this->line->product_type = $type;
3338 $this->line->fk_parent_line = $fk_parent_line;
3339 $this->line->skip_update_total = $skip_update_total;
3340 $this->line->fk_unit = $fk_unit;
3341
3342 $this->line->fk_fournprice = $fk_fournprice;
3343 $this->line->pa_ht = $pa_ht;
3344
3345 // Multicurrency
3346 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
3347 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
3348 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
3349 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
3350
3351 if (is_array($array_options) && count($array_options) > 0) {
3352 // We replace values in this->line->array_options only for entries defined into $array_options
3353 foreach ($array_options as $key => $value) {
3354 $this->line->array_options[$key] = $array_options[$key];
3355 }
3356 }
3357
3358 $result = $this->line->update($user, $notrigger);
3359 if ($result > 0) {
3360 // Reorder if child line
3361 if (!empty($fk_parent_line)) {
3362 $this->line_order(true, 'DESC');
3363 }
3364
3365 // Mise a jour info denormalisees
3366 $this->update_price(1, 'auto');
3367
3368 $this->db->commit();
3369 return $result;
3370 } else {
3371 $this->setErrorsFromObject($this->line);
3372
3373 $this->db->rollback();
3374 return -1;
3375 }
3376 } else {
3377 $this->error = get_class($this)."::updateline Order status makes operation forbidden";
3378 $this->errors = array('OrderStatusMakeOperationForbidden');
3379 return -2;
3380 }
3381 }
3382
3390 public function update(User $user, $notrigger = 0)
3391 {
3392 $error = 0;
3393
3394 // Clean parameters
3395 if (isset($this->ref)) {
3396 $this->ref = trim($this->ref);
3397 }
3398 if (isset($this->ref_client)) {
3399 $this->ref_client = trim($this->ref_client);
3400 }
3401 if (isset($this->ref_customer)) {
3402 $this->ref_customer = trim($this->ref_customer);
3403 }
3404 if (isset($this->note) || isset($this->note_private)) {
3405 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
3406 }
3407 if (isset($this->note_public)) {
3408 $this->note_public = trim($this->note_public);
3409 }
3410 if (isset($this->model_pdf)) {
3411 $this->model_pdf = trim($this->model_pdf);
3412 }
3413 if (isset($this->import_key)) {
3414 $this->import_key = trim($this->import_key);
3415 }
3416 $delivery_date = $this->delivery_date;
3417
3418 // Check parameters
3419 // Put here code to add control on parameters values
3420
3421 // Update request
3422 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
3423
3424 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
3425 $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
3426 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
3427 $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
3428 $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
3429 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
3430 $sql .= " total_tva=".(isset($this->total_tva) ? (float) $this->total_tva : "null").",";
3431 $sql .= " localtax1=".(isset($this->total_localtax1) ? (float) $this->total_localtax1 : "null").",";
3432 $sql .= " localtax2=".(isset($this->total_localtax2) ? (float) $this->total_localtax2 : "null").",";
3433 $sql .= " total_ht=".(isset($this->total_ht) ? (float) $this->total_ht : "null").",";
3434 $sql .= " total_ttc=".(isset($this->total_ttc) ? (float) $this->total_ttc : "null").",";
3435 $sql .= " fk_statut=".(isset($this->status) ? (int) $this->status : "null").",";
3436 $sql .= " fk_user_modif=".(isset($user->id) ? (int) $user->id : "null").",";
3437 $sql .= " fk_user_valid=".((isset($this->user_validation_id) && $this->user_validation_id > 0) ? (int) $this->user_validation_id : "null").",";
3438 $sql .= " fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project : "null").",";
3439 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id : "null").",";
3440 $sql .= " deposit_percent=".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null").",";
3441 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
3442 $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').",";
3443 $sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? (int) $this->shipping_method_id : "null").",";
3444 $sql .= " fk_account=".($this->fk_account > 0 ? (int) $this->fk_account : "null").",";
3445 $sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id : "null").",";
3446 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
3447 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
3448 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
3449 $sql .= " fk_warehouse=".($this->warehouse_id > 0 ? (int) $this->warehouse_id : "null").",";
3450 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
3451 $sql .= " module_source = ".(isset($this->module_source) ? "'".$this->db->escape($this->module_source)."'" : "null").",";
3452 $sql .= " pos_source = ".(isset($this->pos_source) ? "'".$this->db->escape($this->pos_source)."'" : "null");
3453 $sql .= " WHERE rowid=".((int) $this->id);
3454
3455 $this->db->begin();
3456
3457 dol_syslog(get_class($this)."::update", LOG_DEBUG);
3458 $resql = $this->db->query($sql);
3459 if (!$resql) {
3460 $error++;
3461 $this->errors[] = "Error ".$this->db->lasterror();
3462 }
3463
3464 if (!$error) {
3465 $result = $this->insertExtraFields();
3466 if ($result < 0) {
3467 $error++;
3468 }
3469 }
3470
3471 if (!$error && !$notrigger) {
3472 // Call trigger
3473 $result = $this->call_trigger('ORDER_MODIFY', $user);
3474 if ($result < 0) {
3475 $error++;
3476 }
3477 // End call triggers
3478 }
3479
3480 // Commit or rollback
3481 if ($error) {
3482 foreach ($this->errors as $errmsg) {
3483 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
3484 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3485 }
3486 $this->db->rollback();
3487 return -1 * $error;
3488 } else {
3489 $this->db->commit();
3490 return 1;
3491 }
3492 }
3493
3501 public function delete($user, $notrigger = 0)
3502 {
3503 global $conf, $langs;
3504 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3505
3506 $error = 0;
3507
3508 dol_syslog(get_class($this)."::delete ".$this->id, LOG_DEBUG);
3509
3510 $this->db->begin();
3511
3512 if (!$notrigger) {
3513 // Call trigger
3514 $result = $this->call_trigger('ORDER_DELETE', $user);
3515 if ($result < 0) {
3516 $error++;
3517 }
3518 // End call triggers
3519 }
3520
3521 // Test we can delete
3522 if ($this->countNbOfShipments() != 0) {
3523 $this->errors[] = $langs->trans('SomeShipmentExists');
3524 $error++;
3525 }
3526
3527 // Remove linked categories.
3528 if (!$error) {
3529 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_order";
3530 $sql .= " WHERE fk_order = ".((int) $this->id);
3531
3532 $result = $this->db->query($sql);
3533 if (!$result) {
3534 $error++;
3535 $this->errors[] = $this->db->lasterror();
3536 }
3537 }
3538
3539 // Delete extrafields of lines and lines
3540 if (!$error && !empty($this->table_element_line)) {
3541 $tabletodelete = $this->table_element_line;
3542 $sqlef = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete."_extrafields WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id).")";
3543 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
3544 if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
3545 $error++;
3546 $this->error = $this->db->lasterror();
3547 $this->errors[] = $this->error;
3548 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3549 }
3550 }
3551
3552 if (!$error) {
3553 // Delete linked object
3554 $res = $this->deleteObjectLinked();
3555 if ($res < 0) {
3556 $error++;
3557 }
3558 }
3559
3560 if (!$error) {
3561 // Delete linked contacts
3562 $res = $this->delete_linked_contact();
3563 if ($res < 0) {
3564 $error++;
3565 }
3566 }
3567
3568 // Removed extrafields of object
3569 if (!$error) {
3570 $result = $this->deleteExtraFields();
3571 if ($result < 0) {
3572 $error++;
3573 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3574 }
3575 }
3576
3577 // Delete main record
3578 if (!$error) {
3579 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
3580 $res = $this->db->query($sql);
3581 if (!$res) {
3582 $error++;
3583 $this->error = $this->db->lasterror();
3584 $this->errors[] = $this->error;
3585 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3586 }
3587 }
3588
3589 // Delete record into ECM index and physically
3590 if (!$error) {
3591 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive, old method.
3592 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3593 if (!$res) {
3594 $error++;
3595 }
3596 }
3597
3598 if (!$error) {
3599 // We remove directory
3600 $ref = dol_sanitizeFileName($this->ref);
3601 if ($conf->commande->multidir_output[$this->entity] && !empty($this->ref)) {
3602 $dir = $conf->commande->multidir_output[$this->entity]."/".$ref;
3603 $file = $dir."/".$ref.".pdf";
3604 if (file_exists($file)) {
3605 dol_delete_preview($this);
3606
3607 if (!dol_delete_file($file, 0, 0, 0, $this)) {
3608 $this->error = 'ErrorFailToDeleteFile';
3609 $this->errors[] = $this->error;
3610 $this->db->rollback();
3611 return 0;
3612 }
3613 }
3614 if (file_exists($dir)) {
3615 $res = @dol_delete_dir_recursive($dir);
3616 if (!$res) {
3617 $this->error = 'ErrorFailToDeleteDir';
3618 $this->errors[] = $this->error;
3619 $this->db->rollback();
3620 return 0;
3621 }
3622 }
3623 }
3624 }
3625
3626 if (!$error) {
3627 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
3628 $this->db->commit();
3629 return 1;
3630 } else {
3631 $this->db->rollback();
3632 return -1;
3633 }
3634 }
3635
3636
3637 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3645 public function load_board($user, $mode)
3646 {
3647 // phpcs:enable
3648 global $conf, $langs, $hookmanager;
3649
3650 $clause = " WHERE";
3651
3652 $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut, c.total_ht";
3653 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
3654 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3655 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
3656 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3657 $clause = " AND";
3658 }
3659 $sql .= $clause." c.entity IN (".getEntity('commande').")";
3660 //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
3661 if ($mode == 'toship') {
3662 // An order to ship is an open order (validated or in progress)
3663 $sql .= " AND c.fk_statut IN (" . self::STATUS_VALIDATED . "," . self::STATUS_SHIPMENTONPROCESS . ")";
3664 }
3665 if ($mode == 'tobill') {
3666 // An order to bill is an order not already billed
3667 $sql .= " AND c.fk_statut IN (" . self::STATUS_VALIDATED . "," . self::STATUS_SHIPMENTONPROCESS . ", " . self::STATUS_CLOSED . ") AND c.facture = 0";
3668 }
3669 if ($mode == 'shippedtobill') {
3670 // An order shipped and to bill is a delivered order not already billed
3671 $sql .= " AND c.fk_statut IN (" . self::STATUS_CLOSED . ") AND c.facture = 0";
3672 }
3673 if ($user->socid) {
3674 $sql .= " AND c.fk_soc = ".((int) $user->socid);
3675 }
3676 // Add where from hooks
3677 $parameters = array('socid' => $user->socid);
3678 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3679 $sql .= $hookmanager->resPrint;
3680 $resql = $this->db->query($sql);
3681 if ($resql) {
3682 $delay_warning = 0;
3683 $label = $labelShort = $url = '';
3684 if ($mode == 'toship') {
3685 $delay_warning = $conf->commande->client->warning_delay / 60 / 60 / 24;
3686 $url = DOL_URL_ROOT.'/commande/list.php?search_status=-2&mainmenu=commercial&leftmenu=orders';
3687 $label = $langs->transnoentitiesnoconv("OrdersToProcess");
3688 $labelShort = $langs->transnoentitiesnoconv("Opened");
3689 }
3690 if ($mode == 'tobill') {
3691 $url = DOL_URL_ROOT.'/commande/list.php?search_status=-3&search_billed=0&mainmenu=commercial&leftmenu=orders';
3692 $label = $langs->trans("OrdersToBill"); // We set here bill but may be billed or ordered
3693 $labelShort = $langs->trans("ToBill");
3694 }
3695 if ($mode == 'shippedtobill') {
3696 $url = DOL_URL_ROOT.'/commande/list.php?search_status=3&search_billed=0&mainmenu=commercial&leftmenu=orders';
3697 $label = $langs->trans("OrdersToBill"); // We set here bill but may be billed or ordered
3698 $labelShort = $langs->trans("StatusOrderDelivered").' '.$langs->trans("and").' '.$langs->trans("ToBill");
3699 }
3700
3701 $response = new WorkboardResponse();
3702
3703 $response->warning_delay = $delay_warning;
3704 $response->label = $label;
3705 $response->labelShort = $labelShort;
3706 $response->url = $url;
3707 $response->url_late = DOL_URL_ROOT.'/commande/list.php?search_option=late&mainmenu=commercial&leftmenu=orders';
3708 $response->img = img_object('', "order");
3709
3710 $generic_commande = new Commande($this->db);
3711
3712 while ($obj = $this->db->fetch_object($resql)) {
3713 $response->nbtodo++;
3714 $response->total += $obj->total_ht;
3715
3716 $generic_commande->status = $obj->fk_statut;
3717 $generic_commande->date = $this->db->jdate($obj->date_commande);
3718 $generic_commande->delivery_date = $this->db->jdate($obj->delivery_date);
3719
3720 if ($mode == 'toship' && $generic_commande->hasDelay()) {
3721 $response->nbtodolate++;
3722 }
3723 }
3724
3725 return $response;
3726 } else {
3727 $this->error = $this->db->error();
3728 return -1;
3729 }
3730 }
3731
3737 public function getLabelSource()
3738 {
3739 global $langs;
3740
3741 $label = $langs->trans('OrderSource'.$this->source);
3742
3743 if ($label == 'OrderSource') {
3744 return '';
3745 }
3746 return $label;
3747 }
3748
3755 public function getLibStatut($mode)
3756 {
3757 return $this->LibStatut($this->status, $this->billed, $mode);
3758 }
3759
3760 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3770 public function LibStatut($status, $billed, $mode, $donotshowbilled = 0)
3771 {
3772 // phpcs:enable
3773 global $langs, $hookmanager;
3774
3775 $billedtext = '';
3776 if (empty($donotshowbilled)) {
3777 $billedtext .= ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : '');
3778 }
3779 $billedtextlong = ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : '');
3780
3781 $labelTooltip = '';
3782
3783 $paramsBadge = array('badgeParams' => array('attr' => array(
3784 'data-status-element' => $this->element,
3785 'data-billed' => (int) $billed,
3786 'data-status' => (int) $status
3787 )));
3788
3789 if ($status == self::STATUS_CANCELED) {
3790 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderCanceled');
3791 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderCanceledShort');
3792 $statusType = 'status9';
3793 } elseif ($status == self::STATUS_DRAFT) {
3794 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderDraft');
3795 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderDraftShort');
3796 $statusType = 'status0';
3797 } elseif ($status == self::STATUS_VALIDATED) {
3798 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderValidated').$billedtextlong;
3799 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderValidatedShort').$billedtext;
3800 $statusType = 'status1';
3801 } elseif ($status == self::STATUS_SHIPMENTONPROCESS) {
3802 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderSent').$billedtextlong;
3803 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderSentShort').$billedtext;
3804 $labelTooltip = $langs->transnoentitiesnoconv("StatusOrderSent");
3805 if (!empty($this->delivery_date)) {
3806 $labelTooltip .= ' - '.$langs->transnoentitiesnoconv("DateDeliveryPlanned").dol_print_date($this->delivery_date, 'day').$billedtext;
3807 }
3808 $statusType = 'status4';
3809 } elseif ($status == self::STATUS_CLOSED) {
3810 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderDelivered').$billedtextlong;
3811 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderDeliveredShort').$billedtext;
3812 $statusType = 'status6';
3813 } else {
3814 $labelStatus = $langs->transnoentitiesnoconv('Unknown');
3815 $labelStatusShort = '';
3816 $statusType = '';
3817 $mode = 0;
3818 }
3819
3820 $paramsBadge['tooltip'] = $labelTooltip;
3821
3822 $parameters = array(
3823 'status' => $status,
3824 'mode' => $mode,
3825 'billed' => $billed,
3826 'donotshowbilled' => $donotshowbilled,
3827 'paramsBadge' => & $paramsBadge
3828 );
3829
3830 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
3831
3832 if ($reshook > 0) {
3833 return $hookmanager->resPrint;
3834 }
3835
3836 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $paramsBadge);
3837 }
3838
3846 public function getTooltipContentArray($params)
3847 {
3848 global $conf, $langs, $user;
3849
3850 $langs->load('orders');
3851 $datas = [];
3852 $nofetch = !empty($params['nofetch']);
3853
3854 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3855 return ['optimize' => $langs->trans("Order")];
3856 }
3857
3858 if ($user->hasRight('commande', 'lire')) {
3859 $datas['picto'] = img_picto('', $this->picto, '', 0, 0, 0, '', 'paddingrightonly').'<u>'.$langs->trans("Order").'</u>';
3860 if (isset($this->status)) {
3861 $datas['status'] = ' '.$this->getLibStatut(5);
3862 }
3863 $datas['Ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3864 if (!$nofetch) {
3865 $langs->load('companies');
3866 if (empty($this->thirdparty)) {
3867 $this->fetch_thirdparty();
3868 }
3869 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
3870 }
3871 $datas['RefCustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.(empty($this->ref_customer) ? (empty($this->ref_client) ? '' : $this->ref_client) : $this->ref_customer);
3872 if (!$nofetch) {
3873 $langs->load('project');
3874 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
3875 $res = $this->fetchProject();
3876 if ($res > 0 && $this->project instanceof Project) {
3877 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
3878 }
3879 }
3880 }
3881 if (!empty($this->total_ht)) {
3882 $datas['AmountHT'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3883 }
3884 if (!empty($this->total_tva)) {
3885 $datas['VAT'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3886 }
3887 if (!empty($this->total_ttc)) {
3888 $datas['AmountTTC'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3889 }
3890 if (!empty($this->date)) {
3891 $datas['Date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
3892 }
3893 if (!empty($this->delivery_date)) {
3894 $datas['DeliveryDate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
3895 }
3896 }
3897
3898 return $datas;
3899 }
3900
3914 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0, $target = '')
3915 {
3916 global $conf, $langs, $user, $hookmanager;
3917
3918 if (!empty($conf->dol_no_mouse_hover)) {
3919 $notooltip = 1; // Force disable tooltips
3920 }
3921
3922 $result = '';
3923
3924 if (isModEnabled("shipping") && ($option == '1' || $option == '2')) {
3925 $baseurl = DOL_URL_ROOT . '/expedition/shipment.php';
3926 } else {
3927 $baseurl = DOL_URL_ROOT . '/commande/card.php';
3928 }
3929 $query = ['id' => $this->id];
3930 if (!$user->hasRight('commande', 'lire')) {
3931 $option = 'nolink';
3932 }
3933
3934 if ($option !== 'nolink') {
3935 // Add param to save lastsearch_values or not
3936 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3937 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3938 $add_save_lastsearch_values = 1;
3939 }
3940 if ($add_save_lastsearch_values) {
3941 $query = array_merge($query, ['save_lastsearch_values' => 1]);
3942 }
3943 }
3944 $url = dolBuildUrl($baseurl, $query);
3945
3946 if ($short) {
3947 return $url;
3948 }
3949 $params = [
3950 'id' => $this->id,
3951 'objecttype' => $this->element,
3952 'option' => $option,
3953 'nofetch' => 1,
3954 ];
3955 $classfortooltip = 'classfortooltip';
3956 $dataparams = '';
3957 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3958 $classfortooltip = 'classforajaxtooltip';
3959 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
3960 $label = '';
3961 } else {
3962 $label = implode($this->getTooltipContentArray($params));
3963 }
3964
3965 $linkclose = '';
3966 if (empty($notooltip) && $user->hasRight('commande', 'lire')) {
3967 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3968 $label = $langs->trans("Order");
3969 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
3970 }
3971 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
3972 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
3973
3974 $target_value = array('_self', '_blank', '_parent', '_top');
3975 if (in_array($target, $target_value)) {
3976 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
3977 }
3978 }
3979
3980 $linkstart = '<a href="'.$url.'"';
3981 $linkstart .= $linkclose.'>';
3982 $linkend = '</a>';
3983
3984 if ($option === 'nolink') {
3985 $linkstart = '';
3986 $linkend = '';
3987 }
3988
3989 $result .= $linkstart;
3990 if ($withpicto) {
3991 $result .= img_object(($notooltip ? '' : $label), $this->picto, (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
3992 }
3993 if ($withpicto != 2) {
3994 $result .= $this->ref;
3995 }
3996 $result .= $linkend;
3997
3998 if ($addlinktonotes) {
3999 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
4000 if ($txttoshow) {
4001 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
4002 $result .= ' <span class="note inline-block">';
4003 $result .= '<a href="'.DOL_URL_ROOT.'/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
4004 $result .= img_picto('', 'note');
4005 $result .= '</a>';
4006 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
4007 //$result.='</a>';
4008 $result .= '</span>';
4009 }
4010 }
4011
4012 global $action;
4013 $hookmanager->initHooks(array($this->element . 'dao'));
4014 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
4015 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4016 if ($reshook > 0) {
4017 $result = $hookmanager->resPrint;
4018 } else {
4019 $result .= $hookmanager->resPrint;
4020 }
4021 return $result;
4022 }
4023
4024
4031 public function info($id)
4032 {
4033 $sql = 'SELECT c.rowid, date_creation as datec, tms as datem,';
4034 $sql .= ' date_valid as datev,';
4035 $sql .= ' date_cloture as datecloture,';
4036 $sql .= ' fk_user_author, fk_user_valid, fk_user_cloture';
4037 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as c';
4038 $sql .= ' WHERE c.rowid = '.((int) $id);
4039 $result = $this->db->query($sql);
4040 if ($result) {
4041 if ($this->db->num_rows($result)) {
4042 $obj = $this->db->fetch_object($result);
4043 $this->id = $obj->rowid;
4044 if ($obj->fk_user_author) {
4045 $this->user_creation_id = $obj->fk_user_author;
4046 }
4047 if ($obj->fk_user_valid) {
4048 $this->user_validation_id = $obj->fk_user_valid;
4049 }
4050 if ($obj->fk_user_cloture) {
4051 $this->user_closing_id = $obj->fk_user_cloture;
4052 }
4053
4054 $this->date_creation = $this->db->jdate($obj->datec);
4055 $this->date_modification = $this->db->jdate($obj->datem);
4056 $this->date_validation = $this->db->jdate($obj->datev);
4057 $this->date_cloture = $this->db->jdate($obj->datecloture);
4058 }
4059
4060 $this->db->free($result);
4061 } else {
4062 dol_print_error($this->db);
4063 }
4064 }
4065
4066
4075 public function initAsSpecimen($param = array())
4076 {
4077 global $conf, $langs;
4078
4079 dol_syslog(get_class($this)."::initAsSpecimen");
4080
4081 // Load array of products prodids
4082 $num_prods = 0;
4083 $prodids = array();
4084 $sql = "SELECT rowid";
4085 $sql .= " FROM ".MAIN_DB_PREFIX."product";
4086 $sql .= " WHERE entity IN (".getEntity('product').")";
4087 if (array_key_exists('tosell', $param)) {
4088 $sql .= " AND tosell = ".((int) $param['tosell']);
4089 }
4090 $sql .= $this->db->plimit(100);
4091
4092 $resql = $this->db->query($sql);
4093 if ($resql) {
4094 $num_prods = $this->db->num_rows($resql);
4095 $i = 0;
4096 while ($i < $num_prods) {
4097 $i++;
4098 $row = $this->db->fetch_row($resql);
4099 $prodids[$i] = $row[0];
4100 }
4101 }
4102
4103 // Initialise parameters
4104 $this->id = 0;
4105 $this->ref = 'SPECIMEN';
4106 $this->specimen = 1;
4107 $this->entity = $conf->entity;
4108 $this->socid = 1;
4109 $this->date = time();
4110 $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
4111 $this->cond_reglement_code = 'RECEP';
4112 $this->mode_reglement_code = 'CHQ';
4113 $this->availability_code = 'DSP';
4114 $this->demand_reason_code = 'SRC_00';
4115
4116 $this->note_public = 'This is a comment (public)';
4117 $this->note_private = 'This is a comment (private)';
4118
4119 $this->multicurrency_tx = 1;
4120 $this->multicurrency_code = $conf->currency;
4121
4122 $this->status = $this::STATUS_DRAFT;
4123
4124 // Lines
4125 $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)
4126 $xnbp = 0;
4127
4128 while ($xnbp < $nbp) {
4129 $line = new OrderLine($this->db);
4130
4131 $line->desc = $langs->trans("Description")." ".$xnbp;
4132 $line->qty = 1;
4133 $line->subprice = 100;
4134 $line->price = 100;
4135 $line->tva_tx = 20;
4136 if ($xnbp == 2) {
4137 $line->total_ht = 50;
4138 $line->total_ttc = 60;
4139 $line->total_tva = 10;
4140 $line->remise_percent = 50;
4141 } else {
4142 $line->total_ht = 100;
4143 $line->total_ttc = 120;
4144 $line->total_tva = 20;
4145 $line->remise_percent = 0;
4146 }
4147 if ($num_prods > 0) {
4148 $prodid = mt_rand(1, $num_prods);
4149 $line->fk_product = $prodids[$prodid];
4150 $line->product_ref = 'SPECIMEN';
4151 }
4152
4153 $this->lines[$xnbp] = $line;
4154
4155 $this->total_ht += $line->total_ht;
4156 $this->total_tva += $line->total_tva;
4157 $this->total_ttc += $line->total_ttc;
4158
4159 $xnbp++;
4160 }
4161
4162 return 1;
4163 }
4164
4165
4171 public function loadStateBoard()
4172 {
4173 global $user, $hookmanager;
4174
4175 $this->nb = array();
4176 $clause = "WHERE";
4177
4178 $sql = "SELECT count(c.rowid) as nb";
4179 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
4180 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
4181 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
4182 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4183 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
4184 $clause = "AND";
4185 }
4186 $sql .= " ".$clause." c.entity IN (".getEntity('commande').")";
4187 // Add where from hooks
4188 $parameters = array();
4189 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
4190 $sql .= $hookmanager->resPrint;
4191 $resql = $this->db->query($sql);
4192 if ($resql) {
4193 while ($obj = $this->db->fetch_object($resql)) {
4194 $this->nb["orders"] = $obj->nb;
4195 }
4196 $this->db->free($resql);
4197 return 1;
4198 } else {
4199 dol_print_error($this->db);
4200 $this->error = $this->db->error();
4201 return -1;
4202 }
4203 }
4204
4210 public function getLinesArray()
4211 {
4212 return $this->fetch_lines();
4213 }
4214
4226 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4227 {
4228 global $langs;
4229
4230 $langs->load("orders");
4231 $outputlangs->load("products");
4232
4233 if (!dol_strlen($modele)) {
4234 $modele = 'einstein';
4235
4236 if (!empty($this->model_pdf)) {
4237 $modele = $this->model_pdf;
4238 } elseif (getDolGlobalString('COMMANDE_ADDON_PDF')) {
4239 $modele = getDolGlobalString('COMMANDE_ADDON_PDF');
4240 }
4241 }
4242
4243 $modelpath = "core/modules/commande/doc/";
4244
4245 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4246 }
4247
4248
4257 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4258 {
4259 $tables = array(
4260 'commande'
4261 );
4262
4263 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4264 }
4265
4274 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
4275 {
4276 $tables = array(
4277 'commandedet',
4278 );
4279
4280 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
4281 }
4282
4288 public function hasDelay()
4289 {
4290 global $conf;
4291
4292 if (!($this->status > Commande::STATUS_DRAFT && $this->status < Commande::STATUS_CLOSED)) {
4293 return false; // Never late if not inside this status range
4294 }
4295
4296 $now = dol_now();
4297
4298 return max($this->date, $this->delivery_date) < ($now - $conf->commande->client->warning_delay);
4299 }
4300
4306 public function showDelay()
4307 {
4308 global $conf, $langs;
4309
4310 if (empty($this->delivery_date)) {
4311 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date, 'day');
4312 } else {
4313 $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->delivery_date, 'day');
4314 }
4315 $text .= ' '.($conf->commande->client->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->client->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
4316
4317 return $text;
4318 }
4319
4329 public function setSignedStatus(User $user, int $status = 0, int $notrigger = 0, $triggercode = ''): int
4330 {
4331 return $this->setSignedStatusCommon($user, $status, $notrigger, $triggercode);
4332 }
4333}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
Class to manage customers orders.
getNbOfServicesLines()
Return number of line with type service.
getNbOfShipments()
Count number of shipments for this order.
createFromProposal($object, User $user)
Load an object from a proposal and create a new order into database.
setDraft($user, $idwarehouse=-1)
Set draft status.
setDeliveryDate($user, $delivery_date, $notrigger=0)
Set the planned delivery date.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
getLinesArray()
Create an array of order lines.
showDelay()
Show the customer delayed info.
set_date($user, $date, $notrigger=0)
Set the order date.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
loadStateBoard()
Load the indicators this->nb for the state board.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load array lines.
createFromClone(User $user, $socid=0)
Load an object from its id and create a new one in database.
const STATUS_SHIPMENTONPROCESS
Shipment on process.
LibStatut($status, $billed, $mode, $donotshowbilled=0)
Return label of status.
getLibStatut($mode)
Return status label of Order.
hasDelay()
Is the sales order delayed?
const STATUS_CLOSED
Closed (Sent, billed or not)
valid($user, $idwarehouse=0, $notrigger=0)
Validate order.
getLabelSource()
Return source label of order.
set_remise($user, $remise, $notrigger=0)
Applique une remise relative.
initAsSpecimen($param=array())
Initialise an instance with random values.
const STATUS_CANCELED
Canceled status.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=0, $target='')
Return clickable link of object (with eventually picto)
loadExpeditions($filtre_statut=-1, $fk_product=0)
Load array this->expeditions of lines of shipments with nb of products sent for each order line Note:...
__construct($db)
Constructor.
availability($availability_id, $notrigger=0)
Update delivery delay.
set_reopen($user)
Tag the order as validated (opened) Function used when order is reopend after being closed.
set_ref_client($user, $ref_client, $notrigger=0)
Set customer ref.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $date_start='', $date_end='', $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=array(), $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0, $ref_ext='', $noupdateafterinsertline=0)
Add an order line into database (linked to product/service or not)
getTooltipContentArray($params)
getTooltipContentArray
create($user, $notrigger=0)
Create sale order Note that this->ref can be set or empty.
demand_reason($demand_reason_id, $notrigger=0)
Update order demand_reason.
const STATUS_DRAFT
Draft status.
const STOCK_NOT_ENOUGH_FOR_ORDER
ERR Not enough stock.
insert_discount($idremise)
Add a discount line into a sale order (as a sale order line) using an existing absolute discount (Con...
getNbOfProductsLines()
Return number of line with type product.
update(User $user, $notrigger=0)
Update database.
classifyUnBilled(User $user, $notrigger=0)
Classify the order as not invoiced.
setDiscount($user, $remise, $notrigger=0)
Set a percentage discount.
setCategories($categories)
Sets object to given categories.
const STATUS_ACCEPTED
For backward compatibility.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $price_base_type='HT', $info_bits=0, $date_start='', $date_end='', $type=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=array(), $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a line in database.
classifyBilled(User $user, $notrigger=0)
Classify the order as invoiced.
info($id)
Charge les information d'ordre info dans l'objet commande.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
const STATUS_VALIDATED
Validated status.
deleteLine($user=null, $lineid=0, $id=0)
Delete an order line.
countNbOfShipments()
Returns an array with expeditions lines number.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='c.date_commande', $sortorder='DESC')
Return list of orders (eventuelly filtered on a user) into an array.
fetch($id, $ref='', $ref_ext='', $notused='')
Get object from database.
cloture($user, $notrigger=0, $checkpermission=1)
Close order.
set_date_livraison($user, $delivery_date, $notrigger=0)
Set delivery date.
add_product($idproduct, $qty, $remise_percent=0.0, $date_start='', $date_end='')
Add line into array $this->client must be loaded.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setSignedStatus(User $user, int $status=0, int $notrigger=0, $triggercode='')
Set signed status.
cancel($user, $idwarehouse=-1)
Cancel an order If stock is decremented on order validation, we must reincrement it.
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...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
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.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
updateRangOfLine($rowid, $rang)
Update position of line (rang)
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
deleteExtraFields()
Delete all extra fields values for the current object.
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Superclass for orders classes.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage standard extra fields.
Class to manage stock movements.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage order lines.
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
setSignedStatusCommon(User $user, int $status, int $notrigger=0, string $triggercode='')
Set signed status & call trigger with context message.
global $mysoc
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:64
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_now($mode='gmt')
Return date for now.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
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.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
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)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
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.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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).
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
getMarginInfos($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
if(getDolGlobalString( 'TAKEPOS_SHOW_CUSTOMER')) print $langs trans('Date')." left 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 PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:469