dolibarr 25.0.0-alpha
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-2026 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 Vincent de Grandpré <vincent@de-grandpre.quebec>
19 * Copyright (C) 2026 Lionel Vessiller <lvessiller@open-dsi.fr>
20 * Copyright (C) 2026 Nick Fragoulis
21 *
22 * This program is free software; you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation; either version 3 of the License, or
25 * (at your option) any later version.
26 *
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
31 *
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <https://www.gnu.org/licenses/>.
34 */
35
42require_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
43require_once DOL_DOCUMENT_ROOT.'/commande/class/orderline.class.php';
44require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
45require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
46require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
47require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
48require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
49
50
54class Commande extends CommonOrder
55{
56 use CommonSubtotal;
57
61 public $element = 'commande';
62
67 public $TRIGGER_PREFIX = 'ORDER';
68
72 public $table_element = 'commande';
73
77 public $table_element_line = 'commandedet';
78
82 public $class_element_line = 'OrderLine';
83
87 public $fk_element = 'fk_commande';
88
92 public $picto = 'order';
93
98 public $restrictiononfksoc = 1;
99
103 protected $table_ref_field = 'ref';
104
108 public $ref;
109
113 public $socid;
114
118 public $ref_client;
119
123 public $ref_customer;
124
128 public $contactid;
129
135 public $statut;
136
141 public $status;
142
146 public $billed;
147
151 public $date_lim_reglement;
155 public $cond_reglement_code;
156
160 public $cond_reglement_doc;
161
165 public $cond_reglement_label;
166
171 public $deposit_percent;
172
176 public $fk_account;
177
181 public $mode_reglement;
182
186 public $mode_reglement_id;
187
191 public $mode_reglement_code;
192
197 public $availability_id;
198
203 public $availability_code;
204
209 public $availability;
210
214 public $demand_reason_id;
215
219 public $demand_reason_code;
220
224 public $date;
225
231 public $date_commande;
232
236 public $delivery_date;
237
241 public $fk_remise_except;
242
247 public $remise_percent;
248
252 public $source;
253
258 public $signed_status = 0;
259
263 public $warehouse_id;
264
268 public $extraparams = array();
269
273 public $user_author_id;
274
278 public $line;
279
283 public $lines = array();
284
285
289 public $module_source;
293 public $pos_source;
294
298 public $expeditions;
299
303 public $online_payment_url;
304
305
306
332 // BEGIN MODULEBUILDER PROPERTIES
336 public $fields = array(
337 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
338 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20, 'index' => 1),
339 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 25),
340 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 26),
341 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 28, 'uieditable' => 1, 'alwayseditable' => 1),
342 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 20),
343 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 25),
344 'date_commande' => array('type' => 'date', 'label' => 'Date', 'enabled' => 1, 'visible' => 1, 'position' => 60, 'csslist' => 'nowraponall'),
345 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 62, 'csslist' => 'nowraponall'),
346 'date_cloture' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 65, 'csslist' => 'nowraponall'),
347 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 85),
348 'fk_user_cloture' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => -1, 'position' => 90),
349 'source' => array('type' => 'smallint(6)', 'label' => 'Source', 'enabled' => 1, 'visible' => -1, 'position' => 95),
350 'total_tva' => array('type' => 'double(24,8)', 'label' => 'VAT', 'enabled' => 1, 'visible' => -1, 'position' => 125, 'isameasure' => 1),
351 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LocalTax1', 'enabled' => 1, 'visible' => -1, 'position' => 130, 'isameasure' => 1),
352 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LocalTax2', 'enabled' => 1, 'visible' => -1, 'position' => 135, 'isameasure' => 1),
353 'total_ht' => array('type' => 'double(24,8)', 'label' => 'TotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 140, 'isameasure' => 1),
354 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'TotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 145, 'isameasure' => 1),
355 'signed_status' => array('type' => 'smallint(6)', 'label' => 'SignedStatus', 'enabled' => 1, 'visible' => -1, 'position' => 146, 'arrayofkeyval' => array(0 => 'NoSignature', 1 => 'SignedSender', 2 => 'SignedReceiver', 9 => 'SignedAll')),
356 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 150, 'uieditable' => 1, 'alwayseditable' => 1),
357 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 155, 'uieditable' => 1, 'alwayseditable' => 1),
358 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'PDFTemplate', 'enabled' => 1, 'visible' => 0, 'position' => 160),
359 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 170),
360 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'MulticurrencyID', 'enabled' => 1, 'visible' => -1, 'position' => 175),
361 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'position' => 180),
362 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 181),
363 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 185),
364 'date_livraison' => array('type' => 'date', 'label' => 'DateDeliveryPlanned', 'enabled' => 1, 'visible' => -1, 'position' => 190, 'csslist' => 'nowraponall'),
365 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMethod', 'enabled' => 1, 'visible' => -1, 'position' => 195),
366 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'DefaultWarehouse', 'enabled' => 'isModEnabled("stock")', 'visible' => -1, 'position' => 200, 'nodepth' => 1),
367 'fk_availability' => array('type' => 'integer', 'label' => 'Availability', 'enabled' => 1, 'visible' => -1, 'position' => 205),
368 'fk_input_reason' => array('type' => 'integer', 'label' => 'InputReason', 'enabled' => 1, 'visible' => -1, 'position' => 210),
369 //'fk_delivery_address' =>array('type'=>'integer', 'label'=>'DeliveryAddress', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
370 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 225),
371 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 230),
372 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 235),
373 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Currency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240),
374 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'MulticurrencyCurrency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 245),
375 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 250, 'isameasure' => 1),
376 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 255, 'isameasure' => 1),
377 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 260, 'isameasure' => 1),
378 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 265, 'isameasure' => 1),
379 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
380 'module_source' => array('type' => 'varchar(32)', 'label' => 'POSModule', 'enabled' => 1, 'visible' => -1, 'position' => 275),
381 'pos_source' => array('type' => 'varchar(32)', 'label' => 'POSTerminal', 'enabled' => 1, 'visible' => -1, 'position' => 280),
382 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 300),
383 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 302),
384 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -2, 'position' => 304, 'csslist' => 'nowraponall'),
385 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 306),
386 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 400),
387 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
388 );
389 // END MODULEBUILDER PROPERTIES
390
395
399 const STATUS_CANCELED = -1;
403 const STATUS_DRAFT = 0;
411 const STATUS_SHIPMENTONPROCESS = 2; // We set this status when a shipment is validated
412
418
422 const STATUS_CLOSED = 3;
423
424 /*
425 * No signature
426 */
427 const STATUS_NO_SIGNATURE = 0;
428
429 /*
430 * Signed by sender
431 */
432 const STATUS_SIGNED_SENDER = 1;
433
434 /*
435 * Signed by receiver
436 */
437 const STATUS_SIGNED_RECEIVER = 2;
438
439 /*
440 * Signed by all
441 */
442 const STATUS_SIGNED_ALL = 9; // To handle future kind of signature (ex: tripartite contract)
443
444
450 public function __construct($db)
451 {
452 $this->db = $db;
453
454 $this->ismultientitymanaged = 1;
455 $this->isextrafieldmanaged = 1;
456
457 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
458 }
459
468 protected function persistFieldValue(User $user, $field)
469 {
470 if ($field == 'ref_client') {
471 return $this->set_ref_client($user, (string) $this->ref_client);
472 }
473
474 return parent::persistFieldValue($user, $field);
475 }
476
484 public function getNextNumRef($soc)
485 {
486 global $langs, $conf;
487 $langs->load("order");
488
489 if (getDolGlobalString('COMMANDE_ADDON')) {
490 $mybool = false;
491
492 $file = getDolGlobalString('COMMANDE_ADDON') . ".php";
493 $classname = getDolGlobalString('COMMANDE_ADDON');
494
495 // Include file with class
496 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
497 foreach ($dirmodels as $reldir) {
498 $dir = dol_buildpath($reldir."core/modules/commande/");
499
500 // Load file with numbering class (if found)
501 $mybool = ((bool) @include_once $dir.$file) || $mybool;
502 }
503
504 if (!$mybool) {
505 dol_print_error(null, "Failed to include file ".$file);
506 return '';
507 }
508
509 $obj = new $classname();
511 '@phan-var-force ModeleNumRefCommandes $obj';
512
513 $numref = $obj->getNextValue($soc, $this);
514
515 if ($numref != "") {
516 return $numref;
517 } else {
518 $this->error = $obj->error;
519 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
520 return "";
521 }
522 } else {
523 print $langs->trans("Error")." ".$langs->trans("Error_COMMANDE_ADDON_NotDefined");
524 return "";
525 }
526 }
527
528
537 public function valid($user, $idwarehouse = 0, $notrigger = 0)
538 {
539 global $conf, $langs;
540
541 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
542
543 $error = 0;
544
545 // Protection
546 if ($this->status == self::STATUS_VALIDATED) {
547 dol_syslog(get_class($this)."::valid action abandoned: already validated", LOG_WARNING);
548 return 0;
549 }
550
551 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
552 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')))) {
553 $this->error = 'NotEnoughPermissions';
554 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
555 return -1;
556 }
557 if (empty($this->socid)) {
558 $this->error = 'ErrorWrongParameters';
559 return -1;
560 }
561 if (!getDolGlobalBool('ORDER_NOCHECK_ONSALE_PRODUCTS_ONVALID') && !$this->checkActiveProductInLines()) {
562 dol_syslog(get_class($this)."::valid checkActiveProductInLines ".$this->error, LOG_INFO);
563 return -1;
564 }
565 $now = dol_now();
566
567 $this->db->begin();
568
569 // Definition du nom de module de numerotation de commande
570 $soc = new Societe($this->db);
571 $soc->fetch($this->socid);
572
573 // Class of company linked to order
574 $result = $soc->setAsCustomer();
575
576 // Define new ref
577 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
578 $num = $this->getNextNumRef($soc);
579 } else {
580 $num = (string) $this->ref;
581 }
582 $this->newref = dol_sanitizeFileName($num);
583
584 // Validate
585 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
586 $sql .= " SET ref = '".$this->db->escape($num)."',";
587 $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
588 $sql .= " date_valid = '".$this->db->idate($now)."',";
589 $sql .= " fk_user_valid = ".($user->id > 0 ? (int) $user->id : "null").",";
590 $sql .= " fk_user_modif = ".((int) $user->id);
591 $sql .= " WHERE rowid = ".((int) $this->id);
592
593 dol_syslog(get_class($this)."::valid", LOG_DEBUG);
594 $resql = $this->db->query($sql);
595 if (!$resql) {
596 dol_print_error($this->db);
597 $this->error = $this->db->lasterror();
598 $error++;
599 }
600
601 if (!$error) {
602 // If stock is incremented on validate order, we must increment it
603 if ($result >= 0 && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
604 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
605 $langs->load("agenda");
606
607 // Loop on each line
608 $cpt = count($this->lines);
609 for ($i = 0; $i < $cpt; $i++) {
610 if ($this->lines[$i]->fk_product > 0) {
611 $mouvP = new MouvementStock($this->db);
612 $mouvP->origin = &$this;
613 $mouvP->setOrigin($this->element, $this->id);
614 // We decrement stock of product (and sub-products)
615 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv("OrderValidatedInDolibarr", $num));
616 if ($result < 0) {
617 $error++;
618 $this->setErrorsFromObject($mouvP);
619 }
620 }
621 if ($error) {
622 break;
623 }
624 }
625 }
626 }
627
628 if (!$error && !$notrigger) {
629 // Call trigger
630 $result = $this->call_trigger('ORDER_VALIDATE', $user);
631 if ($result < 0) {
632 $error++;
633 }
634 // End call triggers
635 }
636
637 if (!$error) {
638 $this->oldref = $this->ref;
639
640 // Rename directory if dir was a temporary ref
641 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
642 // Now we rename also files into index
643 $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)."'";
644 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
645 $resql = $this->db->query($sql);
646 if (!$resql) {
647 $error++;
648 $this->error = $this->db->lasterror();
649 }
650 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'commande/".$this->db->escape($this->newref)."'";
651 $sql .= " WHERE filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
652 $resql = $this->db->query($sql);
653 if (!$resql) {
654 $error++;
655 $this->error = $this->db->lasterror();
656 }
657
658 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
659 $oldref = dol_sanitizeFileName($this->ref);
660 $newref = dol_sanitizeFileName($num);
661 $dirsource = getMultidirOutput($this).'/'.$oldref;
662 $dirdest = getMultidirOutput($this).'/'.$newref;
663 if (!$error && file_exists($dirsource)) {
664 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
665
666 if (@rename($dirsource, $dirdest)) {
667 dol_syslog("Rename ok");
668 // Rename docs starting with $oldref with $newref
669 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
670 foreach ($listoffiles as $fileentry) {
671 $dirsource = $fileentry['name'];
672 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
673 $dirsource = $fileentry['path'].'/'.$dirsource;
674 $dirdest = $fileentry['path'].'/'.$dirdest;
675 @rename($dirsource, $dirdest);
676 }
677 }
678 }
679 }
680 }
681
682 // Set new ref and current status
683 if (!$error) {
684 $this->ref = $num;
685 $this->statut = self::STATUS_VALIDATED; // deprecated
687 }
688
689 if (!$error) {
690 $this->db->commit();
691 return 1;
692 } else {
693 $this->db->rollback();
694 return -1;
695 }
696 }
697
698 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
706 public function setDraft($user, $idwarehouse = -1)
707 {
708 //phpcs:enable
709 global $langs;
710
711 $error = 0;
712
713 // Protection
714 if ($this->status <= self::STATUS_DRAFT && !getDolGlobalInt('ORDER_REOPEN_TO_DRAFT')) {
715 return 0;
716 }
717
718 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
719 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')))) {
720 $this->error = 'Permission denied';
721 return -1;
722 }
723
724 dol_syslog(__METHOD__, LOG_DEBUG);
725
726 $this->db->begin();
727
728 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
729 $sql .= " SET fk_statut = ".((int) self::STATUS_DRAFT).",";
730 $sql .= " fk_user_modif = ".((int) $user->id);
731 $sql .= " WHERE rowid = ".((int) $this->id);
732
733 if ($this->db->query($sql)) {
734 $this->oldcopy = clone $this;
735
736 // If stock is decremented on validate order, we must reincrement it
737 if (isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
738 $result = 0;
739
740 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
741 $langs->load("agenda");
742
743 $num = count($this->lines);
744 for ($i = 0; $i < $num; $i++) {
745 if ($this->lines[$i]->fk_product > 0) {
746 $mouvP = new MouvementStock($this->db);
747 $mouvP->origin = &$this;
748 $mouvP->setOrigin($this->element, $this->id);
749 // We increment stock of product (and sub-products)
750 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv("OrderBackToDraftInDolibarr", $this->ref));
751 if ($result < 0) {
752 $error++;
753 $this->setErrorsFromObject($mouvP);
754 break;
755 }
756 }
757 }
758 }
759
760 if (!$error) {
761 // Call trigger
762 $result = $this->call_trigger('ORDER_UNVALIDATE', $user);
763 if ($result < 0) {
764 $error++;
765 }
766 }
767
768 if (!$error) {
769 $this->statut = self::STATUS_DRAFT; // deprecated
770 $this->status = self::STATUS_DRAFT;
771 $this->db->commit();
772 return 1;
773 } else {
774 $this->db->rollback();
775 return -1;
776 }
777 } else {
778 $this->error = $this->db->error();
779 $this->db->rollback();
780 return -1;
781 }
782 }
783
784
785 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
793 public function set_reopen($user)
794 {
795 // phpcs:enable
796 $error = 0;
797
798 if ($this->status != self::STATUS_CANCELED && $this->status != self::STATUS_CLOSED) {
799 dol_syslog(get_class($this)."::set_reopen order has not status closed", LOG_WARNING);
800 return 0;
801 }
802
803 $this->db->begin();
804
805 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
806 $sql .= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0,';
807 $sql .= " fk_user_modif = ".((int) $user->id);
808 $sql .= " WHERE rowid = ".((int) $this->id);
809
810 dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG);
811 $resql = $this->db->query($sql);
812 if ($resql) {
813 // Call trigger
814 $result = $this->call_trigger('ORDER_REOPEN', $user);
815 if ($result < 0) {
816 $error++;
817 }
818 // End call triggers
819 } else {
820 $error++;
821 $this->error = $this->db->lasterror();
822 dol_print_error($this->db);
823 }
824
825 if (!$error) {
826 $this->statut = self::STATUS_VALIDATED; // deprecated
828 $this->billed = 0;
829
830 $this->db->commit();
831 return 1;
832 } else {
833 foreach ($this->errors as $errmsg) {
834 dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR);
835 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
836 }
837 $this->db->rollback();
838 return -1 * $error;
839 }
840 }
841
850 public function cloture($user, $notrigger = 0, $checkpermission = 1)
851 {
852 $error = 0;
853
854 $usercanclose = (!$checkpermission
855 || (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
856 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'close')));
857
858 if ($usercanclose) {
859 if ($this->status == self::STATUS_CLOSED) {
860 return 0;
861 }
862 $this->db->begin();
863
864 $now = dol_now();
865
866 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
867 $sql .= ' SET fk_statut = '.self::STATUS_CLOSED.',';
868 $sql .= ' fk_user_cloture = '.((int) $user->id).',';
869 $sql .= " date_cloture = '".$this->db->idate($now)."',";
870 $sql .= " fk_user_modif = ".((int) $user->id);
871 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
872
873 if ($this->db->query($sql)) {
874 if (!$notrigger) {
875 // Call trigger
876 $result = $this->call_trigger('ORDER_CLOSE', $user);
877 if ($result < 0) {
878 $error++;
879 }
880 // End call triggers
881 }
882
883 if (!$error) {
884 $this->statut = self::STATUS_CLOSED; // deprecated
886
887 $this->db->commit();
888 return 1;
889 } else {
890 $this->db->rollback();
891 return -1;
892 }
893 } else {
894 $this->error = $this->db->lasterror();
895
896 $this->db->rollback();
897 return -1;
898 }
899 }
900 return 0;
901 }
902
914 public function setCategories($categories)
915 {
916 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
917 return parent::setCategoriesCommon($categories, Categorie::TYPE_ORDER);
918 }
919
928 public function cancel($user, $idwarehouse = -1)
929 {
930 global $user, $langs;
931
932 $error = 0;
933
934 $this->db->begin();
935
936 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
937 $sql .= " SET fk_statut = ".self::STATUS_CANCELED.",";
938 $sql .= " fk_user_modif = ".((int) $user->id);
939 $sql .= " WHERE rowid = ".((int) $this->id);
940 $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
941
942 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
943 if ($this->db->query($sql)) {
944 // If stock is decremented on validate order, we must reincrement it
945 if (isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
946 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
947 $langs->load("agenda");
948
949 $num = count($this->lines);
950 for ($i = 0; $i < $num; $i++) {
951 if ($this->lines[$i]->fk_product > 0) {
952 $mouvP = new MouvementStock($this->db);
953 $mouvP->setOrigin($this->element, $this->id);
954 // We increment stock of product (and sub-products)
955 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv("OrderCanceledInDolibarr", $this->ref)); // price is 0, we don't want WAP to be changed
956 if ($result < 0) {
957 $error++;
958 $this->setErrorsFromObject($mouvP);
959 break;
960 }
961 }
962 }
963 }
964
965 if (!$error) {
966 // Call trigger
967 $result = $this->call_trigger('ORDER_CANCEL', $user);
968 if ($result < 0) {
969 $error++;
970 }
971 // End call triggers
972 }
973
974 if (!$error) {
975 $this->statut = self::STATUS_CANCELED; // deprecated
977 $this->db->commit();
978 return 1;
979 } else {
980 foreach ($this->errors as $errmsg) {
981 dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
982 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
983 }
984 $this->db->rollback();
985 return -1 * $error;
986 }
987 } else {
988 $this->error = $this->db->error();
989 $this->db->rollback();
990 return -1;
991 }
992 }
993
1002 public function create($user, $notrigger = 0)
1003 {
1004 global $conf, $langs, $mysoc;
1005 $error = 0;
1006
1007 // Clean parameters
1008
1009 if (empty($this->socid)) {
1010 $this->error = 'ErrorWrongParameters';
1011 return -1;
1012 }
1013
1014 // Set tmp vars
1015 $date = ($this->date_commande ? $this->date_commande : $this->date);
1016 $this->import_key = trim((string) $this->import_key);
1017 $delivery_date = $this->delivery_date;
1018
1019 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1020 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1021 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
1022 } else {
1023 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1024 }
1025 if (empty($this->fk_multicurrency)) {
1026 $this->multicurrency_code = $conf->currency;
1027 $this->fk_multicurrency = 0;
1028 $this->multicurrency_tx = 1;
1029 }
1030 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
1031 $this->entity = setEntity($this);
1032
1033 dol_syslog(get_class($this)."::create user=".$user->id);
1034
1035 // Check parameters
1036 if (!empty($this->ref)) { // We check that ref is not already used
1037 $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
1038 if ($result > 0) {
1039 $this->error = 'ErrorRefAlreadyExists';
1040 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1041 $this->db->rollback();
1042 return -1;
1043 }
1044 }
1045
1046 if ($this->isRefClientAlreadyUsed((string) $this->ref_client, (int) $this->socid) != 0) {
1047 return -1;
1048 }
1049
1050 $soc = new Societe($this->db);
1051 $result = $soc->fetch($this->socid);
1052 if ($result < 0) {
1053 $this->error = "Failed to fetch company";
1054 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1055 return -2;
1056 }
1057 if (getDolGlobalString('ORDER_REQUIRE_SOURCE') && $this->source < 0) {
1058 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Source"));
1059 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1060 return -1;
1061 }
1062
1063 $this->date_creation = dol_now();
1064
1065 $this->db->begin();
1066
1067 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1068 $sql .= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client";
1069 $sql .= ", model_pdf, fk_cond_reglement, deposit_percent, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
1070 $sql .= ", fk_shipping_method";
1071 $sql .= ", fk_warehouse";
1072 $sql .= ", fk_incoterms, location_incoterms";
1073 $sql .= ", entity, module_source, pos_source";
1074 $sql .= ", fk_multicurrency";
1075 $sql .= ", multicurrency_code";
1076 $sql .= ", multicurrency_tx";
1077 $sql .= ", import_key";
1078 $sql .= ")";
1079 $sql .= " VALUES ('(PROV)', ".((int) $this->socid).", '".$this->db->idate($this->date_creation)."', ".($user->id > 0 ? ((int) $user->id) : "null");
1080 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1081 $sql .= ", '".$this->db->idate($date)."'";
1082 $sql .= ", ".($this->source >= 0 && $this->source != '' ? $this->db->escape((string) $this->source) : 'null');
1083 $sql .= ", '".$this->db->escape((string) $this->note_private)."'";
1084 $sql .= ", '".$this->db->escape((string) $this->note_public)."'";
1085 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1086 $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
1087 $sql .= ", '".$this->db->escape((string) $this->model_pdf)."'";
1088 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
1089 $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1090 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
1091 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1092 $sql .= ", ".($this->availability_id > 0 ? ((int) $this->availability_id) : "null");
1093 $sql .= ", ".($this->demand_reason_id > 0 ? ((int) $this->demand_reason_id) : "null");
1094 $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
1095 $sql .= ", ".($this->fk_delivery_address > 0 ? ((int) $this->fk_delivery_address) : 'NULL');
1096 $sql .= ", ".(!empty($this->shipping_method_id) && $this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : 'NULL');
1097 $sql .= ", ".(!empty($this->warehouse_id) && $this->warehouse_id > 0 ? ((int) $this->warehouse_id) : 'NULL');
1098 $sql .= ", ".(int) $this->fk_incoterms;
1099 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1100 $sql .= ", ".(int) $this->entity;
1101 $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
1102 $sql .= ", ".((!is_null($this->pos_source) && $this->pos_source != '') ? "'".$this->db->escape($this->pos_source)."'" : "null"); // Can be null, '', '0', '1'
1103 $sql .= ", ".(int) $this->fk_multicurrency;
1104 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1105 $sql .= ", ".(float) $this->multicurrency_tx;
1106 $sql .= ", '".$this->db->escape($this->import_key)."'";
1107 $sql .= ")";
1108
1109 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1110 $resql = $this->db->query($sql);
1111 if ($resql) {
1112 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande');
1113
1114 if ($this->id) {
1115 $fk_parent_line = 0;
1116 $num = count($this->lines);
1117
1118 /*
1119 * Insert products details into db
1120 */
1121 for ($i = 0; $i < $num; $i++) {
1122 $line = $this->lines[$i];
1123
1124 // Test and convert into OrderLine object this->lines[$i]. When coming from REST API, we may still have an array
1125 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
1126 if (!is_object($line)) {
1127 $lineobj = new OrderLine($this->db);
1128 foreach ($line as $key => $val) {
1129 $lineobj->$key = $val;
1130 }
1131 $line = $lineobj;
1132 $this->lines[$i] = $line;
1133 }
1134
1135 // Reset fk_parent_line for no child products and special product
1136 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1137 $fk_parent_line = 0;
1138 }
1139
1140 // Complete vat rate with code
1141 $vatrate = $line->tva_tx;
1142 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
1143 $vatrate .= ' ('.$line->vat_src_code.')';
1144 }
1145
1146 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
1147 $originid = $line->origin_id;
1148 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
1149 } else { // old but bugged version (we store id of line and type of parent object)
1150 $originid = $line->id;
1151 $origintype = $this->element;
1152 }
1153
1154 // ref_ext
1155 if (empty($line->ref_ext)) {
1156 $line->ref_ext = '';
1157 }
1158
1159 // Preserve the original entry mode of the line so the total is computed from the typed value (no rounding drift).
1160 $line_price_base_type = $line->getPriceBaseType();
1161 $result = $this->addline(
1162 $line->desc,
1163 (float) $line->subprice,
1164 $line->qty,
1165 $vatrate,
1166 $line->localtax1_tx,
1167 $line->localtax2_tx,
1168 $line->fk_product,
1169 $line->remise_percent,
1170 $line->info_bits,
1171 $line->fk_remise_except,
1172 $line_price_base_type,
1173 (float) $line->subprice_ttc,
1174 $line->date_start,
1175 $line->date_end,
1176 $line->product_type,
1177 $line->rang,
1178 $line->special_code,
1179 $fk_parent_line,
1180 $line->fk_fournprice,
1181 $line->pa_ht,
1182 $line->label,
1183 $line->array_options,
1184 $line->fk_unit,
1185 (string) $origintype,
1186 $originid,
1187 0,
1188 $line->ref_ext,
1189 1
1190 );
1191
1192 if ($result < 0) {
1193 if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER) {
1194 $this->error = $this->db->lasterror();
1195 $this->errors[] = $this->error;
1196 dol_print_error($this->db);
1197 }
1198 $this->db->rollback();
1199 return -1;
1200 }
1201
1202 // Keep the extra parameters of the source line (for example the options of subtotal lines): addline() can't
1203 // do it when the object is cloned, because the origin it receives is the one of the source line, not the source line
1204 if ($result > 0 && !empty($line->extraparams)) {
1205 $newline = new OrderLine($this->db);
1206 $newline->id = $result;
1207 $newline->extraparams = $line->extraparams;
1208 $newline->setExtraParameters();
1209 }
1210
1211 // Defined the new fk_parent_line
1212 if ($result > 0 && $line->product_type == 9) {
1213 $fk_parent_line = $result;
1214 }
1215 }
1216
1217 $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.
1218
1219 // update ref
1220 $initialref = '(PROV'.$this->id.')';
1221 if (!empty($this->ref)) {
1222 $initialref = $this->ref;
1223 }
1224
1225 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id);
1226 if ($this->db->query($sql)) {
1227 $this->ref = $initialref;
1228
1229 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1230 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1231 }
1232
1233 // Add object linked
1234 if (!empty($this->linked_objects) && is_array($this->linked_objects)) {
1235 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1236 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, ...))
1237 foreach ($tmp_origin_id as $origin_id) {
1238 $ret = $this->add_object_linked($origin, $origin_id);
1239 if (!$ret) {
1240 $this->error = $this->db->lasterror();
1241 $error++;
1242 }
1243 }
1244 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1245 $origin_id = $tmp_origin_id;
1246 $ret = $this->add_object_linked($origin, $origin_id);
1247 if (!$ret) {
1248 $this->error = $this->db->lasterror();
1249 $error++;
1250 }
1251 }
1252 }
1253 }
1254
1255 if (!$error && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1256 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
1257 $originidforcontact = $this->origin_id;
1258 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1259 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1260 $exp = new Expedition($this->db);
1261 $exp->fetch($this->origin_id);
1262 $exp->fetchObjectLinked();
1263 if (count($exp->linkedObjectsIds['commande']) > 0) {
1264 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1265 $originforcontact = 'commande';
1266 if (is_object($value)) {
1267 $originidforcontact = $value->id;
1268 } else {
1269 $originidforcontact = $value;
1270 }
1271 break; // We take first one
1272 }
1273 }
1274 }
1275
1276 $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";
1277 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1278
1279 $resqlcontact = $this->db->query($sqlcontact);
1280 if ($resqlcontact) {
1281 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1282 //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1283 $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
1284 }
1285 } else {
1286 dol_print_error($this->db);
1287 }
1288 }
1289
1290 if (!$error) {
1291 $result = $this->insertExtraFields();
1292 if ($result < 0) {
1293 $error++;
1294 }
1295 }
1296
1297 if (!$error && !$notrigger) {
1298 // Call trigger
1299 $result = $this->call_trigger('ORDER_CREATE', $user);
1300 if ($result < 0) {
1301 $error++;
1302 }
1303 // End call triggers
1304 }
1305
1306 if (!$error) {
1307 $this->db->commit();
1308 return $this->id;
1309 } else {
1310 $this->db->rollback();
1311 return -1 * $error;
1312 }
1313 } else {
1314 $this->error = $this->db->lasterror();
1315 $this->db->rollback();
1316 return -1;
1317 }
1318 }
1319
1320 return 0;
1321 } else {
1322 $this->error = $this->db->lasterror();
1323 $this->db->rollback();
1324 return -1;
1325 }
1326 }
1327
1328
1337 public function createFromClone(User $user, $socid = 0, $forceentity = null)
1338 {
1339 global $hookmanager;
1340
1341 $error = 0;
1342
1343 $object = new self($this->db);
1344
1345 $this->db->begin();
1346
1347 // Load source object
1348 $object->fetch($this->id);
1349
1350 $objFrom = clone $object;
1351
1352 // Change socid if needed
1353 if (!empty($socid) && $socid != $object->socid) {
1354 $objsoc = new Societe($this->db);
1355
1356 if ($objsoc->fetch($socid) > 0) {
1357 $object->socid = $objsoc->id;
1358 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1359 $object->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : '0');
1360 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1361 $object->fk_project = 0;
1362 $object->fk_delivery_address = 0;
1363 }
1364
1365 // TODO Change product price if multi-prices
1366 }
1367
1368 $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1369
1370 $object->id = 0;
1371 $object->ref = '';
1372 $object->statut = self::STATUS_DRAFT; // deprecated
1373 $object->status = self::STATUS_DRAFT;
1374
1375 // Clear fields
1376 $object->user_author_id = $user->id;
1377 $object->user_validation_id = 0;
1378 $object->date = dol_now();
1379 $object->date_commande = dol_now();
1380 $object->date_creation = '';
1381 $object->date_validation = '';
1382 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1383 $object->ref_client = '';
1384 $object->ref_customer = '';
1385 }
1386
1387 // Do not clone ref_ext
1388 $num = count($object->lines);
1389 for ($i = 0; $i < $num; $i++) {
1390 $object->lines[$i]->ref_ext = '';
1391 }
1392
1393 // Create clone
1394 $object->context['createfromclone'] = 'createfromclone';
1395 $object->context['createfromclone_fromid'] = $objFrom->id;
1396 $object->context['createfromclone_fromref'] = $objFrom->ref;
1397 $result = $object->create($user);
1398 if ($result < 0) {
1399 $error++;
1400 $this->setErrorsFromObject($object);
1401 }
1402
1403 if (!$error) {
1404 // copy internal contacts
1405 if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1406 $error++;
1407 }
1408 }
1409
1410 if (!$error) {
1411 // copy external contacts if same company
1412 if ($object->socid == $objFrom->socid) {
1413 if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1414 $error++;
1415 }
1416 }
1417 }
1418
1419 if (!$error) {
1420 // Hook of thirdparty module
1421 if (is_object($hookmanager)) {
1422 $parameters = array('objFrom' => $objFrom, 'clonedObj' => $object);
1423 $action = '';
1424 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1425 if ($reshook < 0) {
1426 $this->setErrorsFromObject($hookmanager);
1427 $error++;
1428 }
1429 }
1430 }
1431
1432 unset($object->context['createfromclone']);
1433 unset($object->context['createfromclone_fromid']);
1434 unset($object->context['createfromclone_fromref']);
1435
1436 // End
1437 if (!$error) {
1438 $this->db->commit();
1439 return $object->id;
1440 } else {
1441 $this->db->rollback();
1442 return -1;
1443 }
1444 }
1445
1446
1454 public function createFromProposal($object, User $user)
1455 {
1456 global $conf, $hookmanager, $langs;
1457
1458 require_once DOL_DOCUMENT_ROOT . '/multicurrency/class/multicurrency.class.php';
1459 require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
1460
1461 $error = 0;
1462
1463 $this->date_commande = dol_now();
1464 $this->date = dol_now();
1465 $this->source = 0;
1466
1467 $num = count($object->lines);
1468 for ($i = 0; $i < $num; $i++) {
1469 $line = new OrderLine($this->db);
1470
1471 $line->libelle = $object->lines[$i]->libelle;
1472 $line->label = $object->lines[$i]->label;
1473 $line->desc = $object->lines[$i]->desc;
1474 $line->price = $object->lines[$i]->price;
1475 $line->subprice = $object->lines[$i]->subprice;
1476 $line->subprice_ttc = $object->lines[$i]->subprice_ttc; // Preserve the TTC entry mode so create() keeps the typed value (no rounding drift).
1477 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1478 $line->tva_tx = $object->lines[$i]->tva_tx;
1479 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1480 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1481 $line->qty = $object->lines[$i]->qty;
1482 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1483 $line->remise_percent = $object->lines[$i]->remise_percent;
1484 $line->fk_product = $object->lines[$i]->fk_product;
1485 $line->info_bits = $object->lines[$i]->info_bits;
1486 $line->product_type = $object->lines[$i]->product_type;
1487 $line->rang = $object->lines[$i]->rang;
1488 $line->special_code = $object->lines[$i]->special_code;
1489 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1490 $line->fk_unit = $object->lines[$i]->fk_unit;
1491
1492 $line->date_start = $object->lines[$i]->date_start;
1493 $line->date_end = $object->lines[$i]->date_end;
1494
1495 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1496 $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);
1497 $line->pa_ht = $marginInfos[0];
1498 $line->marge_tx = $marginInfos[1];
1499 $line->marque_tx = $marginInfos[2];
1500
1501 $line->origin = $object->element;
1502 $line->origin_id = $object->lines[$i]->id;
1503
1504 // get extrafields from original line
1505 $object->lines[$i]->fetch_optionals();
1506 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1507 $line->array_options[$options_key] = $value;
1508 }
1509
1510 $this->lines[$i] = $line;
1511 }
1512
1513 $this->entity = $object->entity;
1514 $this->socid = $object->socid;
1515 $this->fk_project = $object->fk_project;
1516 $this->cond_reglement_id = $object->cond_reglement_id;
1517 $this->deposit_percent = $object->deposit_percent;
1518 $this->mode_reglement_id = $object->mode_reglement_id;
1519 $this->fk_account = $object->fk_account;
1520 $this->fk_incoterms = $object->fk_incoterms;
1521 $this->location_incoterms = $object->location_incoterms;
1522 $this->availability_id = $object->availability_id;
1523 $this->demand_reason_id = $object->demand_reason_id;
1524 $this->delivery_date = $object->delivery_date;
1525 $this->shipping_method_id = $object->shipping_method_id;
1526 $this->warehouse_id = $object->warehouse_id;
1527 $this->fk_delivery_address = $object->fk_delivery_address;
1528 $this->contact_id = $object->contact_id;
1529 $this->ref_client = $object->ref_client;
1530 $this->ref_customer = $object->ref_client;
1531
1532 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1533 $this->note_private = $object->note_private;
1534 $this->note_public = $object->note_public;
1535 }
1536
1537 $this->origin = $object->element;
1538 $this->origin_id = $object->id;
1539
1540 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1541 if (isModEnabled('multicurrency')) {
1542 if (!empty($object->multicurrency_code)) {
1543 $this->multicurrency_code = $object->multicurrency_code;
1544 }
1545 if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($object->multicurrency_tx)) {
1546 $this->multicurrency_tx = $object->multicurrency_tx;
1547 }
1548
1549 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1550 $tmparray = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date_commande);
1551 $this->fk_multicurrency = $tmparray[0];
1552 $this->multicurrency_tx = $tmparray[1];
1553 } else {
1554 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1555 }
1556 if (empty($this->fk_multicurrency)) {
1557 $this->multicurrency_code = $conf->currency;
1558 $this->fk_multicurrency = 0;
1559 $this->multicurrency_tx = 1;
1560 }
1561 }
1562
1563 // get extrafields from original line
1564 $object->fetch_optionals();
1565
1566 $e = new ExtraFields($this->db);
1567 $element_extrafields = $e->fetch_name_optionals_label($this->table_element);
1568
1569 foreach ($object->array_options as $options_key => $value) {
1570 if (array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)) {
1571 $this->array_options[$options_key] = $value;
1572 }
1573 }
1574 // Possibility to add external linked objects with hooks
1575 $this->linked_objects[$this->origin] = $this->origin_id;
1576 if (isset($object->other_linked_objects) && is_array($object->other_linked_objects) && !empty($object->other_linked_objects)) {
1577 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1578 }
1579
1580 $ret = $this->create($user);
1581
1582 if ($ret > 0) {
1583 // Actions hooked (by external module)
1584 $hookmanager->initHooks(array('orderdao'));
1585
1586 $parameters = array('objFrom' => $object);
1587 $action = '';
1588 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1589 if ($reshook < 0) {
1590 $this->setErrorsFromObject($hookmanager);
1591 $error++;
1592 }
1593
1594 if (!$error) {
1595 // Validate immediately the order
1596 if (getDolGlobalString('ORDER_VALID_AFTER_CLOSE_PROPAL')) {
1597 $this->fetch($ret);
1598 $result = $this->valid($user);
1599 if ($result > 0 && !getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1600 $this->fetch($this->id);
1601 $this->fetch_thirdparty();
1602
1603 $outputlangs = $langs;
1604 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($this->thirdparty->default_lang)) {
1605 $outputlangs = new Translate('', $conf);
1606 $outputlangs->setDefaultLang($this->thirdparty->default_lang);
1607 $outputlangs->loadLangs(array('main', 'orders'));
1608 }
1609
1610 $this->generateDocument($this->model_pdf, $outputlangs);
1611 }
1612 }
1613 return $ret;
1614 } else {
1615 return -1;
1616 }
1617 } else {
1618 return -1;
1619 }
1620 }
1621
1622
1662 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)
1663 {
1664 global $mysoc, $langs, $user;
1665
1666 $logtext = "::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent";
1667 $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";
1668 $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";
1669 dol_syslog(get_class($this).$logtext, LOG_DEBUG);
1670
1671 if ($this->status == self::STATUS_DRAFT) {
1672 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1673
1674 // Clean parameters
1675
1676 if (empty($remise_percent)) {
1677 $remise_percent = 0;
1678 }
1679 if (empty($qty)) {
1680 $qty = 0;
1681 }
1682 if (empty($info_bits)) {
1683 $info_bits = 0;
1684 }
1685 if (empty($rang)) {
1686 $rang = 0;
1687 }
1688 if (empty($txtva)) {
1689 $txtva = 0;
1690 }
1691 if (empty($txlocaltax1)) {
1692 $txlocaltax1 = 0;
1693 }
1694 if (empty($txlocaltax2)) {
1695 $txlocaltax2 = 0;
1696 }
1697 if (empty($fk_parent_line) || $fk_parent_line < 0) {
1698 $fk_parent_line = 0;
1699 }
1700 if (empty($this->fk_multicurrency)) {
1701 $this->fk_multicurrency = 0;
1702 }
1703 if (empty($ref_ext)) {
1704 $ref_ext = '';
1705 }
1706
1707 $remise_percent = (float) price2num($remise_percent);
1708 $qty = (float) price2num($qty);
1709 $pu_ht = price2num($pu_ht);
1710 $pu_ht_devise = price2num($pu_ht_devise);
1711 $pu_ttc = price2num($pu_ttc);
1712 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
1713 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
1714 $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
1715 }
1716 $txlocaltax1 = price2num($txlocaltax1);
1717 $txlocaltax2 = price2num($txlocaltax2);
1718 if ($price_base_type == 'HT') {
1719 $pu = $pu_ht;
1720 } else {
1721 $pu = $pu_ttc;
1722 }
1723 $label = trim((string) $label);
1724 $desc = trim((string) $desc);
1725
1726 // Check parameters
1727 if ($type < 0) {
1728 return -1;
1729 }
1730
1731 if ($date_start && $date_end && $date_start > $date_end) {
1732 $langs->load("errors");
1733 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1734 return -1;
1735 }
1736
1737 $this->db->begin();
1738
1739 $product_type = $type;
1740 if (!empty($fk_product) && $fk_product > 0) {
1741 $product = new Product($this->db);
1742 $result = $product->fetch($fk_product);
1743 $product_type = $product->type;
1744
1745 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_ORDER') && $product->isStockManaged()) {
1746 // get real stock
1747 $productChildrenNb = 0;
1748 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
1749 $productChildrenNb = $product->hasFatherOrChild(1);
1750 }
1751 if ($productChildrenNb > 0) {
1752 // compute real stock from each subcomponent
1753 $product_stock = null;
1754 $product->loadStockForVirtualProduct('warehouseopen', $qty);
1755 foreach ($product->stock_warehouse as $componentStockWarehouse) {
1756 if ($product_stock === null) {
1757 $product_stock = $componentStockWarehouse->real;
1758 } else {
1759 $product_stock = min($product_stock, $componentStockWarehouse->real);
1760 }
1761 }
1762 if ($product_stock === null) {
1763 $product_stock = 0;
1764 }
1765 } else {
1766 $product_stock = $product->stock_reel;
1767 }
1768
1769 if ($product_stock < $qty) {
1770 $langs->load("errors");
1771 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
1772 $this->errors[] = $this->error;
1773 dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
1774 $this->db->rollback();
1776 }
1777 }
1778 }
1779 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1780 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1781 // and this is done at the line level, which has its own VAT rate
1782
1783 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
1784
1785 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
1786 $tmpproduct = new Product($this->db);
1787 $result = $tmpproduct->fetch($fk_product);
1788 $newqty = $this->roundQtyToPackaging($qty, $tmpproduct->packaging);
1789 if ($newqty != $qty) {
1790 $qty = $newqty;
1791 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
1792 }
1793 }
1794
1795 // Clean vat code
1796 $reg = array();
1797 $vat_src_code = '';
1798 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1799 $vat_src_code = $reg[1];
1800 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1801 }
1802
1803 $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, $this->multicurrency_code);
1804
1805 $total_ht = $tabprice[0];
1806 $total_tva = $tabprice[1];
1807 $total_ttc = $tabprice[2];
1808 $total_localtax1 = $tabprice[9];
1809 $total_localtax2 = $tabprice[10];
1810 $pu_ht = $tabprice[3];
1811
1812 // MultiCurrency
1813 $multicurrency_total_ht = $tabprice[16];
1814 $multicurrency_total_tva = $tabprice[17];
1815 $multicurrency_total_ttc = $tabprice[18];
1816 $pu_ht_devise = $tabprice[19];
1817
1818 // Rang to use
1819 $ranktouse = $rang;
1820
1821 if (empty($ranktouse) || $ranktouse == -1) {
1822 $rangmax = $this->line_max($fk_parent_line);
1823 $ranktouse = $rangmax + 1;
1824 }
1825
1826 // Insert line
1827 $this->line = new OrderLine($this->db);
1828
1829 $this->line->context = $this->context;
1830
1831 $this->line->fk_commande = $this->id;
1832 $this->line->label = $label;
1833 $this->line->desc = $desc;
1834 $this->line->qty = (float) $qty;
1835 $this->line->ref_ext = $ref_ext;
1836
1837 $this->line->vat_src_code = $vat_src_code;
1838 $this->line->tva_tx = $txtva;
1839 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
1840 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
1841 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
1842 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
1843 $this->line->fk_product = $fk_product;
1844 $this->line->product_type = $product_type;
1845 $this->line->fk_remise_except = $fk_remise_except;
1846 $this->line->remise_percent = $remise_percent;
1847 $this->line->subprice = (float) $pu_ht;
1848 // Persist the original entry mode of the line so updateline() can preserve it later.
1849 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? (float) $pu_ttc : 0;
1850 $this->line->rang = $ranktouse;
1851 $this->line->info_bits = $info_bits;
1852 $this->line->total_ht = (float) $total_ht;
1853 $this->line->total_tva = (float) $total_tva;
1854 $this->line->total_localtax1 = (float) $total_localtax1;
1855 $this->line->total_localtax2 = (float) $total_localtax2;
1856 $this->line->total_ttc = (float) $total_ttc;
1857 $this->line->special_code = $special_code;
1858 if (empty($qty) && empty($special_code)) {
1859 $this->line->special_code = 3;
1860 }
1861 $this->line->origin = $origin;
1862 $this->line->origin_type = $origin;
1863 $this->line->origin_id = $origin_id;
1864
1865 $this->line->fk_parent_line = $fk_parent_line;
1866 $this->line->fk_unit = $fk_unit;
1867
1868 $this->line->date_start = $date_start;
1869 $this->line->date_end = $date_end;
1870
1871 $this->line->fk_fournprice = $fk_fournprice;
1872 $this->line->pa_ht = $pa_ht; // Can be '' when not defined or 0 if defined to 0 or a price value
1873
1874 // Multicurrency
1875 $this->line->fk_multicurrency = $this->fk_multicurrency;
1876 $this->line->multicurrency_code = $this->multicurrency_code;
1877 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
1878 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
1879 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
1880 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
1881
1882 if (is_array($array_options) && count($array_options) > 0) {
1883 $this->line->array_options = $array_options;
1884 }
1885
1886 $result = $this->line->insert($user);
1887 if ($result > 0) {
1888 // Update denormalized fields at the order level
1889 if (empty($noupdateafterinsertline)) {
1890 $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.
1891 }
1892
1893 if ($result > 0) {
1894 if (!isset($this->context['createfromclone'])) {
1895 if (!empty($fk_parent_line)) {
1896 // Always reorder if child line
1897 $this->line_order(true, 'DESC');
1898 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
1899 // Update all rank of all other lines starting from the same $ranktouse
1900 foreach ($this->lines as $tmpline) {
1901 if ($tmpline->rang >= $ranktouse) {
1902 if (!empty($tmpline->id)) {
1903 $this->updateRangOfLine($tmpline->id, $tmpline->rang + 1);
1904 }
1905 }
1906 }
1907 }
1908
1909 $this->lines[] = $this->line;
1910 } else {
1911 // Loop on all lines of parent object
1912 foreach ($this->lines as $tmpline) {
1913 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
1914 $this->line->extraparams = $tmpline->extraparams;
1915 $this->line->setExtraParameters();
1916 }
1917 }
1918 }
1919
1920 $this->db->commit();
1921 return $this->line->id;
1922 } else {
1923 $this->db->rollback();
1924 return -1;
1925 }
1926 } else {
1927 $this->setErrorsFromObject($this->line);
1928 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1929 $this->db->rollback();
1930 return -2;
1931 }
1932 } else {
1933 dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR);
1934 return -3;
1935 }
1936 }
1937
1938
1939 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1953 public function add_product($idproduct, $qty, $remise_percent = 0.0, $date_start = '', $date_end = '')
1954 {
1955 // phpcs:enable
1956 global $conf, $mysoc;
1957
1958 if (!$qty) {
1959 $qty = 1;
1960 }
1961
1962 if ($idproduct > 0) {
1963 $prod = new Product($this->db);
1964 $prod->fetch($idproduct);
1965
1966 $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
1967 $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
1968 if (empty($tva_tx)) {
1969 $tva_npr = 0;
1970 }
1971 $vat_src_code = ''; // May be defined into tva_tx
1972
1973 $localtax1_tx = get_localtax($tva_tx, 1, $this->thirdparty, $mysoc, $tva_npr);
1974 $localtax2_tx = get_localtax($tva_tx, 2, $this->thirdparty, $mysoc, $tva_npr);
1975
1976 // multiprix
1977 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $this->thirdparty->price_level) {
1978 $price = $prod->multiprices[$this->thirdparty->price_level];
1979 $price_ttc = $prod->multiprices_ttc[$this->thirdparty->price_level];
1980 } else {
1981 $price = $prod->price;
1982 $price_ttc = $prod->price_ttc;
1983 }
1984
1985 $line = new OrderLine($this->db);
1986
1987 $line->context = $this->context;
1988
1989 $line->fk_product = $idproduct;
1990 $line->desc = $prod->description;
1991 $line->qty = $qty;
1992 $line->subprice = $price;
1993 $line->subprice_ttc = $price_ttc;
1994 $line->remise_percent = $remise_percent;
1995 $line->vat_src_code = $vat_src_code;
1996 $line->tva_tx = $tva_tx;
1997 $line->localtax1_tx = $localtax1_tx;
1998 $line->localtax2_tx = $localtax2_tx;
1999
2000 $line->product_ref = $prod->ref;
2001 $line->product_label = $prod->label;
2002 $line->product_desc = $prod->description;
2003 $line->fk_unit = $prod->fk_unit;
2004
2005 // Save the start and end date of the line in the object
2006 if ($date_start) {
2007 $line->date_start = $date_start;
2008 }
2009 if ($date_end) {
2010 $line->date_end = $date_end;
2011 }
2012
2013 $this->lines[] = $line;
2014
2032 }
2033 }
2034
2035
2045 public function fetch($id, $ref = '', $ref_ext = '', $notused = '')
2046 {
2047 // Check parameters
2048 if (empty($id) && empty($ref) && empty($ref_ext)) {
2049 return -1;
2050 }
2051
2052 $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';
2053 $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';
2054 $sql .= ', c.fk_account';
2055 $sql .= ', c.date_commande, c.date_valid, c.tms';
2056 $sql .= ', c.date_livraison as delivery_date';
2057 $sql .= ', c.fk_shipping_method';
2058 $sql .= ', c.fk_warehouse';
2059 $sql .= ', c.fk_projet as fk_project, c.source, c.facture as billed';
2060 $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';
2061 $sql .= ', c.fk_incoterms, c.location_incoterms';
2062 $sql .= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
2063 $sql .= ", c.module_source, c.pos_source";
2064 $sql .= ", i.libelle as label_incoterms";
2065 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2066 $sql .= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
2067 $sql .= ', ca.code as availability_code, ca.label as availability_label';
2068 $sql .= ', dr.code as demand_reason_code';
2069 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as c';
2070 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid';
2071 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id';
2072 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
2073 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = dr.rowid';
2074 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
2075
2076 if ($id) {
2077 $sql .= " WHERE c.rowid = ".((int) $id);
2078 } else {
2079 $sql .= " WHERE c.entity IN (".getEntity('commande').")"; // Don't use entity if you use rowid
2080 }
2081
2082 if ($ref) {
2083 $sql .= " AND c.ref = '".$this->db->escape($ref)."'";
2084 }
2085 if ($ref_ext) {
2086 $sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'";
2087 }
2088
2089 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2090 $result = $this->db->query($sql);
2091 if ($result) {
2092 $obj = $this->db->fetch_object($result);
2093 if ($obj) {
2094 $this->id = $obj->rowid;
2095 $this->entity = $obj->entity;
2096
2097 $this->ref = $obj->ref;
2098 $this->ref_client = $obj->ref_client;
2099 $this->ref_customer = $obj->ref_client;
2100 $this->ref_ext = $obj->ref_ext;
2101
2102 $this->socid = $obj->fk_soc;
2103 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2104
2105 $this->fk_project = $obj->fk_project;
2106 $this->project = null; // Clear if another value was already set by fetch_projet
2107
2108 $this->statut = $obj->status; // deprecated
2109 $this->status = $obj->status;
2110
2111 $this->user_author_id = $obj->fk_user_author;
2112 $this->user_creation_id = $obj->fk_user_author;
2113 $this->user_validation_id = $obj->fk_user_valid;
2114 $this->user_modification_id = $obj->fk_user_modif;
2115 $this->total_ht = $obj->total_ht;
2116 $this->total_tva = $obj->total_tva;
2117 $this->total_localtax1 = $obj->total_localtax1;
2118 $this->total_localtax2 = $obj->total_localtax2;
2119 $this->total_ttc = $obj->total_ttc;
2120 $this->date = $this->db->jdate($obj->date_commande);
2121 $this->date_commande = $this->db->jdate($obj->date_commande);
2122 $this->date_creation = $this->db->jdate($obj->date_creation);
2123 $this->date_validation = $this->db->jdate($obj->date_valid);
2124 $this->date_modification = $this->db->jdate($obj->tms);
2125 $this->source = $obj->source;
2126 $this->billed = $obj->billed;
2127 $this->note = $obj->note_private; // deprecated
2128 $this->note_private = $obj->note_private;
2129 $this->note_public = $obj->note_public;
2130 $this->model_pdf = $obj->model_pdf;
2131 $this->last_main_doc = $obj->last_main_doc;
2132 $this->mode_reglement_id = $obj->fk_mode_reglement;
2133 $this->mode_reglement_code = $obj->mode_reglement_code;
2134 $this->mode_reglement = $obj->mode_reglement_libelle;
2135 $this->cond_reglement_id = $obj->fk_cond_reglement;
2136 $this->cond_reglement_code = $obj->cond_reglement_code;
2137 $this->cond_reglement = $obj->cond_reglement_libelle;
2138 $this->cond_reglement_label = $obj->cond_reglement_libelle;
2139 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2140 $this->deposit_percent = $obj->deposit_percent;
2141 $this->fk_account = $obj->fk_account;
2142 $this->availability_id = $obj->fk_availability;
2143 $this->availability_code = $obj->availability_code;
2144 $this->availability = $obj->availability_label;
2145 $this->demand_reason_id = $obj->fk_input_reason;
2146 $this->demand_reason_code = $obj->demand_reason_code;
2147 $this->delivery_date = $this->db->jdate($obj->delivery_date);
2148 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2149 $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
2150 $this->fk_delivery_address = $obj->fk_delivery_address;
2151 $this->module_source = $obj->module_source;
2152 $this->pos_source = $obj->pos_source;
2153
2154 //Incoterms
2155 $this->fk_incoterms = $obj->fk_incoterms;
2156 $this->location_incoterms = $obj->location_incoterms;
2157 $this->label_incoterms = $obj->label_incoterms;
2158
2159 // Multicurrency
2160 $this->fk_multicurrency = $obj->fk_multicurrency;
2161 $this->multicurrency_code = $obj->multicurrency_code;
2162 $this->multicurrency_tx = $obj->multicurrency_tx;
2163 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2164 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2165 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2166
2167 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2168
2169 $this->lines = array();
2170
2171 // Retrieve all extrafield
2172 // fetch optionals attributes and labels
2173 $this->fetch_optionals();
2174
2175 $this->db->free($result);
2176
2177 // Lines
2178 $result = $this->fetch_lines();
2179 if ($result < 0) {
2180 return -3;
2181 }
2182 return 1;
2183 } else {
2184 $this->error = 'Order with id '.$id.' not found sql='.$sql;
2185 return 0;
2186 }
2187 } else {
2188 $this->error = $this->db->error();
2189 return -1;
2190 }
2191 }
2192
2193
2194 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2201 public function insert_discount($idremise)
2202 {
2203 // phpcs:enable
2204 global $langs;
2205
2206 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2207 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2208
2209 $this->db->begin();
2210
2211 $remise = new DiscountAbsolute($this->db);
2212 $result = $remise->fetch($idremise);
2213
2214 if ($result > 0) {
2215 if ($remise->fk_facture) { // Protection against multiple submissions
2216 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2217 $this->db->rollback();
2218 return -5;
2219 }
2220
2221 $line = new OrderLine($this->db);
2222
2223 $line->fk_commande = $this->id;
2224 $line->fk_remise_except = $remise->id;
2225 $line->desc = $remise->description; // Description for the order line
2226 $line->vat_src_code = $remise->vat_src_code;
2227 $line->tva_tx = $remise->tva_tx;
2228 $line->localtax1_tx = $remise->localtax1_tx;
2229 $line->localtax1_type = $remise->localtax1_type;
2230 $line->localtax2_tx = $remise->localtax1_tx;
2231 $line->localtax2_type = $remise->localtax1_type;
2232 $line->subprice = -(float) $remise->amount_ht;
2233 $line->price = -(float) $remise->amount_ht;
2234 $line->fk_product = 0; // Predefined Product ID
2235 $line->qty = 1;
2236 $line->remise_percent = 0;
2237 $line->rang = -1;
2238 $line->info_bits = 2;
2239
2240 $line->total_ht = -(float) $remise->amount_ht;
2241 $line->total_tva = -(float) $remise->amount_tva;
2242 $line->total_ttc = -(float) $remise->amount_ttc;
2243 $line->total_localtax1 = -(float) $remise->total_localtax1;
2244 $line->total_localtax2 = -(float) $remise->total_localtax2;
2245
2246 $result = $line->insert();
2247 if ($result > 0) {
2248 $result = $this->update_price(1);
2249 if ($result > 0) {
2250 $this->db->commit();
2251 return 1;
2252 } else {
2253 $this->db->rollback();
2254 return -1;
2255 }
2256 } else {
2257 $this->setErrorsFromObject($line);
2258 $this->db->rollback();
2259 return -2;
2260 }
2261 } else {
2262 $this->db->rollback();
2263 return -2;
2264 }
2265 }
2266
2267
2268 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2276 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2277 {
2278 // phpcs:enable
2279 $this->lines = array();
2280
2281 $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,';
2282 $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,';
2283 $sql .= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
2284 $sql .= ' l.fk_unit, l.extraparams,';
2285 $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,';
2286 $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,';
2287 $sql .= ' p.customcode, p.fk_country as country_id, c.code as country_code,';
2288 $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units, p.packaging';
2289 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as l';
2290 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
2291 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON c.rowid = p.fk_country';
2292 $sql .= ' WHERE l.fk_commande = '.((int) $this->id);
2293 if ($only_product) {
2294 $sql .= ' AND p.fk_product_type = 0';
2295 }
2296 $sql .= ' ORDER BY l.rang, l.rowid';
2297
2298 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
2299 $result = $this->db->query($sql);
2300 if ($result) {
2301 $num = $this->db->num_rows($result);
2302
2303 $i = 0;
2304 while ($i < $num) {
2305 $objp = $this->db->fetch_object($result);
2306
2307 $line = new OrderLine($this->db);
2308
2309 $line->rowid = $objp->rowid;
2310 $line->id = $objp->rowid;
2311 $line->fk_commande = $objp->fk_commande;
2312 $line->commande_id = $objp->fk_commande;
2313 $line->label = $objp->custom_label;
2314 $line->desc = $objp->description;
2315 $line->description = $objp->description; // Description line
2316 $line->product_type = $objp->product_type;
2317 $line->qty = $objp->qty;
2318 $line->ref_ext = $objp->ref_ext;
2319
2320 $line->vat_src_code = $objp->vat_src_code;
2321 $line->tva_tx = $objp->tva_tx;
2322 $line->localtax1_tx = $objp->localtax1_tx;
2323 $line->localtax2_tx = $objp->localtax2_tx;
2324 $line->localtax1_type = $objp->localtax1_type;
2325 $line->localtax2_type = $objp->localtax2_type;
2326 $line->total_ht = $objp->total_ht;
2327 $line->total_ttc = $objp->total_ttc;
2328 $line->total_tva = $objp->total_tva;
2329 $line->total_localtax1 = $objp->total_localtax1;
2330 $line->total_localtax2 = $objp->total_localtax2;
2331 $line->subprice = (float) $objp->subprice;
2332 $line->subprice_ttc = (float) $objp->subprice_ttc;
2333 $line->fk_remise_except = $objp->fk_remise_except;
2334 $line->remise_percent = $objp->remise_percent;
2335 $line->price = $objp->price;
2336 $line->fk_product = $objp->fk_product;
2337 $line->fk_fournprice = $objp->fk_fournprice;
2338 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2339 $line->pa_ht = $marginInfos[0];
2340 $line->marge_tx = $marginInfos[1];
2341 $line->marque_tx = $marginInfos[2];
2342 $line->rang = $objp->rang;
2343 $line->info_bits = $objp->info_bits;
2344 $line->special_code = $objp->special_code;
2345 $line->fk_parent_line = $objp->fk_parent_line;
2346
2347 $line->ref = $objp->product_ref;
2348 $line->libelle = $objp->product_label;
2349
2350 $line->product_ref = $objp->product_ref;
2351 $line->product_label = $objp->product_label;
2352 $line->product_tosell = $objp->product_tosell;
2353 $line->product_tobuy = $objp->product_tobuy;
2354 $line->product_desc = $objp->product_desc;
2355 $line->product_tobatch = $objp->product_tobatch;
2356 $line->product_barcode = $objp->product_barcode;
2357 $line->product_custom_code = $objp->customcode;
2358 $line->product_custom_country_id = $objp->country_id;
2359 $line->product_custom_country_code = $objp->country_code;
2360
2361 $line->fk_product_type = $objp->fk_product_type; // Product or service
2362 $line->fk_unit = $objp->fk_unit;
2363
2364 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2365
2366 $line->weight = $objp->weight;
2367 $line->weight_units = $objp->weight_units;
2368 $line->volume = $objp->volume;
2369 $line->volume_units = $objp->volume_units;
2370 $line->packaging = $objp->packaging;
2371
2372 $line->date_start = $this->db->jdate($objp->date_start);
2373 $line->date_end = $this->db->jdate($objp->date_end);
2374
2375 // Multicurrency
2376 $line->fk_multicurrency = $objp->fk_multicurrency;
2377 $line->multicurrency_code = $objp->multicurrency_code;
2378 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2379 $line->multicurrency_subprice_ttc = $objp->multicurrency_subprice_ttc;
2380 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2381 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2382 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2383
2384 $line->fetch_optionals();
2385
2386 // multilangs
2387 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2388 $tmpproduct = new Product($this->db);
2389 $tmpproduct->fetch($objp->fk_product);
2390 $tmpproduct->getMultiLangs();
2391
2392 $line->multilangs = $tmpproduct->multilangs;
2393 }
2394
2395 $this->lines[$i] = $line;
2396
2397 $i++;
2398 }
2399
2400 $this->db->free($result);
2401
2402 return 1;
2403 } else {
2404 $this->error = $this->db->error();
2405 return -3;
2406 }
2407 }
2408
2409
2415 public function getNbOfProductsLines()
2416 {
2417 $nb = 0;
2418 foreach ($this->lines as $line) {
2419 if ($line->product_type == 0) {
2420 $nb++;
2421 }
2422 }
2423 return $nb;
2424 }
2425
2431 public function getNbOfServicesLines()
2432 {
2433 $nb = 0;
2434 foreach ($this->lines as $line) {
2435 if ($line->product_type == 1) {
2436 $nb++;
2437 }
2438 }
2439 return $nb;
2440 }
2441
2447 public function getNbOfShipments()
2448 {
2449 $nb = 0;
2450
2451 $sql = 'SELECT COUNT(DISTINCT ed.fk_expedition) as nb';
2452 $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
2453 $sql .= ' '.MAIN_DB_PREFIX.$this->table_element_line.' as cd';
2454 $sql .= ' WHERE';
2455 $sql .= ' ed.fk_elementdet = cd.rowid';
2456 $sql .= ' AND cd.fk_commande = '.((int) $this->id);
2457 //print $sql;
2458
2459 dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG);
2460 $resql = $this->db->query($sql);
2461 if ($resql) {
2462 $obj = $this->db->fetch_object($resql);
2463 if ($obj) {
2464 $nb = (int) $obj->nb;
2465 }
2466
2467 $this->db->free($resql);
2468 return $nb;
2469 } else {
2470 $this->error = $this->db->lasterror();
2471 return -1;
2472 }
2473 }
2474
2483 public function loadExpeditions($filtre_statut = -1, $fk_product = 0)
2484 {
2485 $this->expeditions = array();
2486
2487 $sql = 'SELECT cd.rowid, cd.fk_product,';
2488 $sql .= ' sum(ed.qty) as qty';
2489 $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
2490 if ($filtre_statut >= 0) {
2491 $sql .= ' '.MAIN_DB_PREFIX.'expedition as e,';
2492 }
2493 $sql .= ' '.MAIN_DB_PREFIX.$this->table_element_line.' as cd';
2494 $sql .= ' WHERE';
2495 if ($filtre_statut >= 0) {
2496 $sql .= ' ed.fk_expedition = e.rowid AND';
2497 }
2498 $sql .= ' ed.fk_elementdet = cd.rowid';
2499 $sql .= ' AND cd.fk_commande = '.((int) $this->id);
2500 if ($fk_product > 0) {
2501 $sql .= ' AND cd.fk_product = '.((int) $fk_product);
2502 }
2503 if ($filtre_statut >= 0) {
2504 $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut);
2505 }
2506 $sql .= ' GROUP BY cd.rowid, cd.fk_product';
2507 //print $sql;
2508
2509 dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG);
2510 $resql = $this->db->query($sql);
2511 if ($resql) {
2512 $num = $this->db->num_rows($resql);
2513 $i = 0;
2514 while ($i < $num) {
2515 $obj = $this->db->fetch_object($resql);
2516 $this->expeditions[$obj->rowid] = $obj->qty;
2517 $i++;
2518 }
2519 $this->db->free($resql);
2520 return $num;
2521 } else {
2522 $this->error = $this->db->lasterror();
2523 return -1;
2524 }
2525 }
2526
2532 public function countNbOfShipments()
2533 {
2534 $sql = 'SELECT count(*)';
2535 $sql .= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
2536 $sql .= ', '.MAIN_DB_PREFIX.'element_element as el';
2537 $sql .= ' WHERE el.fk_source = '.((int) $this->id);
2538 $sql .= " AND el.sourcetype = 'commande'";
2539 $sql .= " AND el.fk_target = e.rowid";
2540 $sql .= " AND el.targettype = 'shipping'";
2541
2542 $resql = $this->db->query($sql);
2543 if ($resql) {
2544 $row = $this->db->fetch_row($resql);
2545 return $row[0];
2546 } else {
2547 dol_print_error($this->db);
2548 }
2549
2550 return 0;
2551 }
2552
2561 public function deleteLine($user = null, $lineid = 0, $id = 0)
2562 {
2563 if ($this->status == self::STATUS_DRAFT) {
2564 $this->db->begin();
2565
2566 // Delete line
2567 $line = new OrderLine($this->db);
2568
2569 $line->context = $this->context;
2570
2571 // Load data
2572 $line->fetch($lineid);
2573
2574 if ($id <= 0) {
2575 $id = $this->id;
2576 }
2577 if ($id > 0 && (int) $line->fk_commande !== (int) $id) {
2578 $this->db->rollback();
2579 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2580 return -1;
2581 }
2582
2583 // Memorize previous line for triggers
2584 $staticline = clone $line;
2585 $line->oldline = $staticline;
2586
2587 if ($line->delete($user) > 0) {
2588 $result = $this->update_price(1);
2589
2590 if ($result > 0) {
2591 $this->db->commit();
2592 return 1;
2593 } else {
2594 $this->db->rollback();
2595 $this->error = $this->db->lasterror();
2596 return -1;
2597 }
2598 } else {
2599 $this->db->rollback();
2600 $this->setErrorsFromObject($line);
2601 return -1;
2602 }
2603 } else {
2604 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
2605 return -1;
2606 }
2607 }
2608
2609 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2620 public function set_remise($user, $remise, $notrigger = 0)
2621 {
2622 // phpcs:enable
2623 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
2624 // @phan-suppress-next-line PhanDeprecatedFunction
2625 return $this->setDiscount($user, $remise, $notrigger);
2626 }
2627
2636 public function setDiscount($user, $remise, $notrigger = 0)
2637 {
2638 $remise = trim((string) $remise) ? trim((string) $remise) : 0;
2639
2640 if ($user->hasRight('commande', 'creer')) {
2641 $error = 0;
2642
2643 $this->db->begin();
2644
2645 $remise = price2num($remise, 2);
2646
2647 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2648 $sql .= ' SET remise_percent = '.((float) $remise);
2649 $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_DRAFT);
2650
2651 dol_syslog(__METHOD__, LOG_DEBUG);
2652 $resql = $this->db->query($sql);
2653 if (!$resql) {
2654 $this->errors[] = $this->db->error();
2655 $error++;
2656 }
2657
2658 if (!$error) {
2659 $this->oldcopy = clone $this;
2660 $this->remise_percent = $remise;
2661 $this->update_price(1);
2662 }
2663
2664 if (!$notrigger && empty($error)) {
2665 // Call trigger
2666 $result = $this->call_trigger('ORDER_MODIFY', $user);
2667 if ($result < 0) {
2668 $error++;
2669 }
2670 // End call triggers
2671 }
2672
2673 if (!$error) {
2674 $this->db->commit();
2675 return 1;
2676 } else {
2677 foreach ($this->errors as $errmsg) {
2678 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2679 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2680 }
2681 $this->db->rollback();
2682 return -1 * $error;
2683 }
2684 }
2685
2686 return 0;
2687 }
2688
2689
2690 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2699 public function set_date($user, $date, $notrigger = 0)
2700 {
2701 // phpcs:enable
2702 if ($user->hasRight('commande', 'creer')) {
2703 $error = 0;
2704
2705 $this->db->begin();
2706
2707 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2708 $sql .= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
2709 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".((int) self::STATUS_DRAFT);
2710
2711 dol_syslog(__METHOD__, LOG_DEBUG);
2712 $resql = $this->db->query($sql);
2713 if (!$resql) {
2714 $this->errors[] = $this->db->error();
2715 $error++;
2716 }
2717
2718 if (!$error) {
2719 $this->oldcopy = clone $this;
2720 $this->date = $date;
2721 }
2722
2723 if (!$notrigger && empty($error)) {
2724 // Call trigger
2725 $result = $this->call_trigger('ORDER_MODIFY', $user);
2726 if ($result < 0) {
2727 $error++;
2728 }
2729 // End call triggers
2730 }
2731
2732 if (!$error) {
2733 $this->db->commit();
2734 return 1;
2735 } else {
2736 foreach ($this->errors as $errmsg) {
2737 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2738 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2739 }
2740 $this->db->rollback();
2741 return -1 * $error;
2742 }
2743 } else {
2744 return -2;
2745 }
2746 }
2747
2748 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2758 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2759 {
2760 // phpcs:enable
2761 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2762 }
2763
2772 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2773 {
2774 if ($user->hasRight('commande', 'creer')) {
2775 $error = 0;
2776
2777 $this->db->begin();
2778
2779 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2780 $sql .= " SET date_livraison = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2781 $sql .= " WHERE rowid = ".((int) $this->id);
2782
2783 dol_syslog(__METHOD__, LOG_DEBUG);
2784 $resql = $this->db->query($sql);
2785 if (!$resql) {
2786 $this->errors[] = $this->db->error();
2787 $error++;
2788 }
2789
2790 if (!$error) {
2791 $this->oldcopy = clone $this;
2792 $this->delivery_date = $delivery_date;
2793 }
2794
2795 if (!$notrigger && empty($error)) {
2796 // Call trigger
2797 $result = $this->call_trigger('ORDER_MODIFY', $user);
2798 if ($result < 0) {
2799 $error++;
2800 }
2801 // End call triggers
2802 }
2803
2804 if (!$error) {
2805 $this->db->commit();
2806 return 1;
2807 } else {
2808 foreach ($this->errors as $errmsg) {
2809 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2810 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2811 }
2812 $this->db->rollback();
2813 return -1 * $error;
2814 }
2815 } else {
2816 return -2;
2817 }
2818 }
2819
2820 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2834 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'c.date_commande', $sortorder = 'DESC')
2835 {
2836 // phpcs:enable
2837 global $user;
2838
2839 $ga = array();
2840
2841 $sql = "SELECT s.rowid, s.nom as name, s.client,";
2842 $sql .= " c.rowid as cid, c.ref";
2843 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2844 $sql .= ", sc.fk_soc, sc.fk_user";
2845 }
2846 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX.$this->table_element." as c";
2847 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2848 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2849 }
2850 $sql .= " WHERE c.entity IN (".getEntity('commande').")";
2851 $sql .= " AND c.fk_soc = s.rowid";
2852 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2853 $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2854 }
2855 if ($socid) {
2856 $sql .= " AND s.rowid = ".((int) $socid);
2857 }
2858 if ($draft) {
2859 $sql .= " AND c.fk_statut = ".self::STATUS_DRAFT;
2860 }
2861 if (is_object($excluser)) {
2862 $sql .= " AND c.fk_user_author <> ".((int) $excluser->id);
2863 }
2864 $sql .= $this->db->order($sortfield, $sortorder);
2865 $sql .= $this->db->plimit($limit, $offset);
2866
2867 $result = $this->db->query($sql);
2868 if ($result) {
2869 $numc = $this->db->num_rows($result);
2870 if ($numc) {
2871 $i = 0;
2872 while ($i < $numc) {
2873 $obj = $this->db->fetch_object($result);
2874
2875 if ($shortlist == 1) {
2876 $ga[$obj->cid] = $obj->ref;
2877 } elseif ($shortlist == 2) {
2878 $ga[$obj->cid] = $obj->ref.' ('.$obj->name.')';
2879 } else {
2880 $ga[$i]['id'] = $obj->cid;
2881 $ga[$i]['ref'] = $obj->ref;
2882 $ga[$i]['name'] = $obj->name;
2883 }
2884 $i++;
2885 }
2886 }
2887 return $ga;
2888 } else {
2889 dol_print_error($this->db);
2890 return -1;
2891 }
2892 }
2893
2901 public function availability($availability_id, $notrigger = 0)
2902 {
2903 global $user;
2904
2905 dol_syslog('Commande::availability('.$availability_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_availability = '.((int) $availability_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->availability_id = $availability_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 = 'Command 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
2964 public function demand_reason($demand_reason_id, $notrigger = 0)
2965 {
2966 // phpcs:enable
2967 global $user;
2968
2969 dol_syslog('Commande::demand_reason('.$demand_reason_id.')');
2970 if ($this->status >= self::STATUS_DRAFT) {
2971 $error = 0;
2972
2973 $this->db->begin();
2974
2975 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2976 $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
2977 $sql .= ' WHERE rowid='.((int) $this->id);
2978
2979 dol_syslog(__METHOD__, LOG_DEBUG);
2980 $resql = $this->db->query($sql);
2981 if (!$resql) {
2982 $this->errors[] = $this->db->error();
2983 $error++;
2984 }
2985
2986 if (!$error) {
2987 $this->oldcopy = clone $this;
2988 $this->demand_reason_id = $demand_reason_id;
2989 }
2990
2991 if (!$notrigger && empty($error)) {
2992 // Call trigger
2993 $result = $this->call_trigger('ORDER_MODIFY', $user);
2994 if ($result < 0) {
2995 $error++;
2996 }
2997 // End call triggers
2998 }
2999
3000 if (!$error) {
3001 $this->db->commit();
3002 return 1;
3003 } else {
3004 foreach ($this->errors as $errmsg) {
3005 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3006 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3007 }
3008 $this->db->rollback();
3009 return -1 * $error;
3010 }
3011 } else {
3012 $error_str = 'order status do not meet requirement '.$this->status;
3013 dol_syslog(__METHOD__.$error_str, LOG_ERR);
3014 $this->error = $error_str;
3015 $this->errors[] = $this->error;
3016 return -2;
3017 }
3018 }
3019
3032 public function isRefClientAlreadyUsed(string $ref_client, int $socid, int $excludeid = 0): int
3033 {
3034 global $langs;
3035
3036 if (getDolGlobalInt('ORDER_ALLOW_DUPLICATE_REF_CLIENT')) {
3037 return 0;
3038 }
3039
3040 $ref_client = trim($ref_client);
3041 if ($ref_client === '' || $socid <= 0) {
3042 return 0;
3043 }
3044
3045 $sql = "SELECT ref FROM ".$this->db->prefix()."commande";
3046 $sql .= " WHERE ref_client = '".$this->db->escape($ref_client)."'";
3047 $sql .= " AND fk_soc = ".((int) $socid);
3048 $sql .= " AND entity IN (".getEntity('commande').")";
3049 if ($excludeid > 0) {
3050 $sql .= " AND rowid <> ".((int) $excludeid);
3051 }
3052 $sql .= " ORDER BY rowid ASC";
3053 $sql .= $this->db->plimit(1);
3054
3055 dol_syslog(get_class($this)."::isRefClientAlreadyUsed", LOG_DEBUG);
3056 $resql = $this->db->query($sql);
3057 if (!$resql) {
3058 $this->error = $this->db->lasterror();
3059 $this->errors[] = $this->error;
3060 dol_syslog(get_class($this)."::isRefClientAlreadyUsed ".$this->error, LOG_ERR);
3061 return -1;
3062 }
3063
3064 $obj = $this->db->fetch_object($resql);
3065 $this->db->free($resql);
3066
3067 if (!is_object($obj)) {
3068 return 0;
3069 }
3070
3071 $langs->load('orders');
3072 $this->error = $langs->trans('ErrorRefCustomerAlreadyUsedOnOrder', $ref_client, $obj->ref);
3073 $this->errors[] = $this->error;
3074 dol_syslog(get_class($this)."::isRefClientAlreadyUsed ref_client=".$ref_client." already used by ".$obj->ref, LOG_WARNING);
3075
3076 return 1;
3077 }
3078
3079 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3088 public function set_ref_client($user, $ref_client, $notrigger = 0)
3089 {
3090 // phpcs:enable
3091 if ($user->hasRight('commande', 'creer')) {
3092 $error = 0;
3093
3094 if ($this->isRefClientAlreadyUsed((string) $ref_client, (int) $this->socid, (int) $this->id) != 0) {
3095 return -1;
3096 }
3097
3098 $this->db->begin();
3099
3100 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
3101 $sql .= ' ref_client = '.(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
3102 $sql .= ' WHERE rowid = '.((int) $this->id);
3103
3104 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
3105 $resql = $this->db->query($sql);
3106 if (!$resql) {
3107 $this->errors[] = $this->db->error();
3108 $error++;
3109 }
3110
3111 if (!$error) {
3112 $this->oldcopy = clone $this;
3113 $this->ref_client = $ref_client;
3114 $this->ref_customer = $ref_client;
3115 }
3116
3117 if (!$notrigger && empty($error)) {
3118 // Call trigger
3119 $result = $this->call_trigger('ORDER_MODIFY', $user);
3120 if ($result < 0) {
3121 $error++;
3122 }
3123 // End call triggers
3124 }
3125 if (!$error) {
3126 $this->db->commit();
3127 return 1;
3128 } else {
3129 foreach ($this->errors as $errmsg) {
3130 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3131 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3132 }
3133 $this->db->rollback();
3134 return -1 * $error;
3135 }
3136 } else {
3137 return -1;
3138 }
3139 }
3140
3148 public function classifyBilled(User $user, $notrigger = 0)
3149 {
3150 $error = 0;
3151
3152 if ($this->billed) {
3153 return 0;
3154 }
3155
3156 $this->db->begin();
3157
3158 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET facture = 1';
3159 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
3160
3161 dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
3162 if ($this->db->query($sql)) {
3163 $this->oldcopy = clone $this;
3164 $this->billed = 1;
3165
3166 if (!$notrigger && empty($error)) {
3167 // Call trigger
3168 $result = $this->call_trigger('ORDER_CLASSIFY_BILLED', $user);
3169 if ($result < 0) {
3170 $error++;
3171 }
3172 // End call triggers
3173 }
3174
3175 if (!$error) {
3176 $this->db->commit();
3177 return 1;
3178 } else {
3179 foreach ($this->errors as $errmsg) {
3180 dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR);
3181 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3182 }
3183 $this->db->rollback();
3184 return -1 * $error;
3185 }
3186 } else {
3187 $this->error = $this->db->error();
3188 $this->db->rollback();
3189 return -1;
3190 }
3191 }
3192
3200 public function classifyUnBilled(User $user, $notrigger = 0)
3201 {
3202 $error = 0;
3203
3204 $this->db->begin();
3205
3206 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET facture = 0';
3207 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
3208
3209 dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG);
3210 if ($this->db->query($sql)) {
3211 $this->oldcopy = clone $this;
3212 $this->billed = 1;
3213
3214 if (!$notrigger && empty($error)) {
3215 // Call trigger
3216 $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user);
3217 if ($result < 0) {
3218 $error++;
3219 }
3220 // End call triggers
3221 }
3222
3223 if (!$error) {
3224 $this->billed = 0;
3225
3226 $this->db->commit();
3227 return 1;
3228 } else {
3229 foreach ($this->errors as $errmsg) {
3230 dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR);
3231 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3232 }
3233 $this->db->rollback();
3234 return -1 * $error;
3235 }
3236 } else {
3237 $this->error = $this->db->error();
3238 $this->db->rollback();
3239 return -1;
3240 }
3241 }
3242
3243
3274 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)
3275 {
3276 global $mysoc, $langs, $user;
3277
3278 if (!$this->isLineOfObject($rowid)) {
3279 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
3280 return -1;
3281 }
3282
3283 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");
3284 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3285
3286 if ($this->status == Commande::STATUS_DRAFT) {
3287 // Clean parameters
3288 if (empty($qty)) {
3289 $qty = 0;
3290 }
3291 if (empty($info_bits)) {
3292 $info_bits = 0;
3293 }
3294 if (empty($txtva)) {
3295 $txtva = 0;
3296 }
3297 if (empty($txlocaltax1)) {
3298 $txlocaltax1 = 0;
3299 }
3300 if (empty($txlocaltax2)) {
3301 $txlocaltax2 = 0;
3302 }
3303 if (empty($remise_percent)) {
3304 $remise_percent = 0;
3305 }
3306 if (empty($qty) && empty($special_code)) {
3307 $special_code = 3; // Set option tag
3308 }
3309 if (!empty($qty) && $special_code == 3) {
3310 $special_code = 0; // Remove option tag
3311 }
3312 if (empty($ref_ext)) {
3313 $ref_ext = '';
3314 }
3315
3316 if ($date_start && $date_end && $date_start > $date_end) {
3317 $langs->load("errors");
3318 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3319 return -1;
3320 }
3321
3322 $remise_percent = (float) price2num($remise_percent);
3323 $qty = (float) price2num($qty);
3324 $pu = price2num($pu);
3325 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
3326 $pu_ht_devise = price2num($pu_ht_devise);
3327 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
3328 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3329 }
3330 $txlocaltax1 = (float) price2num($txlocaltax1);
3331 $txlocaltax2 = (float) price2num($txlocaltax2);
3332
3333 $this->db->begin();
3334
3335 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
3336 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
3337 // and this is done at the line level, which has its own VAT rate
3338
3339 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3340
3341 // Clean vat code
3342 $vat_src_code = '';
3343 $reg = array();
3344 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3345 $vat_src_code = $reg[1];
3346 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3347 }
3348
3349 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
3350 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
3351 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
3352 $tmpline = new OrderLine($this->db);
3353 if ($tmpline->fetch($rowid) > 0) {
3354 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
3355 if ($newqty != $qty) {
3356 $qty = $newqty;
3357 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
3358 }
3359 }
3360 }
3361
3362 $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, $this->multicurrency_code);
3363
3364 $total_ht = $tabprice[0];
3365 $total_tva = $tabprice[1];
3366 $total_ttc = $tabprice[2];
3367 $total_localtax1 = $tabprice[9];
3368 $total_localtax2 = $tabprice[10];
3369 $pu_ht = $tabprice[3];
3370 $pu_tva = $tabprice[4];
3371 $pu_ttc = $tabprice[5];
3372
3373 // MultiCurrency
3374 $multicurrency_total_ht = $tabprice[16];
3375 $multicurrency_total_tva = $tabprice[17];
3376 $multicurrency_total_ttc = $tabprice[18];
3377 $pu_ht_devise = $tabprice[19];
3378
3379 // Fetch current line from the database and then clone the object and set it in $oldline property
3380 $line = new OrderLine($this->db);
3381 $line->fetch($rowid);
3382 $line->fetch_optionals();
3383
3384 if (!empty($line->fk_product)) {
3385 $product = new Product($this->db);
3386 $result = $product->fetch($line->fk_product);
3387 $product_type = $product->type;
3388
3389 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_ORDER') && $product->isStockManaged()) {
3390 // get real stock
3391 $productChildrenNb = 0;
3392 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
3393 $productChildrenNb = $product->hasFatherOrChild(1);
3394 }
3395 if ($productChildrenNb > 0) {
3396 // compute real stock from each subcomponent
3397 $product_stock = null;
3398 $product->loadStockForVirtualProduct('warehouseopen', $qty);
3399 foreach ($product->stock_warehouse as $componentStockWarehouse) {
3400 if ($product_stock === null) {
3401 $product_stock = $componentStockWarehouse->real;
3402 } else {
3403 $product_stock = min($product_stock, $componentStockWarehouse->real);
3404 }
3405 }
3406 if ($product_stock === null) {
3407 $product_stock = 0;
3408 }
3409 } else {
3410 $product_stock = $product->stock_reel;
3411 }
3412
3413 if ($product_stock < $qty) {
3414 $langs->load("errors");
3415 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', (string) $product->ref);
3416 $this->errors[] = $this->error;
3417
3418 dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
3419
3420 $this->db->rollback();
3422 }
3423 }
3424 }
3425
3426 $staticline = clone $line;
3427
3428 $line->oldline = $staticline;
3429 $this->line = $line;
3430 $this->line->context = $this->context;
3431 $this->line->rang = $rang;
3432
3433 // Reorder if fk_parent_line change
3434 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
3435 $rangmax = $this->line_max($fk_parent_line);
3436 $this->line->rang = $rangmax + 1;
3437 }
3438
3439
3440 $this->line->id = $rowid;
3441 $this->line->label = $label;
3442 $this->line->desc = $desc;
3443 $this->line->qty = $qty;
3444 $this->line->ref_ext = $ref_ext;
3445
3446 $this->line->vat_src_code = $vat_src_code;
3447 $this->line->tva_tx = $txtva;
3448 $this->line->localtax1_tx = $txlocaltax1;
3449 $this->line->localtax2_tx = $txlocaltax2;
3450 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3451 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3452 $this->line->remise_percent = $remise_percent;
3453 $this->line->subprice = (float) $pu_ht;
3454 // Persist the original entry mode of the line so a no-op edit can preserve it later.
3455 $this->line->subprice_ttc = ($price_base_type === 'TTC') ? (float) $pu_ttc : 0;
3456 $this->line->info_bits = $info_bits;
3457 $this->line->special_code = $special_code;
3458 $this->line->total_ht = (float) $total_ht;
3459 $this->line->total_tva = (float) $total_tva;
3460 $this->line->total_localtax1 = (float) $total_localtax1;
3461 $this->line->total_localtax2 = (float) $total_localtax2;
3462 $this->line->total_ttc = (float) $total_ttc;
3463 $this->line->date_start = $date_start;
3464 $this->line->date_end = $date_end;
3465 $this->line->product_type = $type;
3466 $this->line->fk_parent_line = $fk_parent_line;
3467 $this->line->skip_update_total = $skip_update_total;
3468 $this->line->fk_unit = $fk_unit;
3469
3470 $this->line->fk_fournprice = $fk_fournprice;
3471 $this->line->pa_ht = $pa_ht;
3472
3473 // Multicurrency
3474 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
3475 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
3476 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
3477 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
3478
3479 if (is_array($array_options) && count($array_options) > 0) {
3480 // We replace values in this->line->array_options only for entries defined into $array_options
3481 foreach ($array_options as $key => $value) {
3482 $this->line->array_options[$key] = $array_options[$key];
3483 }
3484 }
3485
3486 $result = $this->line->update($user, $notrigger);
3487 if ($result > 0) {
3488 // Reorder if child line
3489 if (!empty($fk_parent_line)) {
3490 $this->line_order(true, 'DESC');
3491 }
3492
3493 // Mise a jour info denormalisees
3494 $this->update_price(1, 'auto');
3495
3496 $this->db->commit();
3497 return $result;
3498 } else {
3499 $this->setErrorsFromObject($this->line);
3500
3501 $this->db->rollback();
3502 return -1;
3503 }
3504 } else {
3505 $this->error = get_class($this)."::updateline Order status makes operation forbidden";
3506 $this->errors = array('OrderStatusMakeOperationForbidden');
3507 return -2;
3508 }
3509 }
3510
3518 public function update(User $user, $notrigger = 0)
3519 {
3520 $error = 0;
3521
3522 // Clean parameters
3523 if (isset($this->ref)) {
3524 $this->ref = trim($this->ref);
3525 }
3526 if (isset($this->ref_client)) {
3527 $this->ref_client = trim($this->ref_client);
3528 }
3529 if (isset($this->ref_customer)) {
3530 $this->ref_customer = trim($this->ref_customer);
3531 }
3532 if (isset($this->note) || isset($this->note_private)) {
3533 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
3534 }
3535 if (isset($this->note_public)) {
3536 $this->note_public = trim($this->note_public);
3537 }
3538 if (isset($this->model_pdf)) {
3539 $this->model_pdf = trim($this->model_pdf);
3540 }
3541 if (isset($this->import_key)) {
3542 $this->import_key = trim($this->import_key);
3543 }
3544 $delivery_date = $this->delivery_date;
3545
3546 // Check parameters
3547 // Put here code to add control on parameters values
3548 if ($this->isRefClientAlreadyUsed((string) $this->ref_client, (int) $this->socid, (int) $this->id) != 0) {
3549 return -1;
3550 }
3551
3552 // Update request
3553 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
3554
3555 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
3556 $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
3557 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
3558 $sql .= " fk_soc=".(isset($this->socid) ? ((int) $this->socid) : "null").",";
3559 $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
3560 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
3561
3562 $sql .= " total_tva=".(isset($this->total_tva) ? ((float) $this->total_tva) : "null").",";
3563 $sql .= " localtax1=".(isset($this->total_localtax1) ? ((float) $this->total_localtax1) : "null").",";
3564 $sql .= " localtax2=".(isset($this->total_localtax2) ? ((float) $this->total_localtax2) : "null").",";
3565 $sql .= " total_ht=".(isset($this->total_ht) ? ((float) $this->total_ht) : "null").",";
3566 $sql .= " total_ttc=".(isset($this->total_ttc) ? ((float) $this->total_ttc) : "null").",";
3567 $sql .= " fk_statut=".(isset($this->status) ? ((int) $this->status) : "null").",";
3568 $sql .= " fk_user_modif=".(isset($user->id) ? ((int) $user->id) : "null").",";
3569 $sql .= " fk_user_valid=".((isset($this->user_validation_id) && $this->user_validation_id > 0) ? ((int) $this->user_validation_id) : "null").",";
3570 $sql .= " fk_projet=".(isset($this->fk_project) ? ((int) $this->fk_project) : "null").",";
3571 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? ((int) $this->cond_reglement_id) : "null").",";
3572 $sql .= " deposit_percent=".(!empty($this->deposit_percent) ? "'".$this->db->escape((string) $this->deposit_percent)."'" : "null").",";
3573 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? ((int) $this->mode_reglement_id) : "null").",";
3574 $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').",";
3575 $sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? ((int) $this->shipping_method_id) : "null").",";
3576 $sql .= " fk_account=".($this->fk_account > 0 ? ((int) $this->fk_account) : "null").",";
3577 $sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? ((int) $this->demand_reason_id) : "null").",";
3578 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
3579 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
3580 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
3581 $sql .= " fk_warehouse=".($this->warehouse_id > 0 ? ((int) $this->warehouse_id) : "null").",";
3582 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
3583 $sql .= " module_source = ".(isset($this->module_source) ? "'".$this->db->escape($this->module_source)."'" : "null").",";
3584 $sql .= " pos_source = ".(isset($this->pos_source) ? "'".$this->db->escape($this->pos_source)."'" : "null");
3585 $sql .= " WHERE rowid=".((int) $this->id);
3586
3587 $this->db->begin();
3588
3589 dol_syslog(get_class($this)."::update", LOG_DEBUG);
3590 $resql = $this->db->query($sql);
3591 if (!$resql) {
3592 $error++;
3593 $this->errors[] = "Error ".$this->db->lasterror();
3594 }
3595
3596 if (!$error) {
3597 $result = $this->insertExtraFields();
3598 if ($result < 0) {
3599 $error++;
3600 }
3601 }
3602
3603 if (!$error && !$notrigger) {
3604 // Call trigger
3605 $result = $this->call_trigger('ORDER_MODIFY', $user);
3606 if ($result < 0) {
3607 $error++;
3608 }
3609 // End call triggers
3610 }
3611
3612 // Commit or rollback
3613 if ($error) {
3614 foreach ($this->errors as $errmsg) {
3615 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
3616 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3617 }
3618 $this->db->rollback();
3619 return -1 * $error;
3620 } else {
3621 $this->db->commit();
3622 return 1;
3623 }
3624 }
3625
3634 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3635 {
3636 global $conf, $langs;
3637 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3638
3639 $error = 0;
3640
3641 dol_syslog(get_class($this)."::delete ".$this->id, LOG_DEBUG);
3642
3643 $this->db->begin();
3644
3645 if (!$notrigger) {
3646 // Call trigger
3647 $result = $this->call_trigger('ORDER_DELETE', $user);
3648 if ($result < 0) {
3649 $error++;
3650 }
3651 // End call triggers
3652 }
3653
3654 // Test we can delete
3655 if ($this->countNbOfShipments() != 0) {
3656 $this->errors[] = $langs->trans('SomeShipmentExists');
3657 $error++;
3658 }
3659
3660 // Put the stock back, the validation had decreased it. Only when a warehouse was chosen, so
3661 // deleting an order just to clean the database still leaves the stock alone.
3662 // Must run before the lines are removed.
3663 if (!$error && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1 && $this->status != self::STATUS_DRAFT && $idwarehouse > 0) {
3664 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
3665 $langs->load("agenda");
3666
3667 $this->fetch_lines();
3668
3669 $num = count($this->lines);
3670 for ($i = 0; $i < $num; $i++) {
3671 if ($this->lines[$i]->fk_product > 0) {
3672 $mouvP = new MouvementStock($this->db);
3673 $mouvP->origin = &$this;
3674 $mouvP->setOrigin($this->element, $this->id);
3675 // 0 as price so the weighted average value is not changed
3676 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv("OrderDeletedInDolibarr", $this->ref));
3677 if ($result < 0) {
3678 $error++;
3679 $this->error = $mouvP->error;
3680 $this->errors = array_merge($this->errors, $mouvP->errors);
3681 break;
3682 }
3683 }
3684 }
3685 }
3686
3687 // Remove linked categories.
3688 if (!$error) {
3689 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_order";
3690 $sql .= " WHERE fk_order = ".((int) $this->id);
3691
3692 $result = $this->db->query($sql);
3693 if (!$result) {
3694 $error++;
3695 $this->errors[] = $this->db->lasterror();
3696 }
3697 }
3698
3699 // Delete extrafields of lines and lines
3700 if (!$error && !empty($this->table_element_line)) {
3701 $tabletodelete = $this->table_element_line;
3702 $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).")";
3703 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
3704 if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
3705 $error++;
3706 $this->error = $this->db->lasterror();
3707 $this->errors[] = $this->error;
3708 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3709 }
3710 }
3711
3712 if (!$error) {
3713 // Delete linked object
3714 $res = $this->deleteObjectLinked();
3715 if ($res < 0) {
3716 $error++;
3717 }
3718 }
3719
3720 if (!$error) {
3721 // Delete linked contacts
3722 $res = $this->delete_linked_contact();
3723 if ($res < 0) {
3724 $error++;
3725 }
3726 }
3727
3728 // Removed extrafields of object
3729 if (!$error) {
3730 $result = $this->deleteExtraFields();
3731 if ($result < 0) {
3732 $error++;
3733 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3734 }
3735 }
3736
3737 // Delete main record
3738 if (!$error) {
3739 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
3740 $res = $this->db->query($sql);
3741 if (!$res) {
3742 $error++;
3743 $this->error = $this->db->lasterror();
3744 $this->errors[] = $this->error;
3745 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3746 }
3747 }
3748
3749 // Delete record into ECM index and physically
3750 if (!$error) {
3751 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive, old method.
3752 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3753 if (!$res) {
3754 $error++;
3755 }
3756 }
3757
3758 if (!$error) {
3759 // We remove directory
3760 $ref = dol_sanitizeFileName($this->ref);
3761 if ($conf->commande->multidir_output[$this->entity] && !empty($this->ref)) {
3762 $dir = $conf->commande->multidir_output[$this->entity]."/".$ref;
3763 $file = $dir."/".$ref.".pdf";
3764 if (file_exists($file)) {
3765 dol_delete_preview($this);
3766
3767 if (!dol_delete_file($file, 0, 0, 0, $this)) {
3768 $this->error = 'ErrorFailToDeleteFile';
3769 $this->errors[] = $this->error;
3770 $this->db->rollback();
3771 return 0;
3772 }
3773 }
3774 if (file_exists($dir)) {
3775 $res = @dol_delete_dir_recursive($dir);
3776 if (!$res) {
3777 $this->error = 'ErrorFailToDeleteDir';
3778 $this->errors[] = $this->error;
3779 $this->db->rollback();
3780 return 0;
3781 }
3782 }
3783 }
3784 }
3785
3786 if (!$error) {
3787 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
3788 $this->db->commit();
3789 return 1;
3790 } else {
3791 $this->db->rollback();
3792 return -1;
3793 }
3794 }
3795
3796
3797 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3805 public function load_board($user, $mode)
3806 {
3807 // phpcs:enable
3808 global $conf, $langs, $hookmanager;
3809
3810 $clause = " WHERE";
3811
3812 $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut, c.total_ht";
3813 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
3814 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3815 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
3816 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3817 $clause = " AND";
3818 }
3819 $sql .= $clause." c.entity IN (".getEntity('commande').")";
3820 //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
3821 if ($mode == 'toship') {
3822 // An order to ship is an open order (validated or in progress)
3823 $sql .= " AND c.fk_statut IN (" . self::STATUS_VALIDATED . "," . self::STATUS_SHIPMENTONPROCESS . ")";
3824 }
3825 if ($mode == 'tobill') {
3826 // An order to bill is an order not already billed
3827 $sql .= " AND c.fk_statut IN (" . self::STATUS_VALIDATED . "," . self::STATUS_SHIPMENTONPROCESS . ", " . self::STATUS_CLOSED . ") AND c.facture = 0";
3828 }
3829 if ($mode == 'shippedtobill') {
3830 // An order shipped and to bill is a delivered order not already billed
3831 $sql .= " AND c.fk_statut IN (" . self::STATUS_CLOSED . ") AND c.facture = 0";
3832 }
3833 if ($user->socid) {
3834 $sql .= " AND c.fk_soc = ".((int) $user->socid);
3835 }
3836 // Add where from hooks
3837 $parameters = array('socid' => $user->socid);
3838 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3839 $sql .= $hookmanager->resPrint;
3840 $resql = $this->db->query($sql);
3841 if ($resql) {
3842 $delay_warning = 0;
3843 $label = $labelShort = $url = '';
3844 if ($mode == 'toship') {
3845 $delay_warning = $conf->commande->client->warning_delay / 60 / 60 / 24;
3846 $url = DOL_URL_ROOT.'/commande/list.php?search_status=-2&mainmenu=commercial&leftmenu=orders';
3847 $label = $langs->transnoentitiesnoconv("OrdersToProcess");
3848 $labelShort = $langs->transnoentitiesnoconv("Opened");
3849 }
3850 if ($mode == 'tobill') {
3851 $url = DOL_URL_ROOT.'/commande/list.php?search_status=-3&search_billed=0&mainmenu=commercial&leftmenu=orders';
3852 $label = $langs->trans("OrdersToBill"); // We set here bill but may be billed or ordered
3853 $labelShort = $langs->trans("ToBill");
3854 }
3855 if ($mode == 'shippedtobill') {
3856 $url = DOL_URL_ROOT.'/commande/list.php?search_status=3&search_billed=0&mainmenu=commercial&leftmenu=orders';
3857 $label = $langs->trans("OrdersToBill"); // We set here bill but may be billed or ordered
3858 $labelShort = $langs->trans("StatusOrderDelivered").' '.$langs->trans("and").' '.$langs->trans("ToBill");
3859 }
3860
3861 $response = new WorkboardResponse();
3862
3863 $response->warning_delay = $delay_warning;
3864 $response->label = $label;
3865 $response->labelShort = $labelShort;
3866 $response->url = $url;
3867 $response->url_late = DOL_URL_ROOT.'/commande/list.php?search_option=late&mainmenu=commercial&leftmenu=orders';
3868 $response->img = img_object('', "order");
3869
3870 $generic_commande = new Commande($this->db);
3871
3872 while ($obj = $this->db->fetch_object($resql)) {
3873 $response->nbtodo++;
3874 $response->total += $obj->total_ht;
3875
3876 $generic_commande->status = $obj->fk_statut;
3877 $generic_commande->date = $this->db->jdate($obj->date_commande);
3878 $generic_commande->delivery_date = $this->db->jdate($obj->delivery_date);
3879
3880 if ($mode == 'toship' && $generic_commande->hasDelay()) {
3881 $response->nbtodolate++;
3882 }
3883 }
3884
3885 return $response;
3886 } else {
3887 $this->error = $this->db->error();
3888 return -1;
3889 }
3890 }
3891
3897 public function getLabelSource()
3898 {
3899 global $langs;
3900
3901 $label = $langs->trans('OrderSource'.$this->source);
3902
3903 if ($label == 'OrderSource') {
3904 return '';
3905 }
3906 return $label;
3907 }
3908
3915 public function getLibStatut($mode)
3916 {
3917 return $this->LibStatut($this->status, $this->billed, $mode);
3918 }
3919
3920 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3930 public function LibStatut($status, $billed, $mode, $donotshowbilled = 0)
3931 {
3932 // phpcs:enable
3933 global $langs, $hookmanager;
3934
3935 $billedtext = '';
3936 if (empty($donotshowbilled)) {
3937 $billedtext .= ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : '');
3938 }
3939 $billedtextlong = ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : '');
3940
3941 $labelTooltip = '';
3942
3943 $paramsBadge = array('badgeParams' => array('attr' => array(
3944 'data-status-element' => $this->element,
3945 'data-billed' => (int) $billed,
3946 'data-status' => (int) $status
3947 )));
3948
3949 if ($status == self::STATUS_CANCELED) {
3950 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderCanceled');
3951 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderCanceledShort');
3952 $statusType = 'status9';
3953 } elseif ($status == self::STATUS_DRAFT) {
3954 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderDraft');
3955 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderDraftShort');
3956 $statusType = 'status0';
3957 } elseif ($status == self::STATUS_VALIDATED) {
3958 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderValidated').$billedtextlong;
3959 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderValidatedShort').$billedtext;
3960 $statusType = 'status1';
3961 } elseif ($status == self::STATUS_SHIPMENTONPROCESS) {
3962 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderSent').$billedtextlong;
3963 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderSentShort').$billedtext;
3964 $labelTooltip = $langs->transnoentitiesnoconv("StatusOrderSent");
3965 if (!empty($this->delivery_date)) {
3966 $labelTooltip .= ' - '.$langs->transnoentitiesnoconv("DateDeliveryPlanned").dol_print_date($this->delivery_date, 'day').$billedtext;
3967 }
3968 $statusType = 'status4';
3969 } elseif ($status == self::STATUS_CLOSED) {
3970 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderDelivered').$billedtextlong;
3971 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderDeliveredShort').$billedtext;
3972 $statusType = 'status6';
3973 } else {
3974 $labelStatus = $langs->transnoentitiesnoconv('Unknown');
3975 $labelStatusShort = '';
3976 $statusType = '';
3977 $mode = 0;
3978 }
3979
3980 $paramsBadge['tooltip'] = $labelTooltip;
3981
3982 $parameters = array(
3983 'status' => $status,
3984 'mode' => $mode,
3985 'billed' => $billed,
3986 'donotshowbilled' => $donotshowbilled,
3987 'paramsBadge' => & $paramsBadge
3988 );
3989
3990 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
3991
3992 if ($reshook > 0) {
3993 return $hookmanager->resPrint;
3994 }
3995
3996 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $paramsBadge);
3997 }
3998
4006 public function getTooltipContentArray($params)
4007 {
4008 global $conf, $langs, $user;
4009
4010 $langs->load('orders');
4011 $datas = [];
4012 $nofetch = !empty($params['nofetch']);
4013
4014 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
4015 return ['optimize' => $langs->trans("Order")];
4016 }
4017
4018 if ($user->hasRight('commande', 'lire')) {
4019 $datas['picto'] = img_picto('', $this->picto, '', 0, 0, 0, '', 'paddingrightonly').'<u>'.$langs->trans("Order").'</u>';
4020 if (isset($this->status)) {
4021 $datas['status'] = ' '.$this->getLibStatut(5);
4022 }
4023 $datas['Ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
4024 if (!$nofetch) {
4025 $langs->load('companies');
4026 if (empty($this->thirdparty)) {
4027 $this->fetch_thirdparty();
4028 }
4029 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
4030 }
4031 $datas['RefCustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.(empty($this->ref_customer) ? (empty($this->ref_client) ? '' : $this->ref_client) : $this->ref_customer);
4032 if (!$nofetch) {
4033 $langs->load('project');
4034 if (is_null($this->project) || (is_object($this->project) && empty($this->project->id))) {
4035 $res = $this->fetchProject();
4036 if ($res > 0 && $this->project instanceof Project) {
4037 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
4038 }
4039 }
4040 }
4041 if (!empty($this->total_ht)) {
4042 $datas['AmountHT'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
4043 }
4044 if (!empty($this->total_tva)) {
4045 $datas['VAT'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
4046 }
4047 if (!empty($this->total_ttc)) {
4048 $datas['AmountTTC'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
4049 }
4050 if (!empty($this->date)) {
4051 $datas['Date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
4052 }
4053 if (!empty($this->delivery_date)) {
4054 $datas['DeliveryDate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
4055 }
4056 }
4057
4058 return $datas;
4059 }
4060
4074 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0, $target = '')
4075 {
4076 global $conf, $langs, $user, $hookmanager;
4077
4078 if (!empty($conf->dol_no_mouse_hover)) {
4079 $notooltip = 1; // Force disable tooltips
4080 }
4081
4082 $result = '';
4083
4084 if (isModEnabled("shipping") && ($option == '1' || $option == '2')) {
4085 $baseurl = DOL_URL_ROOT . '/expedition/shipment.php';
4086 } else {
4087 $baseurl = DOL_URL_ROOT . '/commande/card.php';
4088 }
4089 $query = ['id' => $this->id];
4090 if (!$user->hasRight('commande', 'lire')) {
4091 $option = 'nolink';
4092 }
4093
4094 if ($option !== 'nolink') {
4095 // Add param to save lastsearch_values or not
4096 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
4097 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
4098 $add_save_lastsearch_values = 1;
4099 }
4100 if ($add_save_lastsearch_values) {
4101 $query = array_merge($query, ['save_lastsearch_values' => 1]);
4102 }
4103 }
4104 $url = dolBuildUrl($baseurl, $query);
4105
4106 if ($short) {
4107 return $url;
4108 }
4109 $params = [
4110 'id' => $this->id,
4111 'objecttype' => $this->element,
4112 'option' => $option,
4113 'nofetch' => 1,
4114 ];
4115 $classfortooltip = 'classfortooltip';
4116 $dataparams = '';
4117 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
4118 $classfortooltip = 'classforajaxtooltip';
4119 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
4120 $label = '';
4121 } else {
4122 $label = implode($this->getTooltipContentArray($params));
4123 }
4124
4125 $linkclose = '';
4126 if (empty($notooltip) && $user->hasRight('commande', 'lire')) {
4127 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
4128 $label = $langs->trans("Order");
4129 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
4130 }
4131 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
4132 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
4133
4134 $target_value = array('_self', '_blank', '_parent', '_top');
4135 if (in_array($target, $target_value)) {
4136 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
4137 }
4138 }
4139
4140 $linkstart = '<a href="'.$url.'"';
4141 $linkstart .= $linkclose.'>';
4142 $linkend = '</a>';
4143
4144 if ($option === 'nolink') {
4145 $linkstart = '';
4146 $linkend = '';
4147 }
4148
4149 $result .= $linkstart;
4150 if ($withpicto) {
4151 $result .= img_object(($notooltip ? '' : $label), $this->picto, (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
4152 }
4153 if ($withpicto != 2) {
4154 $result .= $this->ref;
4155 }
4156 $result .= $linkend;
4157
4158 if ($addlinktonotes) {
4159 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
4160 if ($txttoshow) {
4161 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
4162 $result .= ' <span class="note inline-block">';
4163 $result .= '<a href="'.DOL_URL_ROOT.'/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
4164 $result .= img_picto('', 'note');
4165 $result .= '</a>';
4166 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
4167 //$result.='</a>';
4168 $result .= '</span>';
4169 }
4170 }
4171
4172 global $action;
4173 $hookmanager->initHooks(array($this->element . 'dao'));
4174 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
4175 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4176 if ($reshook > 0) {
4177 $result = $hookmanager->resPrint;
4178 } else {
4179 $result .= $hookmanager->resPrint;
4180 }
4181 return $result;
4182 }
4183
4184
4191 public function info($id)
4192 {
4193 $sql = 'SELECT c.rowid, date_creation as datec, tms as datem,';
4194 $sql .= ' date_valid as datev,';
4195 $sql .= ' date_cloture as datecloture,';
4196 $sql .= ' fk_user_author, fk_user_valid, fk_user_cloture';
4197 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as c';
4198 $sql .= ' WHERE c.rowid = '.((int) $id);
4199 $result = $this->db->query($sql);
4200 if ($result) {
4201 if ($this->db->num_rows($result)) {
4202 $obj = $this->db->fetch_object($result);
4203 $this->id = $obj->rowid;
4204 if ($obj->fk_user_author) {
4205 $this->user_creation_id = $obj->fk_user_author;
4206 }
4207 if ($obj->fk_user_valid) {
4208 $this->user_validation_id = $obj->fk_user_valid;
4209 }
4210 if ($obj->fk_user_cloture) {
4211 $this->user_closing_id = $obj->fk_user_cloture;
4212 }
4213
4214 $this->date_creation = $this->db->jdate($obj->datec);
4215 $this->date_modification = $this->db->jdate($obj->datem);
4216 $this->date_validation = $this->db->jdate($obj->datev);
4217 $this->date_cloture = $this->db->jdate($obj->datecloture);
4218 }
4219
4220 $this->db->free($result);
4221 } else {
4222 dol_print_error($this->db);
4223 }
4224 }
4225
4226
4235 public function initAsSpecimen($param = array())
4236 {
4237 global $conf, $langs;
4238
4239 dol_syslog(get_class($this)."::initAsSpecimen");
4240
4241 // Load array of products prodids
4242 $num_prods = 0;
4243 $prodids = array();
4244 $sql = "SELECT rowid";
4245 $sql .= " FROM ".MAIN_DB_PREFIX."product";
4246 $sql .= " WHERE entity IN (".getEntity('product').")";
4247 if (array_key_exists('tosell', $param)) {
4248 $sql .= " AND tosell = ".((int) $param['tosell']);
4249 }
4250 $sql .= $this->db->plimit(100);
4251
4252 $resql = $this->db->query($sql);
4253 if ($resql) {
4254 $num_prods = $this->db->num_rows($resql);
4255 $i = 0;
4256 while ($i < $num_prods) {
4257 $i++;
4258 $row = $this->db->fetch_row($resql);
4259 $prodids[$i] = $row[0];
4260 }
4261 }
4262
4263 // Initialise parameters
4264 $this->id = 0;
4265 $this->ref = 'SPECIMEN';
4266 $this->specimen = 1;
4267 $this->entity = $conf->entity;
4268 $this->socid = 1;
4269 $this->date = dol_now();
4270 $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
4271 $this->cond_reglement_code = 'RECEP';
4272 $this->mode_reglement_code = 'CHQ';
4273 $this->availability_code = 'DSP';
4274 $this->demand_reason_code = 'SRC_00';
4275
4276 $this->note_public = 'This is a comment (public)';
4277 $this->note_private = 'This is a comment (private)';
4278
4279 $this->multicurrency_tx = 1;
4280 $this->multicurrency_code = $conf->currency;
4281
4282 $this->status = $this::STATUS_DRAFT;
4283
4284 // Lines
4285 $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)
4286 $xnbp = 0;
4287
4288 while ($xnbp < $nbp) {
4289 $line = new OrderLine($this->db);
4290
4291 $line->desc = $langs->trans("Description")." ".$xnbp;
4292 $line->qty = 1;
4293 $line->subprice = 100;
4294 $line->price = 100;
4295 $line->tva_tx = 20;
4296 if ($xnbp == 2) {
4297 $line->total_ht = 50;
4298 $line->total_ttc = 60;
4299 $line->total_tva = 10;
4300 $line->remise_percent = 50;
4301 } else {
4302 $line->total_ht = 100;
4303 $line->total_ttc = 120;
4304 $line->total_tva = 20;
4305 $line->remise_percent = 0;
4306 }
4307 if ($num_prods > 0) {
4308 $prodid = mt_rand(1, $num_prods);
4309 $line->fk_product = $prodids[$prodid];
4310 $line->product_ref = 'SPECIMEN';
4311 }
4312
4313 $this->lines[$xnbp] = $line;
4314
4315 $this->total_ht += $line->total_ht;
4316 $this->total_tva += $line->total_tva;
4317 $this->total_ttc += $line->total_ttc;
4318
4319 $xnbp++;
4320 }
4321
4322 return 1;
4323 }
4324
4325
4331 public function loadStateBoard()
4332 {
4333 global $user, $hookmanager;
4334
4335 $this->nb = array();
4336 $clause = "WHERE";
4337
4338 $sql = "SELECT count(c.rowid) as nb";
4339 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
4340 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
4341 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
4342 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4343 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
4344 $clause = "AND";
4345 }
4346 $sql .= " ".$clause." c.entity IN (".getEntity('commande').")";
4347 // Add where from hooks
4348 $parameters = array();
4349 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
4350 $sql .= $hookmanager->resPrint;
4351 $resql = $this->db->query($sql);
4352 if ($resql) {
4353 while ($obj = $this->db->fetch_object($resql)) {
4354 $this->nb["orders"] = $obj->nb;
4355 }
4356 $this->db->free($resql);
4357 return 1;
4358 } else {
4359 dol_print_error($this->db);
4360 $this->error = $this->db->error();
4361 return -1;
4362 }
4363 }
4364
4371 {
4372 $context = parent::getObjectLinesDisplayContext();
4373 $context['inputalsopricewithtax'] = 1;
4374
4375 return $context;
4376 }
4377
4383 public function getLinesArray()
4384 {
4385 return $this->fetch_lines();
4386 }
4387
4399 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4400 {
4401 global $langs;
4402
4403 $langs->load("orders");
4404 $outputlangs->load("products");
4405
4406 if (!dol_strlen($modele)) {
4407 $modele = 'eratosthene';
4408
4409 if (!empty($this->model_pdf)) {
4410 $modele = $this->model_pdf;
4411 } elseif (getDolGlobalString('COMMANDE_ADDON_PDF')) {
4412 $modele = getDolGlobalString('COMMANDE_ADDON_PDF');
4413 }
4414 }
4415
4416 $modelpath = "core/modules/commande/doc/";
4417
4418 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4419 }
4420
4421
4430 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4431 {
4432 $tables = array(
4433 'commande'
4434 );
4435
4436 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4437 }
4438
4447 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
4448 {
4449 $tables = array(
4450 'commandedet',
4451 );
4452
4453 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
4454 }
4455
4461 public function hasDelay()
4462 {
4463 global $conf;
4464
4465 if (!($this->status > Commande::STATUS_DRAFT && $this->status < Commande::STATUS_CLOSED)) {
4466 return false; // Never late if not inside this status range
4467 }
4468
4469 $now = dol_now();
4470
4471 return max($this->date, $this->delivery_date) < ($now - $conf->commande->client->warning_delay);
4472 }
4473
4479 public function showDelay()
4480 {
4481 global $conf, $langs;
4482
4483 if (empty($this->delivery_date)) {
4484 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date, 'day');
4485 } else {
4486 $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->delivery_date, 'day');
4487 }
4488 $text .= ' '.($conf->commande->client->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->client->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
4489
4490 return $text;
4491 }
4492
4502 public function setSignedStatus(User $user, int $status = 0, int $notrigger = 0, $triggercode = ''): int
4503 {
4504 return $this->setSignedStatusCommon($user, $status, $notrigger, $triggercode);
4505 }
4506
4517 public function getShippableInfos(array $options = array()): array
4518 {
4519 global $conf, $langs, $hookmanager;
4520
4521 $langs->loadLangs(array('orders', 'sendings', 'stocks', 'products'));
4522
4523 $result = array(
4524 'has_product' => false,
4525 'shippable' => false,
4526 'texticon' => '',
4527 'textinfo' => '',
4528 'warning' => false,
4529 );
4530
4531 if (is_object($hookmanager)) {
4532 $parameters = array('options' => $options);
4533 $reshook = $hookmanager->executeHooks('getShippableInfos', $parameters, $this);
4534 if ($reshook < 0) {
4535 dol_syslog(__METHOD__.' hook getShippableInfos failed: '.$hookmanager->error, LOG_ERR);
4536 }
4537 if (!empty($hookmanager->resArray['shippableinfos'])
4538 && is_array($hookmanager->resArray['shippableinfos'])) {
4539 return array_merge($result, $hookmanager->resArray['shippableinfos']);
4540 }
4541 }
4542
4543 // Requested naming for statuses
4544 if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_CLOSED) {
4545 return $result;
4546 }
4547
4548
4549 $genericCommande = $this;
4550 $genericProduct = new Product($this->db);
4551
4552
4553 $productstatcache = array();
4554 $productstatcachevirtual = array();
4555
4556
4557 $genericCommande->getLinesArray(); // Load array ->lines
4558 $genericCommande->loadExpeditions(); // Load array ->expeditions
4559
4560 $notshippable = 0;
4561 $has_reliquat = 0;
4562 $warning = 0;
4563 $textinfo = '';
4564 $textwarning = '';
4565 $nbprod = 0;
4566
4567 $genericProduct = new Product($this->db);
4568
4569 $numlines = count($genericCommande->lines);
4570 for ($lig = 0; $lig < $numlines; $lig++) {
4571 $orderLine = $genericCommande->lines[$lig]; // @phan-var-force OrderLine $orderLine
4572
4573 if (isset($genericCommande->expeditions[$orderLine->id])) {
4574 $reliquat = $orderLine->qty - $genericCommande->expeditions[$orderLine->id];
4575 } else {
4576 $reliquat = $orderLine->qty;
4577 }
4578
4579 if ($orderLine->product_type == 0 && $orderLine->fk_product > 0) { // product, not service
4580 $nbprod = 1;
4581
4582 if (empty($productstatcache[$orderLine->fk_product])) {
4583 $genericProduct->fetch($orderLine->fk_product);
4584 $genericProduct->load_stock('nobatch,warehouseopen'); // loadvirtualstock included
4585
4586 $productstatcache[$orderLine->fk_product]['stockreel'] = $genericProduct->stock_reel;
4587 $productstatcachevirtual[$orderLine->fk_product]['stockreel'] = $genericProduct->stock_theorique;
4588 }
4589
4590 $genericProduct->stock_reel = $productstatcache[$orderLine->fk_product]['stockreel'];
4591 $genericProduct->stock_theorique = $productstatcachevirtual[$orderLine->fk_product]['stockreel'];
4592
4593 if ($reliquat > 0) {
4594 $has_reliquat = 1;
4595 if (!getDolGlobalString('SHIPPABLE_ORDER_ICON_IN_LIST')) {
4596 $textinfo .= $reliquat . ' x ' . $orderLine->product_ref . '&nbsp;' . dol_trunc($orderLine->product_label, 20);
4597 $textinfo .= ' - ' . $langs->trans("Stock") . ': <span class="' . ($genericProduct->stock_reel >= $reliquat ? 'ok' : 'error') . '">' . $genericProduct->stock_reel . '</span>';
4598 $textinfo .= ' - ' . $langs->trans("VirtualStock") . ': <span class="' . ($genericProduct->stock_theorique >= $reliquat ? 'ok' : 'error') . '">' . $genericProduct->stock_theorique . '</span>';
4599 if ($reliquat != $orderLine->qty) {
4600 $textinfo .= ' <span class="opacitymedium">' . $langs->trans("QtyInOtherShipments") . ' ' . ($orderLine->qty - $reliquat) . '</span>';
4601 }
4602 $textinfo .= '<br>';
4603 } else {
4604 // BUGGED CODE (kept for backward compatibility and hidden conf)
4605 $stockorder = 0;
4606 $stockordersupplier = 0;
4607
4608 if (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
4609 if (isModEnabled('order')) {
4610 if (empty($productstatcache[$orderLine->fk_product]['statsordercustomer'])) {
4611 $genericProduct->fetch($orderLine->fk_product);
4612 $genericProduct->load_stats_commande(0, '1,2');
4613 $productstatcache[$orderLine->fk_product]['statsordercustomer'] = $genericProduct->stats_commande['qty'];
4614 }
4615 $genericProduct->stats_commande['qty'] = $productstatcache[$orderLine->fk_product]['statsordercustomer'];
4616 $stockorder = $genericProduct->stats_commande['qty'];
4617
4618 if (isModEnabled('supplier_order')) {
4619 if (empty($productstatcache[$orderLine->fk_product]['statsordersupplier'])) {
4620 $genericProduct->load_stats_commande_fournisseur(0, '3');
4621 $productstatcache[$orderLine->fk_product]['statsordersupplier'] = $genericProduct->stats_commande_fournisseur['qty'];
4622 }
4623 $genericProduct->stats_commande_fournisseur['qty'] = $productstatcache[$orderLine->fk_product]['statsordersupplier'];
4624 $stockordersupplier = $genericProduct->stats_commande_fournisseur['qty'];
4625 }
4626 }
4627 }
4628
4629 $textinfo .= $reliquat . ' x ' . $orderLine->ref . '&nbsp;' . dol_trunc($orderLine->product_label, 20);
4630 $textinfo .= ' ' . $langs->trans("Available") . '&nbsp;&nbsp;' . $genericProduct->stock_reel . '..' . $stockorder;
4631
4632 if ($stockorder && $genericProduct->stock_reel < ($genericProduct->stock_reel - $stockorder + $reliquat)) {
4633 $warning++;
4634 $textwarning .= '<span class="warning">' . $langs->trans("Available") . '&nbsp;&nbsp;' . $genericProduct->stock_reel . '..' . $stockorder . '</span>';
4635 } else {
4636 if ($reliquat > $genericProduct->stock_reel) {
4637 $textinfo .= ' <span class="warning">' . $langs->trans("Available") . '&nbsp;&nbsp;' . $genericProduct->stock_reel . '</span>';
4638 } else {
4639 $textinfo .= ' <span class="ok">' . $langs->trans("Available") . '&nbsp;&nbsp;' . $genericProduct->stock_reel . '</span>';
4640 }
4641 }
4642
4643 if (isModEnabled('supplier_order')) {
4644 $textinfo .= '&nbsp;' . $langs->trans("SupplierOrder") . '&nbsp;&nbsp;' . $stockordersupplier;
4645 }
4646 if ($reliquat != $orderLine->qty) {
4647 $textinfo .= ' <span class="opacitymedium">' . $langs->trans("QtyInOtherShipments") . ' ' . ($orderLine->qty - $reliquat) . '</span>';
4648 }
4649 $textinfo .= '<br>';
4650 }
4651
4652 if ($reliquat > $genericProduct->stock_reel) {
4653 $notshippable++;
4654 }
4655 }
4656 }
4657 }
4658
4659 if ($nbprod) {
4660 if (!$has_reliquat) {
4661 $texticon = img_picto('', 'statut5', '', 0, 0, 0, '', 'paddingleft');
4662 $textinfo = $texticon . ' ' . $langs->trans("Shipped");
4663 $result['shippable'] = true;
4664 } elseif ($notshippable) {
4665 $texticon = img_picto('', 'dolly', '', 0, 0, 0, '', 'error paddingleft');
4666 $textinfo = $texticon . ' ' . $langs->trans("NonShippable") . '<br>' . $textinfo;
4667 $result['shippable'] = false;
4668 } else {
4669 $texticon = img_picto('', 'dolly', '', 0, 0, 0, '', 'green paddingleft');
4670 $textinfo = $texticon . ' ' . $langs->trans("Shippable") . '<br>' . $textinfo;
4671 $result['shippable'] = true;
4672 }
4673 $result['has_product'] = true;
4674 $result['texticon'] = $texticon;
4675 $result['textinfo'] = $textinfo;
4676 $result['warning'] = !empty($warning);
4677 }
4678
4679 return $result;
4680 }
4681}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage 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.
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.
getObjectLinesDisplayContext()
Return the display context of the lines, as defined by the card before printObjectLines() and formAdd...
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.
persistFieldValue(User $user, $field)
Save into database the current value of one field, called by updateFieldFromUi().
isRefClientAlreadyUsed(string $ref_client, int $socid, int $excludeid=0)
Check if a customer ref is already used by another customer order of the same third party.
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.
getShippableInfos(array $options=array())
Compute shippable status and tooltip/icon for the order.
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.
createFromClone(User $user, $socid=0, $forceentity=null)
Load an object from its id and create a new one in database.
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.
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 translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
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:66
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
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)
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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)
Definition html.lib.php:183
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492