dolibarr 24.0.3
commande.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
6 * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2011 Jean Heimburger <jean@tiaris.info>
8 * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
9 * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
10 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
11 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
12 * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
13 * Copyright (C) 2016-2022 Ferran Marcet <fmarcet@2byte.es>
14 * Copyright (C) 2021-2025 Frédéric France <frederic.france@free.fr>
15 * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
16 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
17 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
18 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
19 * Copyright (C) 2026 Nick Fragoulis
20 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 3 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <https://www.gnu.org/licenses/>.
33 */
34
41require_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
42require_once DOL_DOCUMENT_ROOT.'/commande/class/orderline.class.php';
43require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
44require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
45require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
46require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
47require_once DOL_DOCUMENT_ROOT.'/subtotals/class/commonsubtotal.class.php';
48
49
53class Commande extends CommonOrder
54{
55 use CommonSubtotal;
56
60 public $element = 'commande';
61
66 public $TRIGGER_PREFIX = 'ORDER';
67
71 public $table_element = 'commande';
72
76 public $table_element_line = 'commandedet';
77
81 public $class_element_line = 'OrderLine';
82
86 public $fk_element = 'fk_commande';
87
91 public $picto = 'order';
92
97 public $restrictiononfksoc = 1;
98
102 protected $table_ref_field = 'ref';
103
107 public $ref;
108
112 public $socid;
113
117 public $ref_client;
118
122 public $ref_customer;
123
127 public $contactid;
128
134 public $statut;
135
140 public $status;
141
145 public $billed;
146
150 public $date_lim_reglement;
154 public $cond_reglement_code;
155
159 public $cond_reglement_doc;
160
164 public $cond_reglement_label;
165
170 public $deposit_percent;
171
175 public $fk_account;
176
180 public $mode_reglement;
181
185 public $mode_reglement_id;
186
190 public $mode_reglement_code;
191
196 public $availability_id;
197
202 public $availability_code;
203
208 public $availability;
209
213 public $demand_reason_id;
214
218 public $demand_reason_code;
219
223 public $date;
224
230 public $date_commande;
231
235 public $delivery_date;
236
240 public $fk_remise_except;
241
246 public $remise_percent;
247
251 public $source;
252
257 public $signed_status = 0;
258
262 public $warehouse_id;
263
267 public $extraparams = array();
268
272 public $user_author_id;
273
277 public $line;
278
282 public $lines = array();
283
284
288 public $module_source;
292 public $pos_source;
293
297 public $expeditions;
298
302 public $online_payment_url;
303
304
305
331 // BEGIN MODULEBUILDER PROPERTIES
335 public $fields = array(
336 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
337 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 20, 'index' => 1),
338 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'showoncombobox' => 1, 'position' => 25),
339 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 26),
340 'ref_client' => array('type' => 'varchar(255)', 'label' => 'RefCustomer', 'enabled' => 1, 'visible' => -1, 'position' => 28),
341 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'notnull' => 1, 'position' => 20),
342 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => "isModEnabled('project')", 'visible' => -1, 'position' => 25),
343 'date_commande' => array('type' => 'date', 'label' => 'Date', 'enabled' => 1, 'visible' => 1, 'position' => 60, 'csslist' => 'nowraponall'),
344 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 62, 'csslist' => 'nowraponall'),
345 'date_cloture' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => -1, 'position' => 65, 'csslist' => 'nowraponall'),
346 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 85),
347 'fk_user_cloture' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => -1, 'position' => 90),
348 'source' => array('type' => 'smallint(6)', 'label' => 'Source', 'enabled' => 1, 'visible' => -1, 'position' => 95),
349 'total_tva' => array('type' => 'double(24,8)', 'label' => 'VAT', 'enabled' => 1, 'visible' => -1, 'position' => 125, 'isameasure' => 1),
350 'localtax1' => array('type' => 'double(24,8)', 'label' => 'LocalTax1', 'enabled' => 1, 'visible' => -1, 'position' => 130, 'isameasure' => 1),
351 'localtax2' => array('type' => 'double(24,8)', 'label' => 'LocalTax2', 'enabled' => 1, 'visible' => -1, 'position' => 135, 'isameasure' => 1),
352 'total_ht' => array('type' => 'double(24,8)', 'label' => 'TotalHT', 'enabled' => 1, 'visible' => -1, 'position' => 140, 'isameasure' => 1),
353 'total_ttc' => array('type' => 'double(24,8)', 'label' => 'TotalTTC', 'enabled' => 1, 'visible' => -1, 'position' => 145, 'isameasure' => 1),
354 'signed_status' => array('type' => 'smallint(6)', 'label' => 'SignedStatus', 'enabled' => 1, 'visible' => -1, 'position' => 146, 'arrayofkeyval' => array(0 => 'NoSignature', 1 => 'SignedSender', 2 => 'SignedReceiver', 9 => 'SignedAll')),
355 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 150),
356 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 155),
357 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'PDFTemplate', 'enabled' => 1, 'visible' => 0, 'position' => 160),
358 'fk_account' => array('type' => 'integer', 'label' => 'BankAccount', 'enabled' => 'isModEnabled("bank")', 'visible' => -1, 'position' => 170),
359 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'MulticurrencyID', 'enabled' => 1, 'visible' => -1, 'position' => 175),
360 'fk_cond_reglement' => array('type' => 'integer', 'label' => 'PaymentTerm', 'enabled' => 1, 'visible' => -1, 'position' => 180),
361 'deposit_percent' => array('type' => 'varchar(63)', 'label' => 'DepositPercent', 'enabled' => 1, 'visible' => -1, 'position' => 181),
362 'fk_mode_reglement' => array('type' => 'integer', 'label' => 'PaymentMode', 'enabled' => 1, 'visible' => -1, 'position' => 185),
363 'date_livraison' => array('type' => 'date', 'label' => 'DateDeliveryPlanned', 'enabled' => 1, 'visible' => -1, 'position' => 190, 'csslist' => 'nowraponall'),
364 'fk_shipping_method' => array('type' => 'integer', 'label' => 'ShippingMethod', 'enabled' => 1, 'visible' => -1, 'position' => 195),
365 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'DefaultWarehouse', 'enabled' => 'isModEnabled("stock")', 'visible' => -1, 'position' => 200, 'nodepth' => 1),
366 'fk_availability' => array('type' => 'integer', 'label' => 'Availability', 'enabled' => 1, 'visible' => -1, 'position' => 205),
367 'fk_input_reason' => array('type' => 'integer', 'label' => 'InputReason', 'enabled' => 1, 'visible' => -1, 'position' => 210),
368 //'fk_delivery_address' =>array('type'=>'integer', 'label'=>'DeliveryAddress', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
369 'extraparams' => array('type' => 'varchar(255)', 'label' => 'Extraparams', 'enabled' => 1, 'visible' => -1, 'position' => 225),
370 'fk_incoterms' => array('type' => 'integer', 'label' => 'IncotermCode', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 230),
371 'location_incoterms' => array('type' => 'varchar(255)', 'label' => 'IncotermLabel', 'enabled' => 'isModEnabled("incoterm")', 'visible' => -1, 'position' => 235),
372 'fk_multicurrency' => array('type' => 'integer', 'label' => 'Fk multicurrency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 240),
373 'multicurrency_code' => array('type' => 'varchar(255)', 'label' => 'MulticurrencyCurrency', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 245),
374 'multicurrency_tx' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyRate', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 250, 'isameasure' => 1),
375 'multicurrency_total_ht' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountHT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 255, 'isameasure' => 1),
376 'multicurrency_total_tva' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountVAT', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 260, 'isameasure' => 1),
377 'multicurrency_total_ttc' => array('type' => 'double(24,8)', 'label' => 'MulticurrencyAmountTTC', 'enabled' => 'isModEnabled("multicurrency")', 'visible' => -1, 'position' => 265, 'isameasure' => 1),
378 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'visible' => -1, 'position' => 270),
379 'module_source' => array('type' => 'varchar(32)', 'label' => 'POSModule', 'enabled' => 1, 'visible' => -1, 'position' => 275),
380 'pos_source' => array('type' => 'varchar(32)', 'label' => 'POSTerminal', 'enabled' => 1, 'visible' => -1, 'position' => 280),
381 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 300),
382 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'notnull' => -1, 'position' => 302),
383 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -2, 'position' => 304, 'csslist' => 'nowraponall'),
384 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 306),
385 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 400),
386 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'enabled' => 1, 'visible' => -1, 'position' => 500),
387 );
388 // END MODULEBUILDER PROPERTIES
389
394
398 const STATUS_CANCELED = -1;
402 const STATUS_DRAFT = 0;
410 const STATUS_SHIPMENTONPROCESS = 2; // We set this status when a shipment is validated
411
417
421 const STATUS_CLOSED = 3;
422
423 /*
424 * No signature
425 */
426 const STATUS_NO_SIGNATURE = 0;
427
428 /*
429 * Signed by sender
430 */
431 const STATUS_SIGNED_SENDER = 1;
432
433 /*
434 * Signed by receiver
435 */
436 const STATUS_SIGNED_RECEIVER = 2;
437
438 /*
439 * Signed by all
440 */
441 const STATUS_SIGNED_ALL = 9; // To handle future kind of signature (ex: tripartite contract)
442
443
449 public function __construct($db)
450 {
451 $this->db = $db;
452
453 $this->ismultientitymanaged = 1;
454 $this->isextrafieldmanaged = 1;
455
456 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
457 }
458
466 public function getNextNumRef($soc)
467 {
468 global $langs, $conf;
469 $langs->load("order");
470
471 if (getDolGlobalString('COMMANDE_ADDON')) {
472 $mybool = false;
473
474 $file = getDolGlobalString('COMMANDE_ADDON') . ".php";
475 $classname = getDolGlobalString('COMMANDE_ADDON');
476
477 // Include file with class
478 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
479 foreach ($dirmodels as $reldir) {
480 $dir = dol_buildpath($reldir."core/modules/commande/");
481
482 // Load file with numbering class (if found)
483 $mybool = ((bool) @include_once $dir.$file) || $mybool;
484 }
485
486 if (!$mybool) {
487 dol_print_error(null, "Failed to include file ".$file);
488 return '';
489 }
490
491 $obj = new $classname();
493 '@phan-var-force ModeleNumRefCommandes $obj';
494
495 $numref = $obj->getNextValue($soc, $this);
496
497 if ($numref != "") {
498 return $numref;
499 } else {
500 $this->error = $obj->error;
501 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
502 return "";
503 }
504 } else {
505 print $langs->trans("Error")." ".$langs->trans("Error_COMMANDE_ADDON_NotDefined");
506 return "";
507 }
508 }
509
510
519 public function valid($user, $idwarehouse = 0, $notrigger = 0)
520 {
521 global $conf, $langs;
522
523 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
524
525 $error = 0;
526
527 // Protection
528 if ($this->status == self::STATUS_VALIDATED) {
529 dol_syslog(get_class($this)."::valid action abandoned: already validated", LOG_WARNING);
530 return 0;
531 }
532
533 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
534 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')))) {
535 $this->error = 'NotEnoughPermissions';
536 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
537 return -1;
538 }
539 if (empty($this->socid)) {
540 $this->error = 'ErrorWrongParameters';
541 return -1;
542 }
543 if (!getDolGlobalBool('ORDER_NOCHECK_ONSALE_PRODUCTS_ONVALID') && !$this->checkActiveProductInLines()) {
544 dol_syslog(get_class($this)."::valid checkActiveProductInLines ".$this->error, LOG_INFO);
545 return -1;
546 }
547 $now = dol_now();
548
549 $this->db->begin();
550
551 // Definition du nom de module de numerotation de commande
552 $soc = new Societe($this->db);
553 $soc->fetch($this->socid);
554
555 // Class of company linked to order
556 $result = $soc->setAsCustomer();
557
558 // Define new ref
559 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
560 $num = $this->getNextNumRef($soc);
561 } else {
562 $num = (string) $this->ref;
563 }
564 $this->newref = dol_sanitizeFileName($num);
565
566 // Validate
567 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
568 $sql .= " SET ref = '".$this->db->escape($num)."',";
569 $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
570 $sql .= " date_valid = '".$this->db->idate($now)."',";
571 $sql .= " fk_user_valid = ".($user->id > 0 ? (int) $user->id : "null").",";
572 $sql .= " fk_user_modif = ".((int) $user->id);
573 $sql .= " WHERE rowid = ".((int) $this->id);
574
575 dol_syslog(get_class($this)."::valid", LOG_DEBUG);
576 $resql = $this->db->query($sql);
577 if (!$resql) {
578 dol_print_error($this->db);
579 $this->error = $this->db->lasterror();
580 $error++;
581 }
582
583 if (!$error) {
584 // If stock is incremented on validate order, we must increment it
585 if ($result >= 0 && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
586 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
587 $langs->load("agenda");
588
589 // Loop on each line
590 $cpt = count($this->lines);
591 for ($i = 0; $i < $cpt; $i++) {
592 if ($this->lines[$i]->fk_product > 0) {
593 $mouvP = new MouvementStock($this->db);
594 $mouvP->origin = &$this;
595 $mouvP->setOrigin($this->element, $this->id);
596 // We decrement stock of product (and sub-products)
597 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr", $num));
598 if ($result < 0) {
599 $error++;
600 $this->setErrorsFromObject($mouvP);
601 }
602 }
603 if ($error) {
604 break;
605 }
606 }
607 }
608 }
609
610 if (!$error && !$notrigger) {
611 // Call trigger
612 $result = $this->call_trigger('ORDER_VALIDATE', $user);
613 if ($result < 0) {
614 $error++;
615 }
616 // End call triggers
617 }
618
619 if (!$error) {
620 $this->oldref = $this->ref;
621
622 // Rename directory if dir was a temporary ref
623 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
624 // Now we rename also files into index
625 $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)."'";
626 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
627 $resql = $this->db->query($sql);
628 if (!$resql) {
629 $error++;
630 $this->error = $this->db->lasterror();
631 }
632 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'commande/".$this->db->escape($this->newref)."'";
633 $sql .= " WHERE filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
634 $resql = $this->db->query($sql);
635 if (!$resql) {
636 $error++;
637 $this->error = $this->db->lasterror();
638 }
639
640 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
641 $oldref = dol_sanitizeFileName($this->ref);
642 $newref = dol_sanitizeFileName($num);
643 $dirsource = getMultidirOutput($this).'/'.$oldref;
644 $dirdest = getMultidirOutput($this).'/'.$newref;
645 if (!$error && file_exists($dirsource)) {
646 dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
647
648 if (@rename($dirsource, $dirdest)) {
649 dol_syslog("Rename ok");
650 // Rename docs starting with $oldref with $newref
651 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref, '/'));
652 foreach ($listoffiles as $fileentry) {
653 $dirsource = $fileentry['name'];
654 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
655 $dirsource = $fileentry['path'].'/'.$dirsource;
656 $dirdest = $fileentry['path'].'/'.$dirdest;
657 @rename($dirsource, $dirdest);
658 }
659 }
660 }
661 }
662 }
663
664 // Set new ref and current status
665 if (!$error) {
666 $this->ref = $num;
667 $this->statut = self::STATUS_VALIDATED; // deprecated
669 }
670
671 if (!$error) {
672 $this->db->commit();
673 return 1;
674 } else {
675 $this->db->rollback();
676 return -1;
677 }
678 }
679
680 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
688 public function setDraft($user, $idwarehouse = -1)
689 {
690 //phpcs:enable
691 global $langs;
692
693 $error = 0;
694
695 // Protection
696 if ($this->status <= self::STATUS_DRAFT && !getDolGlobalInt('ORDER_REOPEN_TO_DRAFT')) {
697 return 0;
698 }
699
700 if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
701 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')))) {
702 $this->error = 'Permission denied';
703 return -1;
704 }
705
706 dol_syslog(__METHOD__, LOG_DEBUG);
707
708 $this->db->begin();
709
710 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
711 $sql .= " SET fk_statut = ".((int) self::STATUS_DRAFT).",";
712 $sql .= " fk_user_modif = ".((int) $user->id);
713 $sql .= " WHERE rowid = ".((int) $this->id);
714
715 if ($this->db->query($sql)) {
716 $this->oldcopy = clone $this;
717
718 // If stock is decremented on validate order, we must reincrement it
719 if (isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
720 $result = 0;
721
722 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
723 $langs->load("agenda");
724
725 $num = count($this->lines);
726 for ($i = 0; $i < $num; $i++) {
727 if ($this->lines[$i]->fk_product > 0) {
728 $mouvP = new MouvementStock($this->db);
729 $mouvP->origin = &$this;
730 $mouvP->setOrigin($this->element, $this->id);
731 // We increment stock of product (and sub-products)
732 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv("OrderBackToDraftInDolibarr", $this->ref));
733 if ($result < 0) {
734 $error++;
735 $this->setErrorsFromObject($mouvP);
736 break;
737 }
738 }
739 }
740 }
741
742 if (!$error) {
743 // Call trigger
744 $result = $this->call_trigger('ORDER_UNVALIDATE', $user);
745 if ($result < 0) {
746 $error++;
747 }
748 }
749
750 if (!$error) {
751 $this->statut = self::STATUS_DRAFT; // deprecated
752 $this->status = self::STATUS_DRAFT;
753 $this->db->commit();
754 return 1;
755 } else {
756 $this->db->rollback();
757 return -1;
758 }
759 } else {
760 $this->error = $this->db->error();
761 $this->db->rollback();
762 return -1;
763 }
764 }
765
766
767 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
775 public function set_reopen($user)
776 {
777 // phpcs:enable
778 $error = 0;
779
780 if ($this->status != self::STATUS_CANCELED && $this->status != self::STATUS_CLOSED) {
781 dol_syslog(get_class($this)."::set_reopen order has not status closed", LOG_WARNING);
782 return 0;
783 }
784
785 $this->db->begin();
786
787 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
788 $sql .= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0,';
789 $sql .= " fk_user_modif = ".((int) $user->id);
790 $sql .= " WHERE rowid = ".((int) $this->id);
791
792 dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG);
793 $resql = $this->db->query($sql);
794 if ($resql) {
795 // Call trigger
796 $result = $this->call_trigger('ORDER_REOPEN', $user);
797 if ($result < 0) {
798 $error++;
799 }
800 // End call triggers
801 } else {
802 $error++;
803 $this->error = $this->db->lasterror();
804 dol_print_error($this->db);
805 }
806
807 if (!$error) {
808 $this->statut = self::STATUS_VALIDATED; // deprecated
810 $this->billed = 0;
811
812 $this->db->commit();
813 return 1;
814 } else {
815 foreach ($this->errors as $errmsg) {
816 dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR);
817 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
818 }
819 $this->db->rollback();
820 return -1 * $error;
821 }
822 }
823
832 public function cloture($user, $notrigger = 0, $checkpermission = 1)
833 {
834 $error = 0;
835
836 $usercanclose = (!$checkpermission
837 || (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
838 || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'close')));
839
840 if ($usercanclose) {
841 if ($this->status == self::STATUS_CLOSED) {
842 return 0;
843 }
844 $this->db->begin();
845
846 $now = dol_now();
847
848 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
849 $sql .= ' SET fk_statut = '.self::STATUS_CLOSED.',';
850 $sql .= ' fk_user_cloture = '.((int) $user->id).',';
851 $sql .= " date_cloture = '".$this->db->idate($now)."',";
852 $sql .= " fk_user_modif = ".((int) $user->id);
853 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
854
855 if ($this->db->query($sql)) {
856 if (!$notrigger) {
857 // Call trigger
858 $result = $this->call_trigger('ORDER_CLOSE', $user);
859 if ($result < 0) {
860 $error++;
861 }
862 // End call triggers
863 }
864
865 if (!$error) {
866 $this->statut = self::STATUS_CLOSED; // deprecated
868
869 $this->db->commit();
870 return 1;
871 } else {
872 $this->db->rollback();
873 return -1;
874 }
875 } else {
876 $this->error = $this->db->lasterror();
877
878 $this->db->rollback();
879 return -1;
880 }
881 }
882 return 0;
883 }
884
896 public function setCategories($categories)
897 {
898 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
899 return parent::setCategoriesCommon($categories, Categorie::TYPE_ORDER);
900 }
901
910 public function cancel($user, $idwarehouse = -1)
911 {
912 global $user, $langs;
913
914 $error = 0;
915
916 $this->db->begin();
917
918 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
919 $sql .= " SET fk_statut = ".self::STATUS_CANCELED.",";
920 $sql .= " fk_user_modif = ".((int) $user->id);
921 $sql .= " WHERE rowid = ".((int) $this->id);
922 $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
923
924 dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
925 if ($this->db->query($sql)) {
926 // If stock is decremented on validate order, we must reincrement it
927 if (isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
928 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
929 $langs->load("agenda");
930
931 $num = count($this->lines);
932 for ($i = 0; $i < $num; $i++) {
933 if ($this->lines[$i]->fk_product > 0) {
934 $mouvP = new MouvementStock($this->db);
935 $mouvP->setOrigin($this->element, $this->id);
936 // We increment stock of product (and sub-products)
937 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr", $this->ref)); // price is 0, we don't want WAP to be changed
938 if ($result < 0) {
939 $error++;
940 $this->setErrorsFromObject($mouvP);
941 break;
942 }
943 }
944 }
945 }
946
947 if (!$error) {
948 // Call trigger
949 $result = $this->call_trigger('ORDER_CANCEL', $user);
950 if ($result < 0) {
951 $error++;
952 }
953 // End call triggers
954 }
955
956 if (!$error) {
957 $this->statut = self::STATUS_CANCELED; // deprecated
959 $this->db->commit();
960 return 1;
961 } else {
962 foreach ($this->errors as $errmsg) {
963 dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
964 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
965 }
966 $this->db->rollback();
967 return -1 * $error;
968 }
969 } else {
970 $this->error = $this->db->error();
971 $this->db->rollback();
972 return -1;
973 }
974 }
975
984 public function create($user, $notrigger = 0)
985 {
986 global $conf, $langs, $mysoc;
987 $error = 0;
988
989 // Clean parameters
990
991 if (empty($this->socid)) {
992 $this->error = 'ErrorWrongParameters';
993 return -1;
994 }
995
996 // Set tmp vars
997 $date = ($this->date_commande ? $this->date_commande : $this->date);
998 $this->import_key = trim((string) $this->import_key);
999 $delivery_date = $this->delivery_date;
1000
1001 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1002 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1003 list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
1004 } else {
1005 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1006 }
1007 if (empty($this->fk_multicurrency)) {
1008 $this->multicurrency_code = $conf->currency;
1009 $this->fk_multicurrency = 0;
1010 $this->multicurrency_tx = 1;
1011 }
1012 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
1013 $this->entity = setEntity($this);
1014
1015 dol_syslog(get_class($this)."::create user=".$user->id);
1016
1017 // Check parameters
1018 if (!empty($this->ref)) { // We check that ref is not already used
1019 $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
1020 if ($result > 0) {
1021 $this->error = 'ErrorRefAlreadyExists';
1022 dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1023 $this->db->rollback();
1024 return -1;
1025 }
1026 }
1027
1028 $soc = new Societe($this->db);
1029 $result = $soc->fetch($this->socid);
1030 if ($result < 0) {
1031 $this->error = "Failed to fetch company";
1032 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1033 return -2;
1034 }
1035 if (getDolGlobalString('ORDER_REQUIRE_SOURCE') && $this->source < 0) {
1036 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Source"));
1037 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1038 return -1;
1039 }
1040
1041 $this->date_creation = dol_now();
1042
1043 $this->db->begin();
1044
1045 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1046 $sql .= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client";
1047 $sql .= ", model_pdf, fk_cond_reglement, deposit_percent, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
1048 $sql .= ", fk_shipping_method";
1049 $sql .= ", fk_warehouse";
1050 $sql .= ", fk_incoterms, location_incoterms";
1051 $sql .= ", entity, module_source, pos_source";
1052 $sql .= ", fk_multicurrency";
1053 $sql .= ", multicurrency_code";
1054 $sql .= ", multicurrency_tx";
1055 $sql .= ", import_key";
1056 $sql .= ")";
1057 $sql .= " VALUES ('(PROV)', ".((int) $this->socid).", '".$this->db->idate($this->date_creation)."', ".($user->id > 0 ? ((int) $user->id) : "null");
1058 $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
1059 $sql .= ", '".$this->db->idate($date)."'";
1060 $sql .= ", ".($this->source >= 0 && $this->source != '' ? $this->db->escape((string) $this->source) : 'null');
1061 $sql .= ", '".$this->db->escape($this->note_private)."'";
1062 $sql .= ", '".$this->db->escape($this->note_public)."'";
1063 $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
1064 $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
1065 $sql .= ", '".$this->db->escape($this->model_pdf)."'";
1066 $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
1067 $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
1068 $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
1069 $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
1070 $sql .= ", ".($this->availability_id > 0 ? ((int) $this->availability_id) : "null");
1071 $sql .= ", ".($this->demand_reason_id > 0 ? ((int) $this->demand_reason_id) : "null");
1072 $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
1073 $sql .= ", ".($this->fk_delivery_address > 0 ? ((int) $this->fk_delivery_address) : 'NULL');
1074 $sql .= ", ".(!empty($this->shipping_method_id) && $this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : 'NULL');
1075 $sql .= ", ".(!empty($this->warehouse_id) && $this->warehouse_id > 0 ? ((int) $this->warehouse_id) : 'NULL');
1076 $sql .= ", ".(int) $this->fk_incoterms;
1077 $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
1078 $sql .= ", ".(int) $this->entity;
1079 $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
1080 $sql .= ", ".((!is_null($this->pos_source) && $this->pos_source != '') ? "'".$this->db->escape($this->pos_source)."'" : "null"); // Can be null, '', '0', '1'
1081 $sql .= ", ".(int) $this->fk_multicurrency;
1082 $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
1083 $sql .= ", ".(float) $this->multicurrency_tx;
1084 $sql .= ", '".$this->db->escape($this->import_key)."'";
1085 $sql .= ")";
1086
1087 dol_syslog(get_class($this)."::create", LOG_DEBUG);
1088 $resql = $this->db->query($sql);
1089 if ($resql) {
1090 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande');
1091
1092 if ($this->id) {
1093 $fk_parent_line = 0;
1094 $num = count($this->lines);
1095
1096 /*
1097 * Insert products details into db
1098 */
1099 for ($i = 0; $i < $num; $i++) {
1100 $line = $this->lines[$i];
1101
1102 // Test and convert into OrderLine object this->lines[$i]. When coming from REST API, we may still have an array
1103 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
1104 if (!is_object($line)) {
1105 $lineobj = new OrderLine($this->db);
1106 foreach ($line as $key => $val) {
1107 $lineobj->$key = $val;
1108 }
1109 $line = $lineobj;
1110 $this->lines[$i] = $line;
1111 }
1112
1113 // Reset fk_parent_line for no child products and special product
1114 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1115 $fk_parent_line = 0;
1116 }
1117
1118 // Complete vat rate with code
1119 $vatrate = $line->tva_tx;
1120 if ($line->vat_src_code && !preg_match('/\‍(.*\‍)/', (string) $vatrate)) {
1121 $vatrate .= ' ('.$line->vat_src_code.')';
1122 }
1123
1124 if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
1125 $originid = $line->origin_id;
1126 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
1127 } else { // old but bugged version (we store id of line and type of parent object)
1128 $originid = $line->id;
1129 $origintype = $this->element;
1130 }
1131
1132 // ref_ext
1133 if (empty($line->ref_ext)) {
1134 $line->ref_ext = '';
1135 }
1136
1137 $result = $this->addline(
1138 $line->desc,
1139 $line->subprice,
1140 $line->qty,
1141 $vatrate,
1142 $line->localtax1_tx,
1143 $line->localtax2_tx,
1144 $line->fk_product,
1145 $line->remise_percent,
1146 $line->info_bits,
1147 $line->fk_remise_except,
1148 'HT',
1149 0,
1150 $line->date_start,
1151 $line->date_end,
1152 $line->product_type,
1153 $line->rang,
1154 $line->special_code,
1155 $fk_parent_line,
1156 $line->fk_fournprice,
1157 $line->pa_ht,
1158 $line->label,
1159 $line->array_options,
1160 $line->fk_unit,
1161 (string) $origintype,
1162 $originid,
1163 0,
1164 $line->ref_ext,
1165 1
1166 );
1167
1168 if ($result < 0) {
1169 if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER) {
1170 $this->error = $this->db->lasterror();
1171 $this->errors[] = $this->error;
1172 dol_print_error($this->db);
1173 }
1174 $this->db->rollback();
1175 return -1;
1176 }
1177
1178 // Keep the extra parameters of the source line (for example the options of subtotal lines): addline() can't
1179 // do it when the object is cloned, because the origin it receives is the one of the source line, not the source line
1180 if ($result > 0 && !empty($line->extraparams)) {
1181 $newline = new OrderLine($this->db);
1182 $newline->id = $result;
1183 $newline->extraparams = $line->extraparams;
1184 $newline->setExtraParameters();
1185 }
1186
1187 // Defined the new fk_parent_line
1188 if ($result > 0 && $line->product_type == 9) {
1189 $fk_parent_line = $result;
1190 }
1191 }
1192
1193 $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.
1194
1195 // update ref
1196 $initialref = '(PROV'.$this->id.')';
1197 if (!empty($this->ref)) {
1198 $initialref = $this->ref;
1199 }
1200
1201 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id);
1202 if ($this->db->query($sql)) {
1203 $this->ref = $initialref;
1204
1205 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
1206 $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
1207 }
1208
1209 // Add object linked
1210 if (!empty($this->linked_objects) && is_array($this->linked_objects)) {
1211 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
1212 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, ...))
1213 foreach ($tmp_origin_id as $origin_id) {
1214 $ret = $this->add_object_linked($origin, $origin_id);
1215 if (!$ret) {
1216 $this->error = $this->db->lasterror();
1217 $error++;
1218 }
1219 }
1220 } else { // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1221 $origin_id = $tmp_origin_id;
1222 $ret = $this->add_object_linked($origin, $origin_id);
1223 if (!$ret) {
1224 $this->error = $this->db->lasterror();
1225 $error++;
1226 }
1227 }
1228 }
1229 }
1230
1231 if (!$error && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
1232 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
1233 $originidforcontact = $this->origin_id;
1234 if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
1235 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1236 $exp = new Expedition($this->db);
1237 $exp->fetch($this->origin_id);
1238 $exp->fetchObjectLinked();
1239 if (count($exp->linkedObjectsIds['commande']) > 0) {
1240 foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1241 $originforcontact = 'commande';
1242 if (is_object($value)) {
1243 $originidforcontact = $value->id;
1244 } else {
1245 $originidforcontact = $value;
1246 }
1247 break; // We take first one
1248 }
1249 }
1250 }
1251
1252 $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";
1253 $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
1254
1255 $resqlcontact = $this->db->query($sqlcontact);
1256 if ($resqlcontact) {
1257 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
1258 //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1259 $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
1260 }
1261 } else {
1262 dol_print_error($this->db);
1263 }
1264 }
1265
1266 if (!$error) {
1267 $result = $this->insertExtraFields();
1268 if ($result < 0) {
1269 $error++;
1270 }
1271 }
1272
1273 if (!$error && !$notrigger) {
1274 // Call trigger
1275 $result = $this->call_trigger('ORDER_CREATE', $user);
1276 if ($result < 0) {
1277 $error++;
1278 }
1279 // End call triggers
1280 }
1281
1282 if (!$error) {
1283 $this->db->commit();
1284 return $this->id;
1285 } else {
1286 $this->db->rollback();
1287 return -1 * $error;
1288 }
1289 } else {
1290 $this->error = $this->db->lasterror();
1291 $this->db->rollback();
1292 return -1;
1293 }
1294 }
1295
1296 return 0;
1297 } else {
1298 $this->error = $this->db->lasterror();
1299 $this->db->rollback();
1300 return -1;
1301 }
1302 }
1303
1304
1313 public function createFromClone(User $user, $socid = 0, $forceentity = null)
1314 {
1315 global $hookmanager;
1316
1317 $error = 0;
1318
1319 $object = new self($this->db);
1320
1321 $this->db->begin();
1322
1323 // Load source object
1324 $object->fetch($this->id);
1325
1326 $objFrom = clone $object;
1327
1328 // Change socid if needed
1329 if (!empty($socid) && $socid != $object->socid) {
1330 $objsoc = new Societe($this->db);
1331
1332 if ($objsoc->fetch($socid) > 0) {
1333 $object->socid = $objsoc->id;
1334 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1335 $object->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : '0');
1336 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1337 $object->fk_project = 0;
1338 $object->fk_delivery_address = 0;
1339 }
1340
1341 // TODO Change product price if multi-prices
1342 }
1343
1344 $object->entity = (!empty($forceentity) ? $forceentity : $object->entity);
1345
1346 $object->id = 0;
1347 $object->ref = '';
1348 $object->statut = self::STATUS_DRAFT; // deprecated
1349 $object->status = self::STATUS_DRAFT;
1350
1351 // Clear fields
1352 $object->user_author_id = $user->id;
1353 $object->user_validation_id = 0;
1354 $object->date = dol_now();
1355 $object->date_commande = dol_now();
1356 $object->date_creation = '';
1357 $object->date_validation = '';
1358 if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
1359 $object->ref_client = '';
1360 $object->ref_customer = '';
1361 }
1362
1363 // Do not clone ref_ext
1364 $num = count($object->lines);
1365 for ($i = 0; $i < $num; $i++) {
1366 $object->lines[$i]->ref_ext = '';
1367 }
1368
1369 // Create clone
1370 $object->context['createfromclone'] = 'createfromclone';
1371 $result = $object->create($user);
1372 if ($result < 0) {
1373 $error++;
1374 $this->setErrorsFromObject($object);
1375 }
1376
1377 if (!$error) {
1378 // copy internal contacts
1379 if ($object->copy_linked_contact($objFrom, 'internal') < 0) {
1380 $error++;
1381 }
1382 }
1383
1384 if (!$error) {
1385 // copy external contacts if same company
1386 if ($object->socid == $objFrom->socid) {
1387 if ($object->copy_linked_contact($objFrom, 'external') < 0) {
1388 $error++;
1389 }
1390 }
1391 }
1392
1393 if (!$error) {
1394 // Hook of thirdparty module
1395 if (is_object($hookmanager)) {
1396 $parameters = array('objFrom' => $objFrom, 'clonedObj' => $object);
1397 $action = '';
1398 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1399 if ($reshook < 0) {
1400 $this->setErrorsFromObject($hookmanager);
1401 $error++;
1402 }
1403 }
1404 }
1405
1406 unset($object->context['createfromclone']);
1407
1408 // End
1409 if (!$error) {
1410 $this->db->commit();
1411 return $object->id;
1412 } else {
1413 $this->db->rollback();
1414 return -1;
1415 }
1416 }
1417
1418
1426 public function createFromProposal($object, User $user)
1427 {
1428 global $conf, $hookmanager, $langs;
1429
1430 require_once DOL_DOCUMENT_ROOT . '/multicurrency/class/multicurrency.class.php';
1431 require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
1432
1433 $error = 0;
1434
1435 $this->date_commande = dol_now();
1436 $this->date = dol_now();
1437 $this->source = 0;
1438
1439 $num = count($object->lines);
1440 for ($i = 0; $i < $num; $i++) {
1441 $line = new OrderLine($this->db);
1442
1443 $line->libelle = $object->lines[$i]->libelle;
1444 $line->label = $object->lines[$i]->label;
1445 $line->desc = $object->lines[$i]->desc;
1446 $line->price = $object->lines[$i]->price;
1447 $line->subprice = $object->lines[$i]->subprice;
1448 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1449 $line->tva_tx = $object->lines[$i]->tva_tx;
1450 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1451 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1452 $line->qty = $object->lines[$i]->qty;
1453 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1454 $line->remise_percent = $object->lines[$i]->remise_percent;
1455 $line->fk_product = $object->lines[$i]->fk_product;
1456 $line->info_bits = $object->lines[$i]->info_bits;
1457 $line->product_type = $object->lines[$i]->product_type;
1458 $line->rang = $object->lines[$i]->rang;
1459 $line->special_code = $object->lines[$i]->special_code;
1460 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1461 $line->fk_unit = $object->lines[$i]->fk_unit;
1462
1463 $line->date_start = $object->lines[$i]->date_start;
1464 $line->date_end = $object->lines[$i]->date_end;
1465
1466 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1467 $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);
1468 $line->pa_ht = $marginInfos[0];
1469 $line->marge_tx = $marginInfos[1];
1470 $line->marque_tx = $marginInfos[2];
1471
1472 $line->origin = $object->element;
1473 $line->origin_id = $object->lines[$i]->id;
1474
1475 // get extrafields from original line
1476 $object->lines[$i]->fetch_optionals();
1477 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1478 $line->array_options[$options_key] = $value;
1479 }
1480
1481 $this->lines[$i] = $line;
1482 }
1483
1484 $this->entity = $object->entity;
1485 $this->socid = $object->socid;
1486 $this->fk_project = $object->fk_project;
1487 $this->cond_reglement_id = $object->cond_reglement_id;
1488 $this->deposit_percent = $object->deposit_percent;
1489 $this->mode_reglement_id = $object->mode_reglement_id;
1490 $this->fk_account = $object->fk_account;
1491 $this->fk_incoterms = $object->fk_incoterms;
1492 $this->location_incoterms = $object->location_incoterms;
1493 $this->availability_id = $object->availability_id;
1494 $this->demand_reason_id = $object->demand_reason_id;
1495 $this->delivery_date = $object->delivery_date;
1496 $this->shipping_method_id = $object->shipping_method_id;
1497 $this->warehouse_id = $object->warehouse_id;
1498 $this->fk_delivery_address = $object->fk_delivery_address;
1499 $this->contact_id = $object->contact_id;
1500 $this->ref_client = $object->ref_client;
1501 $this->ref_customer = $object->ref_client;
1502
1503 if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
1504 $this->note_private = $object->note_private;
1505 $this->note_public = $object->note_public;
1506 }
1507
1508 $this->origin = $object->element;
1509 $this->origin_id = $object->id;
1510
1511 // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
1512 if (isModEnabled('multicurrency')) {
1513 if (!empty($object->multicurrency_code)) {
1514 $this->multicurrency_code = $object->multicurrency_code;
1515 }
1516 if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($object->multicurrency_tx)) {
1517 $this->multicurrency_tx = $object->multicurrency_tx;
1518 }
1519
1520 if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
1521 $tmparray = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date_commande);
1522 $this->fk_multicurrency = $tmparray[0];
1523 $this->multicurrency_tx = $tmparray[1];
1524 } else {
1525 $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
1526 }
1527 if (empty($this->fk_multicurrency)) {
1528 $this->multicurrency_code = $conf->currency;
1529 $this->fk_multicurrency = 0;
1530 $this->multicurrency_tx = 1;
1531 }
1532 }
1533
1534 // get extrafields from original line
1535 $object->fetch_optionals();
1536
1537 $e = new ExtraFields($this->db);
1538 $element_extrafields = $e->fetch_name_optionals_label($this->table_element);
1539
1540 foreach ($object->array_options as $options_key => $value) {
1541 if (array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)) {
1542 $this->array_options[$options_key] = $value;
1543 }
1544 }
1545 // Possibility to add external linked objects with hooks
1546 $this->linked_objects[$this->origin] = $this->origin_id;
1547 if (isset($object->other_linked_objects) && is_array($object->other_linked_objects) && !empty($object->other_linked_objects)) {
1548 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1549 }
1550
1551 $ret = $this->create($user);
1552
1553 if ($ret > 0) {
1554 // Actions hooked (by external module)
1555 $hookmanager->initHooks(array('orderdao'));
1556
1557 $parameters = array('objFrom' => $object);
1558 $action = '';
1559 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1560 if ($reshook < 0) {
1561 $this->setErrorsFromObject($hookmanager);
1562 $error++;
1563 }
1564
1565 if (!$error) {
1566 // Validate immediately the order
1567 if (getDolGlobalString('ORDER_VALID_AFTER_CLOSE_PROPAL')) {
1568 $this->fetch($ret);
1569 $result = $this->valid($user);
1570 if ($result > 0 && !getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1571 $this->fetch($this->id);
1572 $this->fetch_thirdparty();
1573
1574 $outputlangs = $langs;
1575 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($this->thirdparty->default_lang)) {
1576 $outputlangs = new Translate('', $conf);
1577 $outputlangs->setDefaultLang($this->thirdparty->default_lang);
1578 $outputlangs->loadLangs(array('main', 'orders'));
1579 }
1580
1581 $this->generateDocument($this->model_pdf, $outputlangs);
1582 }
1583 }
1584 return $ret;
1585 } else {
1586 return -1;
1587 }
1588 } else {
1589 return -1;
1590 }
1591 }
1592
1593
1633 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)
1634 {
1635 global $mysoc, $langs, $user;
1636
1637 $logtext = "::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent";
1638 $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";
1639 $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";
1640 dol_syslog(get_class($this).$logtext, LOG_DEBUG);
1641
1642 if ($this->status == self::STATUS_DRAFT) {
1643 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1644
1645 // Clean parameters
1646
1647 if (empty($remise_percent)) {
1648 $remise_percent = 0;
1649 }
1650 if (empty($qty)) {
1651 $qty = 0;
1652 }
1653 if (empty($info_bits)) {
1654 $info_bits = 0;
1655 }
1656 if (empty($rang)) {
1657 $rang = 0;
1658 }
1659 if (empty($txtva)) {
1660 $txtva = 0;
1661 }
1662 if (empty($txlocaltax1)) {
1663 $txlocaltax1 = 0;
1664 }
1665 if (empty($txlocaltax2)) {
1666 $txlocaltax2 = 0;
1667 }
1668 if (empty($fk_parent_line) || $fk_parent_line < 0) {
1669 $fk_parent_line = 0;
1670 }
1671 if (empty($this->fk_multicurrency)) {
1672 $this->fk_multicurrency = 0;
1673 }
1674 if (empty($ref_ext)) {
1675 $ref_ext = '';
1676 }
1677
1678 $remise_percent = (float) price2num($remise_percent);
1679 $qty = (float) price2num($qty);
1680 $pu_ht = price2num($pu_ht);
1681 $pu_ht_devise = price2num($pu_ht_devise);
1682 $pu_ttc = price2num($pu_ttc);
1683 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
1684 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
1685 $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
1686 }
1687 $txlocaltax1 = price2num($txlocaltax1);
1688 $txlocaltax2 = price2num($txlocaltax2);
1689 if ($price_base_type == 'HT') {
1690 $pu = $pu_ht;
1691 } else {
1692 $pu = $pu_ttc;
1693 }
1694 $label = trim($label);
1695 $desc = trim($desc);
1696
1697 // Check parameters
1698 if ($type < 0) {
1699 return -1;
1700 }
1701
1702 if ($date_start && $date_end && $date_start > $date_end) {
1703 $langs->load("errors");
1704 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
1705 return -1;
1706 }
1707
1708 $this->db->begin();
1709
1710 $product_type = $type;
1711 if (!empty($fk_product) && $fk_product > 0) {
1712 $product = new Product($this->db);
1713 $result = $product->fetch($fk_product);
1714 $product_type = $product->type;
1715
1716 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_ORDER') && $product->isStockManaged()) {
1717 // get real stock
1718 $productChildrenNb = 0;
1719 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
1720 $productChildrenNb = $product->hasFatherOrChild(1);
1721 }
1722 if ($productChildrenNb > 0) {
1723 // compute real stock from each subcomponent
1724 $product_stock = null;
1725 $product->loadStockForVirtualProduct('warehouseopen', $qty);
1726 foreach ($product->stock_warehouse as $componentStockWarehouse) {
1727 if ($product_stock === null) {
1728 $product_stock = $componentStockWarehouse->real;
1729 } else {
1730 $product_stock = min($product_stock, $componentStockWarehouse->real);
1731 }
1732 }
1733 if ($product_stock === null) {
1734 $product_stock = 0;
1735 }
1736 } else {
1737 $product_stock = $product->stock_reel;
1738 }
1739
1740 if ($product_stock < $qty) {
1741 $langs->load("errors");
1742 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
1743 $this->errors[] = $this->error;
1744 dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
1745 $this->db->rollback();
1747 }
1748 }
1749 }
1750 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
1751 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
1752 // and this is done at the line level, which has its own VAT rate
1753
1754 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
1755
1756 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
1757 $tmpproduct = new Product($this->db);
1758 $result = $tmpproduct->fetch($fk_product);
1759 $newqty = $this->roundQtyToPackaging($qty, $tmpproduct->packaging);
1760 if ($newqty != $qty) {
1761 $qty = $newqty;
1762 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
1763 }
1764 }
1765
1766 // Clean vat code
1767 $reg = array();
1768 $vat_src_code = '';
1769 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
1770 $vat_src_code = $reg[1];
1771 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
1772 }
1773
1774 $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);
1775
1776 /*var_dump($txlocaltax1);
1777 var_dump($txlocaltax2);
1778 var_dump($localtaxes_type);
1779 var_dump($tabprice);
1780 var_dump($tabprice[9]);
1781 var_dump($tabprice[10]);
1782 exit;*/
1783
1784 $total_ht = $tabprice[0];
1785 $total_tva = $tabprice[1];
1786 $total_ttc = $tabprice[2];
1787 $total_localtax1 = $tabprice[9];
1788 $total_localtax2 = $tabprice[10];
1789 $pu_ht = $tabprice[3];
1790
1791 // MultiCurrency
1792 $multicurrency_total_ht = $tabprice[16];
1793 $multicurrency_total_tva = $tabprice[17];
1794 $multicurrency_total_ttc = $tabprice[18];
1795 $pu_ht_devise = $tabprice[19];
1796
1797 // Rang to use
1798 $ranktouse = $rang;
1799
1800 if (empty($ranktouse) || $ranktouse == -1) {
1801 $rangmax = $this->line_max($fk_parent_line);
1802 $ranktouse = $rangmax + 1;
1803 }
1804
1805 // Insert line
1806 $this->line = new OrderLine($this->db);
1807
1808 $this->line->context = $this->context;
1809
1810 $this->line->fk_commande = $this->id;
1811 $this->line->label = $label;
1812 $this->line->desc = $desc;
1813 $this->line->qty = (float) $qty;
1814 $this->line->ref_ext = $ref_ext;
1815
1816 $this->line->vat_src_code = $vat_src_code;
1817 $this->line->tva_tx = $txtva;
1818 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
1819 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
1820 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
1821 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
1822 $this->line->fk_product = $fk_product;
1823 $this->line->product_type = $product_type;
1824 $this->line->fk_remise_except = $fk_remise_except;
1825 $this->line->remise_percent = $remise_percent;
1826 $this->line->subprice = (float) $pu_ht;
1827 $this->line->rang = $ranktouse;
1828 $this->line->info_bits = $info_bits;
1829 $this->line->total_ht = (float) $total_ht;
1830 $this->line->total_tva = (float) $total_tva;
1831 $this->line->total_localtax1 = (float) $total_localtax1;
1832 $this->line->total_localtax2 = (float) $total_localtax2;
1833 $this->line->total_ttc = (float) $total_ttc;
1834 $this->line->special_code = $special_code;
1835 if (empty($qty) && empty($special_code)) {
1836 $this->line->special_code = 3;
1837 }
1838 $this->line->origin = $origin;
1839 $this->line->origin_type = $origin;
1840 $this->line->origin_id = $origin_id;
1841
1842 $this->line->fk_parent_line = $fk_parent_line;
1843 $this->line->fk_unit = $fk_unit;
1844
1845 $this->line->date_start = $date_start;
1846 $this->line->date_end = $date_end;
1847
1848 $this->line->fk_fournprice = $fk_fournprice;
1849 $this->line->pa_ht = $pa_ht; // Can be '' when not defined or 0 if defined to 0 or a price value
1850
1851 // Multicurrency
1852 $this->line->fk_multicurrency = $this->fk_multicurrency;
1853 $this->line->multicurrency_code = $this->multicurrency_code;
1854 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
1855 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
1856 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
1857 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
1858
1859 if (is_array($array_options) && count($array_options) > 0) {
1860 $this->line->array_options = $array_options;
1861 }
1862
1863 $result = $this->line->insert($user);
1864 if ($result > 0) {
1865 // Update denormalized fields at the order level
1866 if (empty($noupdateafterinsertline)) {
1867 $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.
1868 }
1869
1870 if ($result > 0) {
1871 if (!isset($this->context['createfromclone'])) {
1872 if (!empty($fk_parent_line)) {
1873 // Always reorder if child line
1874 $this->line_order(true, 'DESC');
1875 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
1876 // Update all rank of all other lines starting from the same $ranktouse
1877 foreach ($this->lines as $tmpline) {
1878 if ($tmpline->rang >= $ranktouse) {
1879 if (!empty($tmpline->id)) {
1880 $this->updateRangOfLine($tmpline->id, $tmpline->rang + 1);
1881 }
1882 }
1883 }
1884 }
1885
1886 $this->lines[] = $this->line;
1887 } else {
1888 // Loop on all lines of parent object
1889 foreach ($this->lines as $tmpline) {
1890 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
1891 $this->line->extraparams = $tmpline->extraparams;
1892 $this->line->setExtraParameters();
1893 }
1894 }
1895 }
1896
1897 $this->db->commit();
1898 return $this->line->id;
1899 } else {
1900 $this->db->rollback();
1901 return -1;
1902 }
1903 } else {
1904 $this->setErrorsFromObject($this->line);
1905 dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
1906 $this->db->rollback();
1907 return -2;
1908 }
1909 } else {
1910 dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR);
1911 return -3;
1912 }
1913 }
1914
1915
1916 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1930 public function add_product($idproduct, $qty, $remise_percent = 0.0, $date_start = '', $date_end = '')
1931 {
1932 // phpcs:enable
1933 global $conf, $mysoc;
1934
1935 if (!$qty) {
1936 $qty = 1;
1937 }
1938
1939 if ($idproduct > 0) {
1940 $prod = new Product($this->db);
1941 $prod->fetch($idproduct);
1942
1943 $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
1944 $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
1945 if (empty($tva_tx)) {
1946 $tva_npr = 0;
1947 }
1948 $vat_src_code = ''; // May be defined into tva_tx
1949
1950 $localtax1_tx = get_localtax($tva_tx, 1, $this->thirdparty, $mysoc, $tva_npr);
1951 $localtax2_tx = get_localtax($tva_tx, 2, $this->thirdparty, $mysoc, $tva_npr);
1952
1953 // multiprix
1954 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $this->thirdparty->price_level) {
1955 $price = $prod->multiprices[$this->thirdparty->price_level];
1956 $price_ttc = $prod->multiprices_ttc[$this->thirdparty->price_level];
1957 } else {
1958 $price = $prod->price;
1959 $price_ttc = $prod->price_ttc;
1960 }
1961
1962 $line = new OrderLine($this->db);
1963
1964 $line->context = $this->context;
1965
1966 $line->fk_product = $idproduct;
1967 $line->desc = $prod->description;
1968 $line->qty = $qty;
1969 $line->subprice = $price;
1970 $line->subprice_ttc = $price_ttc;
1971 $line->remise_percent = $remise_percent;
1972 $line->vat_src_code = $vat_src_code;
1973 $line->tva_tx = $tva_tx;
1974 $line->localtax1_tx = $localtax1_tx;
1975 $line->localtax2_tx = $localtax2_tx;
1976
1977 $line->product_ref = $prod->ref;
1978 $line->product_label = $prod->label;
1979 $line->product_desc = $prod->description;
1980 $line->fk_unit = $prod->fk_unit;
1981
1982 // Save the start and end date of the line in the object
1983 if ($date_start) {
1984 $line->date_start = $date_start;
1985 }
1986 if ($date_end) {
1987 $line->date_end = $date_end;
1988 }
1989
1990 $this->lines[] = $line;
1991
2009 }
2010 }
2011
2012
2022 public function fetch($id, $ref = '', $ref_ext = '', $notused = '')
2023 {
2024 // Check parameters
2025 if (empty($id) && empty($ref) && empty($ref_ext)) {
2026 return -1;
2027 }
2028
2029 $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';
2030 $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';
2031 $sql .= ', c.fk_account';
2032 $sql .= ', c.date_commande, c.date_valid, c.tms';
2033 $sql .= ', c.date_livraison as delivery_date';
2034 $sql .= ', c.fk_shipping_method';
2035 $sql .= ', c.fk_warehouse';
2036 $sql .= ', c.fk_projet as fk_project, c.source, c.facture as billed';
2037 $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';
2038 $sql .= ', c.fk_incoterms, c.location_incoterms';
2039 $sql .= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
2040 $sql .= ", c.module_source, c.pos_source";
2041 $sql .= ", i.libelle as label_incoterms";
2042 $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2043 $sql .= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
2044 $sql .= ', ca.code as availability_code, ca.label as availability_label';
2045 $sql .= ', dr.code as demand_reason_code';
2046 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as c';
2047 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid';
2048 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id';
2049 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
2050 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = dr.rowid';
2051 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
2052
2053 if ($id) {
2054 $sql .= " WHERE c.rowid = ".((int) $id);
2055 } else {
2056 $sql .= " WHERE c.entity IN (".getEntity('commande').")"; // Don't use entity if you use rowid
2057 }
2058
2059 if ($ref) {
2060 $sql .= " AND c.ref = '".$this->db->escape($ref)."'";
2061 }
2062 if ($ref_ext) {
2063 $sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'";
2064 }
2065
2066 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2067 $result = $this->db->query($sql);
2068 if ($result) {
2069 $obj = $this->db->fetch_object($result);
2070 if ($obj) {
2071 $this->id = $obj->rowid;
2072 $this->entity = $obj->entity;
2073
2074 $this->ref = $obj->ref;
2075 $this->ref_client = $obj->ref_client;
2076 $this->ref_customer = $obj->ref_client;
2077 $this->ref_ext = $obj->ref_ext;
2078
2079 $this->socid = $obj->fk_soc;
2080 $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
2081
2082 $this->fk_project = $obj->fk_project;
2083 $this->project = null; // Clear if another value was already set by fetch_projet
2084
2085 $this->statut = $obj->status; // deprecated
2086 $this->status = $obj->status;
2087
2088 $this->user_author_id = $obj->fk_user_author;
2089 $this->user_creation_id = $obj->fk_user_author;
2090 $this->user_validation_id = $obj->fk_user_valid;
2091 $this->user_modification_id = $obj->fk_user_modif;
2092 $this->total_ht = $obj->total_ht;
2093 $this->total_tva = $obj->total_tva;
2094 $this->total_localtax1 = $obj->total_localtax1;
2095 $this->total_localtax2 = $obj->total_localtax2;
2096 $this->total_ttc = $obj->total_ttc;
2097 $this->date = $this->db->jdate($obj->date_commande);
2098 $this->date_commande = $this->db->jdate($obj->date_commande);
2099 $this->date_creation = $this->db->jdate($obj->date_creation);
2100 $this->date_validation = $this->db->jdate($obj->date_valid);
2101 $this->date_modification = $this->db->jdate($obj->tms);
2102 $this->source = $obj->source;
2103 $this->billed = $obj->billed;
2104 $this->note = $obj->note_private; // deprecated
2105 $this->note_private = $obj->note_private;
2106 $this->note_public = $obj->note_public;
2107 $this->model_pdf = $obj->model_pdf;
2108 $this->last_main_doc = $obj->last_main_doc;
2109 $this->mode_reglement_id = $obj->fk_mode_reglement;
2110 $this->mode_reglement_code = $obj->mode_reglement_code;
2111 $this->mode_reglement = $obj->mode_reglement_libelle;
2112 $this->cond_reglement_id = $obj->fk_cond_reglement;
2113 $this->cond_reglement_code = $obj->cond_reglement_code;
2114 $this->cond_reglement = $obj->cond_reglement_libelle;
2115 $this->cond_reglement_label = $obj->cond_reglement_libelle;
2116 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2117 $this->deposit_percent = $obj->deposit_percent;
2118 $this->fk_account = $obj->fk_account;
2119 $this->availability_id = $obj->fk_availability;
2120 $this->availability_code = $obj->availability_code;
2121 $this->availability = $obj->availability_label;
2122 $this->demand_reason_id = $obj->fk_input_reason;
2123 $this->demand_reason_code = $obj->demand_reason_code;
2124 $this->delivery_date = $this->db->jdate($obj->delivery_date);
2125 $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
2126 $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
2127 $this->fk_delivery_address = $obj->fk_delivery_address;
2128 $this->module_source = $obj->module_source;
2129 $this->pos_source = $obj->pos_source;
2130
2131 //Incoterms
2132 $this->fk_incoterms = $obj->fk_incoterms;
2133 $this->location_incoterms = $obj->location_incoterms;
2134 $this->label_incoterms = $obj->label_incoterms;
2135
2136 // Multicurrency
2137 $this->fk_multicurrency = $obj->fk_multicurrency;
2138 $this->multicurrency_code = $obj->multicurrency_code;
2139 $this->multicurrency_tx = $obj->multicurrency_tx;
2140 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2141 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2142 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2143
2144 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
2145
2146 $this->lines = array();
2147
2148 // Retrieve all extrafield
2149 // fetch optionals attributes and labels
2150 $this->fetch_optionals();
2151
2152 $this->db->free($result);
2153
2154 // Lines
2155 $result = $this->fetch_lines();
2156 if ($result < 0) {
2157 return -3;
2158 }
2159 return 1;
2160 } else {
2161 $this->error = 'Order with id '.$id.' not found sql='.$sql;
2162 return 0;
2163 }
2164 } else {
2165 $this->error = $this->db->error();
2166 return -1;
2167 }
2168 }
2169
2170
2171 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2178 public function insert_discount($idremise)
2179 {
2180 // phpcs:enable
2181 global $langs;
2182
2183 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2184 include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
2185
2186 $this->db->begin();
2187
2188 $remise = new DiscountAbsolute($this->db);
2189 $result = $remise->fetch($idremise);
2190
2191 if ($result > 0) {
2192 if ($remise->fk_facture) { // Protection against multiple submissions
2193 $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
2194 $this->db->rollback();
2195 return -5;
2196 }
2197
2198 $line = new OrderLine($this->db);
2199
2200 $line->fk_commande = $this->id;
2201 $line->fk_remise_except = $remise->id;
2202 $line->desc = $remise->description; // Description for the order line
2203 $line->vat_src_code = $remise->vat_src_code;
2204 $line->tva_tx = $remise->tva_tx;
2205 $line->localtax1_tx = $remise->localtax1_tx;
2206 $line->localtax1_type = $remise->localtax1_type;
2207 $line->localtax2_tx = $remise->localtax1_tx;
2208 $line->localtax2_type = $remise->localtax1_type;
2209 $line->subprice = -(float) $remise->amount_ht;
2210 $line->price = -(float) $remise->amount_ht;
2211 $line->fk_product = 0; // Predefined Product ID
2212 $line->qty = 1;
2213 $line->remise_percent = 0;
2214 $line->rang = -1;
2215 $line->info_bits = 2;
2216
2217 $line->total_ht = -(float) $remise->amount_ht;
2218 $line->total_tva = -(float) $remise->amount_tva;
2219 $line->total_ttc = -(float) $remise->amount_ttc;
2220 $line->total_localtax1 = -(float) $remise->total_localtax1;
2221 $line->total_localtax2 = -(float) $remise->total_localtax2;
2222
2223 $result = $line->insert();
2224 if ($result > 0) {
2225 $result = $this->update_price(1);
2226 if ($result > 0) {
2227 $this->db->commit();
2228 return 1;
2229 } else {
2230 $this->db->rollback();
2231 return -1;
2232 }
2233 } else {
2234 $this->setErrorsFromObject($line);
2235 $this->db->rollback();
2236 return -2;
2237 }
2238 } else {
2239 $this->db->rollback();
2240 return -2;
2241 }
2242 }
2243
2244
2245 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2253 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2254 {
2255 // phpcs:enable
2256 $this->lines = array();
2257
2258 $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,';
2259 $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,';
2260 $sql .= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
2261 $sql .= ' l.fk_unit, l.extraparams,';
2262 $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,';
2263 $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,';
2264 $sql .= ' p.customcode, p.fk_country as country_id, c.code as country_code,';
2265 $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units, p.packaging';
2266 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as l';
2267 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
2268 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON c.rowid = p.fk_country';
2269 $sql .= ' WHERE l.fk_commande = '.((int) $this->id);
2270 if ($only_product) {
2271 $sql .= ' AND p.fk_product_type = 0';
2272 }
2273 $sql .= ' ORDER BY l.rang, l.rowid';
2274
2275 dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
2276 $result = $this->db->query($sql);
2277 if ($result) {
2278 $num = $this->db->num_rows($result);
2279
2280 $i = 0;
2281 while ($i < $num) {
2282 $objp = $this->db->fetch_object($result);
2283
2284 $line = new OrderLine($this->db);
2285
2286 $line->rowid = $objp->rowid;
2287 $line->id = $objp->rowid;
2288 $line->fk_commande = $objp->fk_commande;
2289 $line->commande_id = $objp->fk_commande;
2290 $line->label = $objp->custom_label;
2291 $line->desc = $objp->description;
2292 $line->description = $objp->description; // Description line
2293 $line->product_type = $objp->product_type;
2294 $line->qty = $objp->qty;
2295 $line->ref_ext = $objp->ref_ext;
2296
2297 $line->vat_src_code = $objp->vat_src_code;
2298 $line->tva_tx = $objp->tva_tx;
2299 $line->localtax1_tx = $objp->localtax1_tx;
2300 $line->localtax2_tx = $objp->localtax2_tx;
2301 $line->localtax1_type = $objp->localtax1_type;
2302 $line->localtax2_type = $objp->localtax2_type;
2303 $line->total_ht = $objp->total_ht;
2304 $line->total_ttc = $objp->total_ttc;
2305 $line->total_tva = $objp->total_tva;
2306 $line->total_localtax1 = $objp->total_localtax1;
2307 $line->total_localtax2 = $objp->total_localtax2;
2308 $line->subprice = (float) $objp->subprice;
2309 $line->subprice_ttc = (float) $objp->subprice_ttc;
2310 $line->fk_remise_except = $objp->fk_remise_except;
2311 $line->remise_percent = $objp->remise_percent;
2312 $line->price = $objp->price;
2313 $line->fk_product = $objp->fk_product;
2314 $line->fk_fournprice = $objp->fk_fournprice;
2315 $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2316 $line->pa_ht = $marginInfos[0];
2317 $line->marge_tx = $marginInfos[1];
2318 $line->marque_tx = $marginInfos[2];
2319 $line->rang = $objp->rang;
2320 $line->info_bits = $objp->info_bits;
2321 $line->special_code = $objp->special_code;
2322 $line->fk_parent_line = $objp->fk_parent_line;
2323
2324 $line->ref = $objp->product_ref;
2325 $line->libelle = $objp->product_label;
2326
2327 $line->product_ref = $objp->product_ref;
2328 $line->product_label = $objp->product_label;
2329 $line->product_tosell = $objp->product_tosell;
2330 $line->product_tobuy = $objp->product_tobuy;
2331 $line->product_desc = $objp->product_desc;
2332 $line->product_tobatch = $objp->product_tobatch;
2333 $line->product_barcode = $objp->product_barcode;
2334 $line->product_custom_code = $objp->customcode;
2335 $line->product_custom_country_id = $objp->country_id;
2336 $line->product_custom_country_code = $objp->country_code;
2337
2338 $line->fk_product_type = $objp->fk_product_type; // Product or service
2339 $line->fk_unit = $objp->fk_unit;
2340
2341 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams, true) : array();
2342
2343 $line->weight = $objp->weight;
2344 $line->weight_units = $objp->weight_units;
2345 $line->volume = $objp->volume;
2346 $line->volume_units = $objp->volume_units;
2347 $line->packaging = $objp->packaging;
2348
2349 $line->date_start = $this->db->jdate($objp->date_start);
2350 $line->date_end = $this->db->jdate($objp->date_end);
2351
2352 // Multicurrency
2353 $line->fk_multicurrency = $objp->fk_multicurrency;
2354 $line->multicurrency_code = $objp->multicurrency_code;
2355 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2356 $line->multicurrency_subprice_ttc = $objp->multicurrency_subprice_ttc;
2357 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2358 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2359 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2360
2361 $line->fetch_optionals();
2362
2363 // multilangs
2364 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2365 $tmpproduct = new Product($this->db);
2366 $tmpproduct->fetch($objp->fk_product);
2367 $tmpproduct->getMultiLangs();
2368
2369 $line->multilangs = $tmpproduct->multilangs;
2370 }
2371
2372 $this->lines[$i] = $line;
2373
2374 $i++;
2375 }
2376
2377 $this->db->free($result);
2378
2379 return 1;
2380 } else {
2381 $this->error = $this->db->error();
2382 return -3;
2383 }
2384 }
2385
2386
2392 public function getNbOfProductsLines()
2393 {
2394 $nb = 0;
2395 foreach ($this->lines as $line) {
2396 if ($line->product_type == 0) {
2397 $nb++;
2398 }
2399 }
2400 return $nb;
2401 }
2402
2408 public function getNbOfServicesLines()
2409 {
2410 $nb = 0;
2411 foreach ($this->lines as $line) {
2412 if ($line->product_type == 1) {
2413 $nb++;
2414 }
2415 }
2416 return $nb;
2417 }
2418
2424 public function getNbOfShipments()
2425 {
2426 $nb = 0;
2427
2428 $sql = 'SELECT COUNT(DISTINCT ed.fk_expedition) as nb';
2429 $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
2430 $sql .= ' '.MAIN_DB_PREFIX.$this->table_element_line.' as cd';
2431 $sql .= ' WHERE';
2432 $sql .= ' ed.fk_elementdet = cd.rowid';
2433 $sql .= ' AND cd.fk_commande = '.((int) $this->id);
2434 //print $sql;
2435
2436 dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG);
2437 $resql = $this->db->query($sql);
2438 if ($resql) {
2439 $obj = $this->db->fetch_object($resql);
2440 if ($obj) {
2441 $nb = (int) $obj->nb;
2442 }
2443
2444 $this->db->free($resql);
2445 return $nb;
2446 } else {
2447 $this->error = $this->db->lasterror();
2448 return -1;
2449 }
2450 }
2451
2460 public function loadExpeditions($filtre_statut = -1, $fk_product = 0)
2461 {
2462 $this->expeditions = array();
2463
2464 $sql = 'SELECT cd.rowid, cd.fk_product,';
2465 $sql .= ' sum(ed.qty) as qty';
2466 $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
2467 if ($filtre_statut >= 0) {
2468 $sql .= ' '.MAIN_DB_PREFIX.'expedition as e,';
2469 }
2470 $sql .= ' '.MAIN_DB_PREFIX.$this->table_element_line.' as cd';
2471 $sql .= ' WHERE';
2472 if ($filtre_statut >= 0) {
2473 $sql .= ' ed.fk_expedition = e.rowid AND';
2474 }
2475 $sql .= ' ed.fk_elementdet = cd.rowid';
2476 $sql .= ' AND cd.fk_commande = '.((int) $this->id);
2477 if ($fk_product > 0) {
2478 $sql .= ' AND cd.fk_product = '.((int) $fk_product);
2479 }
2480 if ($filtre_statut >= 0) {
2481 $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut);
2482 }
2483 $sql .= ' GROUP BY cd.rowid, cd.fk_product';
2484 //print $sql;
2485
2486 dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG);
2487 $resql = $this->db->query($sql);
2488 if ($resql) {
2489 $num = $this->db->num_rows($resql);
2490 $i = 0;
2491 while ($i < $num) {
2492 $obj = $this->db->fetch_object($resql);
2493 $this->expeditions[$obj->rowid] = $obj->qty;
2494 $i++;
2495 }
2496 $this->db->free($resql);
2497 return $num;
2498 } else {
2499 $this->error = $this->db->lasterror();
2500 return -1;
2501 }
2502 }
2503
2509 public function countNbOfShipments()
2510 {
2511 $sql = 'SELECT count(*)';
2512 $sql .= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
2513 $sql .= ', '.MAIN_DB_PREFIX.'element_element as el';
2514 $sql .= ' WHERE el.fk_source = '.((int) $this->id);
2515 $sql .= " AND el.sourcetype = 'commande'";
2516 $sql .= " AND el.fk_target = e.rowid";
2517 $sql .= " AND el.targettype = 'shipping'";
2518
2519 $resql = $this->db->query($sql);
2520 if ($resql) {
2521 $row = $this->db->fetch_row($resql);
2522 return $row[0];
2523 } else {
2524 dol_print_error($this->db);
2525 }
2526
2527 return 0;
2528 }
2529
2538 public function deleteLine($user = null, $lineid = 0, $id = 0)
2539 {
2540 if ($this->status == self::STATUS_DRAFT) {
2541 $this->db->begin();
2542
2543 // Delete line
2544 $line = new OrderLine($this->db);
2545
2546 $line->context = $this->context;
2547
2548 // Load data
2549 $line->fetch($lineid);
2550
2551 if ($id <= 0) {
2552 $id = $this->id;
2553 }
2554 if ($id > 0 && (int) $line->fk_commande !== (int) $id) {
2555 $this->db->rollback();
2556 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
2557 return -1;
2558 }
2559
2560 // Memorize previous line for triggers
2561 $staticline = clone $line;
2562 $line->oldline = $staticline;
2563
2564 if ($line->delete($user) > 0) {
2565 $result = $this->update_price(1);
2566
2567 if ($result > 0) {
2568 $this->db->commit();
2569 return 1;
2570 } else {
2571 $this->db->rollback();
2572 $this->error = $this->db->lasterror();
2573 return -1;
2574 }
2575 } else {
2576 $this->db->rollback();
2577 $this->setErrorsFromObject($line);
2578 return -1;
2579 }
2580 } else {
2581 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
2582 return -1;
2583 }
2584 }
2585
2586 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2597 public function set_remise($user, $remise, $notrigger = 0)
2598 {
2599 // phpcs:enable
2600 dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
2601 // @phan-suppress-next-line PhanDeprecatedFunction
2602 return $this->setDiscount($user, $remise, $notrigger);
2603 }
2604
2613 public function setDiscount($user, $remise, $notrigger = 0)
2614 {
2615 $remise = trim((string) $remise) ? trim((string) $remise) : 0;
2616
2617 if ($user->hasRight('commande', 'creer')) {
2618 $error = 0;
2619
2620 $this->db->begin();
2621
2622 $remise = price2num($remise, 2);
2623
2624 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2625 $sql .= ' SET remise_percent = '.((float) $remise);
2626 $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_DRAFT);
2627
2628 dol_syslog(__METHOD__, LOG_DEBUG);
2629 $resql = $this->db->query($sql);
2630 if (!$resql) {
2631 $this->errors[] = $this->db->error();
2632 $error++;
2633 }
2634
2635 if (!$error) {
2636 $this->oldcopy = clone $this;
2637 $this->remise_percent = $remise;
2638 $this->update_price(1);
2639 }
2640
2641 if (!$notrigger && empty($error)) {
2642 // Call trigger
2643 $result = $this->call_trigger('ORDER_MODIFY', $user);
2644 if ($result < 0) {
2645 $error++;
2646 }
2647 // End call triggers
2648 }
2649
2650 if (!$error) {
2651 $this->db->commit();
2652 return 1;
2653 } else {
2654 foreach ($this->errors as $errmsg) {
2655 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2656 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2657 }
2658 $this->db->rollback();
2659 return -1 * $error;
2660 }
2661 }
2662
2663 return 0;
2664 }
2665
2666
2667 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2676 public function set_date($user, $date, $notrigger = 0)
2677 {
2678 // phpcs:enable
2679 if ($user->hasRight('commande', 'creer')) {
2680 $error = 0;
2681
2682 $this->db->begin();
2683
2684 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2685 $sql .= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
2686 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".((int) self::STATUS_DRAFT);
2687
2688 dol_syslog(__METHOD__, LOG_DEBUG);
2689 $resql = $this->db->query($sql);
2690 if (!$resql) {
2691 $this->errors[] = $this->db->error();
2692 $error++;
2693 }
2694
2695 if (!$error) {
2696 $this->oldcopy = clone $this;
2697 $this->date = $date;
2698 }
2699
2700 if (!$notrigger && empty($error)) {
2701 // Call trigger
2702 $result = $this->call_trigger('ORDER_MODIFY', $user);
2703 if ($result < 0) {
2704 $error++;
2705 }
2706 // End call triggers
2707 }
2708
2709 if (!$error) {
2710 $this->db->commit();
2711 return 1;
2712 } else {
2713 foreach ($this->errors as $errmsg) {
2714 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2715 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2716 }
2717 $this->db->rollback();
2718 return -1 * $error;
2719 }
2720 } else {
2721 return -2;
2722 }
2723 }
2724
2725 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2735 public function set_date_livraison($user, $delivery_date, $notrigger = 0)
2736 {
2737 // phpcs:enable
2738 return $this->setDeliveryDate($user, $delivery_date, $notrigger);
2739 }
2740
2749 public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
2750 {
2751 if ($user->hasRight('commande', 'creer')) {
2752 $error = 0;
2753
2754 $this->db->begin();
2755
2756 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2757 $sql .= " SET date_livraison = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
2758 $sql .= " WHERE rowid = ".((int) $this->id);
2759
2760 dol_syslog(__METHOD__, LOG_DEBUG);
2761 $resql = $this->db->query($sql);
2762 if (!$resql) {
2763 $this->errors[] = $this->db->error();
2764 $error++;
2765 }
2766
2767 if (!$error) {
2768 $this->oldcopy = clone $this;
2769 $this->delivery_date = $delivery_date;
2770 }
2771
2772 if (!$notrigger && empty($error)) {
2773 // Call trigger
2774 $result = $this->call_trigger('ORDER_MODIFY', $user);
2775 if ($result < 0) {
2776 $error++;
2777 }
2778 // End call triggers
2779 }
2780
2781 if (!$error) {
2782 $this->db->commit();
2783 return 1;
2784 } else {
2785 foreach ($this->errors as $errmsg) {
2786 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2787 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2788 }
2789 $this->db->rollback();
2790 return -1 * $error;
2791 }
2792 } else {
2793 return -2;
2794 }
2795 }
2796
2797 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2811 public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'c.date_commande', $sortorder = 'DESC')
2812 {
2813 // phpcs:enable
2814 global $user;
2815
2816 $ga = array();
2817
2818 $sql = "SELECT s.rowid, s.nom as name, s.client,";
2819 $sql .= " c.rowid as cid, c.ref";
2820 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2821 $sql .= ", sc.fk_soc, sc.fk_user";
2822 }
2823 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX.$this->table_element." as c";
2824 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2825 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2826 }
2827 $sql .= " WHERE c.entity IN (".getEntity('commande').")";
2828 $sql .= " AND c.fk_soc = s.rowid";
2829 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
2830 $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
2831 }
2832 if ($socid) {
2833 $sql .= " AND s.rowid = ".((int) $socid);
2834 }
2835 if ($draft) {
2836 $sql .= " AND c.fk_statut = ".self::STATUS_DRAFT;
2837 }
2838 if (is_object($excluser)) {
2839 $sql .= " AND c.fk_user_author <> ".((int) $excluser->id);
2840 }
2841 $sql .= $this->db->order($sortfield, $sortorder);
2842 $sql .= $this->db->plimit($limit, $offset);
2843
2844 $result = $this->db->query($sql);
2845 if ($result) {
2846 $numc = $this->db->num_rows($result);
2847 if ($numc) {
2848 $i = 0;
2849 while ($i < $numc) {
2850 $obj = $this->db->fetch_object($result);
2851
2852 if ($shortlist == 1) {
2853 $ga[$obj->cid] = $obj->ref;
2854 } elseif ($shortlist == 2) {
2855 $ga[$obj->cid] = $obj->ref.' ('.$obj->name.')';
2856 } else {
2857 $ga[$i]['id'] = $obj->cid;
2858 $ga[$i]['ref'] = $obj->ref;
2859 $ga[$i]['name'] = $obj->name;
2860 }
2861 $i++;
2862 }
2863 }
2864 return $ga;
2865 } else {
2866 dol_print_error($this->db);
2867 return -1;
2868 }
2869 }
2870
2878 public function availability($availability_id, $notrigger = 0)
2879 {
2880 global $user;
2881
2882 dol_syslog('Commande::availability('.$availability_id.')');
2883 if ($this->status >= self::STATUS_DRAFT) {
2884 $error = 0;
2885
2886 $this->db->begin();
2887
2888 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2889 $sql .= ' SET fk_availability = '.((int) $availability_id);
2890 $sql .= ' WHERE rowid='.((int) $this->id);
2891
2892 dol_syslog(__METHOD__, LOG_DEBUG);
2893 $resql = $this->db->query($sql);
2894 if (!$resql) {
2895 $this->errors[] = $this->db->error();
2896 $error++;
2897 }
2898
2899 if (!$error) {
2900 $this->oldcopy = clone $this;
2901 $this->availability_id = $availability_id;
2902 }
2903
2904 if (!$notrigger && empty($error)) {
2905 // Call trigger
2906 $result = $this->call_trigger('ORDER_MODIFY', $user);
2907 if ($result < 0) {
2908 $error++;
2909 }
2910 // End call triggers
2911 }
2912
2913 if (!$error) {
2914 $this->db->commit();
2915 return 1;
2916 } else {
2917 foreach ($this->errors as $errmsg) {
2918 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2919 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2920 }
2921 $this->db->rollback();
2922 return -1 * $error;
2923 }
2924 } else {
2925 $error_str = 'Command status do not meet requirement '.$this->status;
2926 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2927 $this->error = $error_str;
2928 $this->errors[] = $this->error;
2929 return -2;
2930 }
2931 }
2932
2933 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2941 public function demand_reason($demand_reason_id, $notrigger = 0)
2942 {
2943 // phpcs:enable
2944 global $user;
2945
2946 dol_syslog('Commande::demand_reason('.$demand_reason_id.')');
2947 if ($this->status >= self::STATUS_DRAFT) {
2948 $error = 0;
2949
2950 $this->db->begin();
2951
2952 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2953 $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
2954 $sql .= ' WHERE rowid='.((int) $this->id);
2955
2956 dol_syslog(__METHOD__, LOG_DEBUG);
2957 $resql = $this->db->query($sql);
2958 if (!$resql) {
2959 $this->errors[] = $this->db->error();
2960 $error++;
2961 }
2962
2963 if (!$error) {
2964 $this->oldcopy = clone $this;
2965 $this->demand_reason_id = $demand_reason_id;
2966 }
2967
2968 if (!$notrigger && empty($error)) {
2969 // Call trigger
2970 $result = $this->call_trigger('ORDER_MODIFY', $user);
2971 if ($result < 0) {
2972 $error++;
2973 }
2974 // End call triggers
2975 }
2976
2977 if (!$error) {
2978 $this->db->commit();
2979 return 1;
2980 } else {
2981 foreach ($this->errors as $errmsg) {
2982 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2983 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2984 }
2985 $this->db->rollback();
2986 return -1 * $error;
2987 }
2988 } else {
2989 $error_str = 'order status do not meet requirement '.$this->status;
2990 dol_syslog(__METHOD__.$error_str, LOG_ERR);
2991 $this->error = $error_str;
2992 $this->errors[] = $this->error;
2993 return -2;
2994 }
2995 }
2996
2997 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3006 public function set_ref_client($user, $ref_client, $notrigger = 0)
3007 {
3008 // phpcs:enable
3009 if ($user->hasRight('commande', 'creer')) {
3010 $error = 0;
3011
3012 $this->db->begin();
3013
3014 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
3015 $sql .= ' ref_client = '.(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
3016 $sql .= ' WHERE rowid = '.((int) $this->id);
3017
3018 dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
3019 $resql = $this->db->query($sql);
3020 if (!$resql) {
3021 $this->errors[] = $this->db->error();
3022 $error++;
3023 }
3024
3025 if (!$error) {
3026 $this->oldcopy = clone $this;
3027 $this->ref_client = $ref_client;
3028 $this->ref_customer = $ref_client;
3029 }
3030
3031 if (!$notrigger && empty($error)) {
3032 // Call trigger
3033 $result = $this->call_trigger('ORDER_MODIFY', $user);
3034 if ($result < 0) {
3035 $error++;
3036 }
3037 // End call triggers
3038 }
3039 if (!$error) {
3040 $this->db->commit();
3041 return 1;
3042 } else {
3043 foreach ($this->errors as $errmsg) {
3044 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
3045 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3046 }
3047 $this->db->rollback();
3048 return -1 * $error;
3049 }
3050 } else {
3051 return -1;
3052 }
3053 }
3054
3062 public function classifyBilled(User $user, $notrigger = 0)
3063 {
3064 $error = 0;
3065
3066 if ($this->billed) {
3067 return 0;
3068 }
3069
3070 $this->db->begin();
3071
3072 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET facture = 1';
3073 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
3074
3075 dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
3076 if ($this->db->query($sql)) {
3077 $this->oldcopy = clone $this;
3078 $this->billed = 1;
3079
3080 if (!$notrigger && empty($error)) {
3081 // Call trigger
3082 $result = $this->call_trigger('ORDER_CLASSIFY_BILLED', $user);
3083 if ($result < 0) {
3084 $error++;
3085 }
3086 // End call triggers
3087 }
3088
3089 if (!$error) {
3090 $this->db->commit();
3091 return 1;
3092 } else {
3093 foreach ($this->errors as $errmsg) {
3094 dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR);
3095 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3096 }
3097 $this->db->rollback();
3098 return -1 * $error;
3099 }
3100 } else {
3101 $this->error = $this->db->error();
3102 $this->db->rollback();
3103 return -1;
3104 }
3105 }
3106
3114 public function classifyUnBilled(User $user, $notrigger = 0)
3115 {
3116 $error = 0;
3117
3118 $this->db->begin();
3119
3120 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET facture = 0';
3121 $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
3122
3123 dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG);
3124 if ($this->db->query($sql)) {
3125 $this->oldcopy = clone $this;
3126 $this->billed = 1;
3127
3128 if (!$notrigger && empty($error)) {
3129 // Call trigger
3130 $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user);
3131 if ($result < 0) {
3132 $error++;
3133 }
3134 // End call triggers
3135 }
3136
3137 if (!$error) {
3138 $this->billed = 0;
3139
3140 $this->db->commit();
3141 return 1;
3142 } else {
3143 foreach ($this->errors as $errmsg) {
3144 dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR);
3145 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3146 }
3147 $this->db->rollback();
3148 return -1 * $error;
3149 }
3150 } else {
3151 $this->error = $this->db->error();
3152 $this->db->rollback();
3153 return -1;
3154 }
3155 }
3156
3157
3188 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)
3189 {
3190 global $mysoc, $langs, $user;
3191
3192 if (!$this->isLineOfObject($rowid)) {
3193 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
3194 return -1;
3195 }
3196
3197 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");
3198 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3199
3200 if ($this->status == Commande::STATUS_DRAFT) {
3201 // Clean parameters
3202 if (empty($qty)) {
3203 $qty = 0;
3204 }
3205 if (empty($info_bits)) {
3206 $info_bits = 0;
3207 }
3208 if (empty($txtva)) {
3209 $txtva = 0;
3210 }
3211 if (empty($txlocaltax1)) {
3212 $txlocaltax1 = 0;
3213 }
3214 if (empty($txlocaltax2)) {
3215 $txlocaltax2 = 0;
3216 }
3217 if (empty($remise_percent)) {
3218 $remise_percent = 0;
3219 }
3220 if (empty($qty) && empty($special_code)) {
3221 $special_code = 3; // Set option tag
3222 }
3223 if (!empty($qty) && $special_code == 3) {
3224 $special_code = 0; // Remove option tag
3225 }
3226 if (empty($ref_ext)) {
3227 $ref_ext = '';
3228 }
3229
3230 if ($date_start && $date_end && $date_start > $date_end) {
3231 $langs->load("errors");
3232 $this->error = $langs->trans('ErrorStartDateGreaterEnd');
3233 return -1;
3234 }
3235
3236 $remise_percent = (float) price2num($remise_percent);
3237 $qty = (float) price2num($qty);
3238 $pu = price2num($pu);
3239 $pa_ht = price2num($pa_ht); // do not convert to float here, it breaks the functioning of $pa_ht_isemptystring
3240 $pu_ht_devise = price2num($pu_ht_devise);
3241 if (!preg_match('/\‍((.*)\‍)/', (string) $txtva)) {
3242 $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
3243 }
3244 $txlocaltax1 = (float) price2num($txlocaltax1);
3245 $txlocaltax2 = (float) price2num($txlocaltax2);
3246
3247 $this->db->begin();
3248
3249 // Calculation of the gross total (TTC) and VAT for the line from qty, pu, remise_percent and txtva
3250 // VERY IMPORTANT: It's at the time of line insertion that we must store the net, VAT, and gross amounts,
3251 // and this is done at the line level, which has its own VAT rate
3252
3253 $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
3254
3255 // Clean vat code
3256 $vat_src_code = '';
3257 $reg = array();
3258 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
3259 $vat_src_code = $reg[1];
3260 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
3261 }
3262
3263 // Round the quantity to the packaging before computing the amounts of the line (and checking the stock),
3264 // else the line is saved with the rounded quantity but with the amounts of the quantity before rounding
3265 if (getDolGlobalString('PRODUCT_USE_CUSTOMER_PACKAGING')) {
3266 $tmpline = new OrderLine($this->db);
3267 if ($tmpline->fetch($rowid) > 0) {
3268 $newqty = $this->roundQtyToPackaging($qty, $tmpline->packaging);
3269 if ($newqty != $qty) {
3270 $qty = $newqty;
3271 setEventMessages($langs->trans('QtyRecalculatedWithPackaging'), null, 'warnings');
3272 }
3273 }
3274 }
3275
3276 $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);
3277
3278 $total_ht = $tabprice[0];
3279 $total_tva = $tabprice[1];
3280 $total_ttc = $tabprice[2];
3281 $total_localtax1 = $tabprice[9];
3282 $total_localtax2 = $tabprice[10];
3283 $pu_ht = $tabprice[3];
3284 $pu_tva = $tabprice[4];
3285 $pu_ttc = $tabprice[5];
3286
3287 // MultiCurrency
3288 $multicurrency_total_ht = $tabprice[16];
3289 $multicurrency_total_tva = $tabprice[17];
3290 $multicurrency_total_ttc = $tabprice[18];
3291 $pu_ht_devise = $tabprice[19];
3292
3293 // Fetch current line from the database and then clone the object and set it in $oldline property
3294 $line = new OrderLine($this->db);
3295 $line->fetch($rowid);
3296 $line->fetch_optionals();
3297
3298 if (!empty($line->fk_product)) {
3299 $product = new Product($this->db);
3300 $result = $product->fetch($line->fk_product);
3301 $product_type = $product->type;
3302
3303 if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_ORDER') && $product->isStockManaged()) {
3304 // get real stock
3305 $productChildrenNb = 0;
3306 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
3307 $productChildrenNb = $product->hasFatherOrChild(1);
3308 }
3309 if ($productChildrenNb > 0) {
3310 // compute real stock from each subcomponent
3311 $product_stock = null;
3312 $product->loadStockForVirtualProduct('warehouseopen', $qty);
3313 foreach ($product->stock_warehouse as $componentStockWarehouse) {
3314 if ($product_stock === null) {
3315 $product_stock = $componentStockWarehouse->real;
3316 } else {
3317 $product_stock = min($product_stock, $componentStockWarehouse->real);
3318 }
3319 }
3320 if ($product_stock === null) {
3321 $product_stock = 0;
3322 }
3323 } else {
3324 $product_stock = $product->stock_reel;
3325 }
3326
3327 if ($product_stock < $qty) {
3328 $langs->load("errors");
3329 $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', (string) $product->ref);
3330 $this->errors[] = $this->error;
3331
3332 dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
3333
3334 $this->db->rollback();
3336 }
3337 }
3338 }
3339
3340 $staticline = clone $line;
3341
3342 $line->oldline = $staticline;
3343 $this->line = $line;
3344 $this->line->context = $this->context;
3345 $this->line->rang = $rang;
3346
3347 // Reorder if fk_parent_line change
3348 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
3349 $rangmax = $this->line_max($fk_parent_line);
3350 $this->line->rang = $rangmax + 1;
3351 }
3352
3353
3354 $this->line->id = $rowid;
3355 $this->line->label = $label;
3356 $this->line->desc = $desc;
3357 $this->line->qty = $qty;
3358 $this->line->ref_ext = $ref_ext;
3359
3360 $this->line->vat_src_code = $vat_src_code;
3361 $this->line->tva_tx = $txtva;
3362 $this->line->localtax1_tx = $txlocaltax1;
3363 $this->line->localtax2_tx = $txlocaltax2;
3364 $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
3365 $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
3366 $this->line->remise_percent = $remise_percent;
3367 $this->line->subprice = (float) $pu_ht;
3368 $this->line->info_bits = $info_bits;
3369 $this->line->special_code = $special_code;
3370 $this->line->total_ht = (float) $total_ht;
3371 $this->line->total_tva = (float) $total_tva;
3372 $this->line->total_localtax1 = (float) $total_localtax1;
3373 $this->line->total_localtax2 = (float) $total_localtax2;
3374 $this->line->total_ttc = (float) $total_ttc;
3375 $this->line->date_start = $date_start;
3376 $this->line->date_end = $date_end;
3377 $this->line->product_type = $type;
3378 $this->line->fk_parent_line = $fk_parent_line;
3379 $this->line->skip_update_total = $skip_update_total;
3380 $this->line->fk_unit = $fk_unit;
3381
3382 $this->line->fk_fournprice = $fk_fournprice;
3383 $this->line->pa_ht = $pa_ht;
3384
3385 // Multicurrency
3386 $this->line->multicurrency_subprice = (float) $pu_ht_devise;
3387 $this->line->multicurrency_total_ht = (float) $multicurrency_total_ht;
3388 $this->line->multicurrency_total_tva = (float) $multicurrency_total_tva;
3389 $this->line->multicurrency_total_ttc = (float) $multicurrency_total_ttc;
3390
3391 if (is_array($array_options) && count($array_options) > 0) {
3392 // We replace values in this->line->array_options only for entries defined into $array_options
3393 foreach ($array_options as $key => $value) {
3394 $this->line->array_options[$key] = $array_options[$key];
3395 }
3396 }
3397
3398 $result = $this->line->update($user, $notrigger);
3399 if ($result > 0) {
3400 // Reorder if child line
3401 if (!empty($fk_parent_line)) {
3402 $this->line_order(true, 'DESC');
3403 }
3404
3405 // Mise a jour info denormalisees
3406 $this->update_price(1, 'auto');
3407
3408 $this->db->commit();
3409 return $result;
3410 } else {
3411 $this->setErrorsFromObject($this->line);
3412
3413 $this->db->rollback();
3414 return -1;
3415 }
3416 } else {
3417 $this->error = get_class($this)."::updateline Order status makes operation forbidden";
3418 $this->errors = array('OrderStatusMakeOperationForbidden');
3419 return -2;
3420 }
3421 }
3422
3430 public function update(User $user, $notrigger = 0)
3431 {
3432 $error = 0;
3433
3434 // Clean parameters
3435 if (isset($this->ref)) {
3436 $this->ref = trim($this->ref);
3437 }
3438 if (isset($this->ref_client)) {
3439 $this->ref_client = trim($this->ref_client);
3440 }
3441 if (isset($this->ref_customer)) {
3442 $this->ref_customer = trim($this->ref_customer);
3443 }
3444 if (isset($this->note) || isset($this->note_private)) {
3445 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
3446 }
3447 if (isset($this->note_public)) {
3448 $this->note_public = trim($this->note_public);
3449 }
3450 if (isset($this->model_pdf)) {
3451 $this->model_pdf = trim($this->model_pdf);
3452 }
3453 if (isset($this->import_key)) {
3454 $this->import_key = trim($this->import_key);
3455 }
3456 $delivery_date = $this->delivery_date;
3457
3458 // Check parameters
3459 // Put here code to add control on parameters values
3460
3461 // Update request
3462 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
3463
3464 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
3465 $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
3466 $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
3467 $sql .= " fk_soc=".(isset($this->socid) ? ((int) $this->socid) : "null").",";
3468 $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
3469 $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
3470
3471 $sql .= " total_tva=".(isset($this->total_tva) ? ((float) $this->total_tva) : "null").",";
3472 $sql .= " localtax1=".(isset($this->total_localtax1) ? ((float) $this->total_localtax1) : "null").",";
3473 $sql .= " localtax2=".(isset($this->total_localtax2) ? ((float) $this->total_localtax2) : "null").",";
3474 $sql .= " total_ht=".(isset($this->total_ht) ? ((float) $this->total_ht) : "null").",";
3475 $sql .= " total_ttc=".(isset($this->total_ttc) ? ((float) $this->total_ttc) : "null").",";
3476 $sql .= " fk_statut=".(isset($this->status) ? ((int) $this->status) : "null").",";
3477 $sql .= " fk_user_modif=".(isset($user->id) ? ((int) $user->id) : "null").",";
3478 $sql .= " fk_user_valid=".((isset($this->user_validation_id) && $this->user_validation_id > 0) ? ((int) $this->user_validation_id) : "null").",";
3479 $sql .= " fk_projet=".(isset($this->fk_project) ? ((int) $this->fk_project) : "null").",";
3480 $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? ((int) $this->cond_reglement_id) : "null").",";
3481 $sql .= " deposit_percent=".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null").",";
3482 $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? ((int) $this->mode_reglement_id) : "null").",";
3483 $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').",";
3484 $sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? ((int) $this->shipping_method_id) : "null").",";
3485 $sql .= " fk_account=".($this->fk_account > 0 ? ((int) $this->fk_account) : "null").",";
3486 $sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? ((int) $this->demand_reason_id) : "null").",";
3487 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
3488 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
3489 $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
3490 $sql .= " fk_warehouse=".($this->warehouse_id > 0 ? ((int) $this->warehouse_id) : "null").",";
3491 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
3492 $sql .= " module_source = ".(isset($this->module_source) ? "'".$this->db->escape($this->module_source)."'" : "null").",";
3493 $sql .= " pos_source = ".(isset($this->pos_source) ? "'".$this->db->escape($this->pos_source)."'" : "null");
3494 $sql .= " WHERE rowid=".((int) $this->id);
3495
3496 $this->db->begin();
3497
3498 dol_syslog(get_class($this)."::update", LOG_DEBUG);
3499 $resql = $this->db->query($sql);
3500 if (!$resql) {
3501 $error++;
3502 $this->errors[] = "Error ".$this->db->lasterror();
3503 }
3504
3505 if (!$error) {
3506 $result = $this->insertExtraFields();
3507 if ($result < 0) {
3508 $error++;
3509 }
3510 }
3511
3512 if (!$error && !$notrigger) {
3513 // Call trigger
3514 $result = $this->call_trigger('ORDER_MODIFY', $user);
3515 if ($result < 0) {
3516 $error++;
3517 }
3518 // End call triggers
3519 }
3520
3521 // Commit or rollback
3522 if ($error) {
3523 foreach ($this->errors as $errmsg) {
3524 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
3525 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
3526 }
3527 $this->db->rollback();
3528 return -1 * $error;
3529 } else {
3530 $this->db->commit();
3531 return 1;
3532 }
3533 }
3534
3542 public function delete($user, $notrigger = 0)
3543 {
3544 global $conf, $langs;
3545 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3546
3547 $error = 0;
3548
3549 dol_syslog(get_class($this)."::delete ".$this->id, LOG_DEBUG);
3550
3551 $this->db->begin();
3552
3553 if (!$notrigger) {
3554 // Call trigger
3555 $result = $this->call_trigger('ORDER_DELETE', $user);
3556 if ($result < 0) {
3557 $error++;
3558 }
3559 // End call triggers
3560 }
3561
3562 // Test we can delete
3563 if ($this->countNbOfShipments() != 0) {
3564 $this->errors[] = $langs->trans('SomeShipmentExists');
3565 $error++;
3566 }
3567
3568 // Remove linked categories.
3569 if (!$error) {
3570 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_order";
3571 $sql .= " WHERE fk_order = ".((int) $this->id);
3572
3573 $result = $this->db->query($sql);
3574 if (!$result) {
3575 $error++;
3576 $this->errors[] = $this->db->lasterror();
3577 }
3578 }
3579
3580 // Delete extrafields of lines and lines
3581 if (!$error && !empty($this->table_element_line)) {
3582 $tabletodelete = $this->table_element_line;
3583 $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).")";
3584 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
3585 if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
3586 $error++;
3587 $this->error = $this->db->lasterror();
3588 $this->errors[] = $this->error;
3589 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3590 }
3591 }
3592
3593 if (!$error) {
3594 // Delete linked object
3595 $res = $this->deleteObjectLinked();
3596 if ($res < 0) {
3597 $error++;
3598 }
3599 }
3600
3601 if (!$error) {
3602 // Delete linked contacts
3603 $res = $this->delete_linked_contact();
3604 if ($res < 0) {
3605 $error++;
3606 }
3607 }
3608
3609 // Removed extrafields of object
3610 if (!$error) {
3611 $result = $this->deleteExtraFields();
3612 if ($result < 0) {
3613 $error++;
3614 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3615 }
3616 }
3617
3618 // Delete main record
3619 if (!$error) {
3620 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
3621 $res = $this->db->query($sql);
3622 if (!$res) {
3623 $error++;
3624 $this->error = $this->db->lasterror();
3625 $this->errors[] = $this->error;
3626 dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
3627 }
3628 }
3629
3630 // Delete record into ECM index and physically
3631 if (!$error) {
3632 $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive, old method.
3633 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
3634 if (!$res) {
3635 $error++;
3636 }
3637 }
3638
3639 if (!$error) {
3640 // We remove directory
3641 $ref = dol_sanitizeFileName($this->ref);
3642 if ($conf->commande->multidir_output[$this->entity] && !empty($this->ref)) {
3643 $dir = $conf->commande->multidir_output[$this->entity]."/".$ref;
3644 $file = $dir."/".$ref.".pdf";
3645 if (file_exists($file)) {
3646 dol_delete_preview($this);
3647
3648 if (!dol_delete_file($file, 0, 0, 0, $this)) {
3649 $this->error = 'ErrorFailToDeleteFile';
3650 $this->errors[] = $this->error;
3651 $this->db->rollback();
3652 return 0;
3653 }
3654 }
3655 if (file_exists($dir)) {
3656 $res = @dol_delete_dir_recursive($dir);
3657 if (!$res) {
3658 $this->error = 'ErrorFailToDeleteDir';
3659 $this->errors[] = $this->error;
3660 $this->db->rollback();
3661 return 0;
3662 }
3663 }
3664 }
3665 }
3666
3667 if (!$error) {
3668 dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
3669 $this->db->commit();
3670 return 1;
3671 } else {
3672 $this->db->rollback();
3673 return -1;
3674 }
3675 }
3676
3677
3678 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3686 public function load_board($user, $mode)
3687 {
3688 // phpcs:enable
3689 global $conf, $langs, $hookmanager;
3690
3691 $clause = " WHERE";
3692
3693 $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut, c.total_ht";
3694 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
3695 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
3696 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
3697 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
3698 $clause = " AND";
3699 }
3700 $sql .= $clause." c.entity IN (".getEntity('commande').")";
3701 //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
3702 if ($mode == 'toship') {
3703 // An order to ship is an open order (validated or in progress)
3704 $sql .= " AND c.fk_statut IN (" . self::STATUS_VALIDATED . "," . self::STATUS_SHIPMENTONPROCESS . ")";
3705 }
3706 if ($mode == 'tobill') {
3707 // An order to bill is an order not already billed
3708 $sql .= " AND c.fk_statut IN (" . self::STATUS_VALIDATED . "," . self::STATUS_SHIPMENTONPROCESS . ", " . self::STATUS_CLOSED . ") AND c.facture = 0";
3709 }
3710 if ($mode == 'shippedtobill') {
3711 // An order shipped and to bill is a delivered order not already billed
3712 $sql .= " AND c.fk_statut IN (" . self::STATUS_CLOSED . ") AND c.facture = 0";
3713 }
3714 if ($user->socid) {
3715 $sql .= " AND c.fk_soc = ".((int) $user->socid);
3716 }
3717 // Add where from hooks
3718 $parameters = array('socid' => $user->socid);
3719 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
3720 $sql .= $hookmanager->resPrint;
3721 $resql = $this->db->query($sql);
3722 if ($resql) {
3723 $delay_warning = 0;
3724 $label = $labelShort = $url = '';
3725 if ($mode == 'toship') {
3726 $delay_warning = $conf->commande->client->warning_delay / 60 / 60 / 24;
3727 $url = DOL_URL_ROOT.'/commande/list.php?search_status=-2&mainmenu=commercial&leftmenu=orders';
3728 $label = $langs->transnoentitiesnoconv("OrdersToProcess");
3729 $labelShort = $langs->transnoentitiesnoconv("Opened");
3730 }
3731 if ($mode == 'tobill') {
3732 $url = DOL_URL_ROOT.'/commande/list.php?search_status=-3&search_billed=0&mainmenu=commercial&leftmenu=orders';
3733 $label = $langs->trans("OrdersToBill"); // We set here bill but may be billed or ordered
3734 $labelShort = $langs->trans("ToBill");
3735 }
3736 if ($mode == 'shippedtobill') {
3737 $url = DOL_URL_ROOT.'/commande/list.php?search_status=3&search_billed=0&mainmenu=commercial&leftmenu=orders';
3738 $label = $langs->trans("OrdersToBill"); // We set here bill but may be billed or ordered
3739 $labelShort = $langs->trans("StatusOrderDelivered").' '.$langs->trans("and").' '.$langs->trans("ToBill");
3740 }
3741
3742 $response = new WorkboardResponse();
3743
3744 $response->warning_delay = $delay_warning;
3745 $response->label = $label;
3746 $response->labelShort = $labelShort;
3747 $response->url = $url;
3748 $response->url_late = DOL_URL_ROOT.'/commande/list.php?search_option=late&mainmenu=commercial&leftmenu=orders';
3749 $response->img = img_object('', "order");
3750
3751 $generic_commande = new Commande($this->db);
3752
3753 while ($obj = $this->db->fetch_object($resql)) {
3754 $response->nbtodo++;
3755 $response->total += $obj->total_ht;
3756
3757 $generic_commande->status = $obj->fk_statut;
3758 $generic_commande->date = $this->db->jdate($obj->date_commande);
3759 $generic_commande->delivery_date = $this->db->jdate($obj->delivery_date);
3760
3761 if ($mode == 'toship' && $generic_commande->hasDelay()) {
3762 $response->nbtodolate++;
3763 }
3764 }
3765
3766 return $response;
3767 } else {
3768 $this->error = $this->db->error();
3769 return -1;
3770 }
3771 }
3772
3778 public function getLabelSource()
3779 {
3780 global $langs;
3781
3782 $label = $langs->trans('OrderSource'.$this->source);
3783
3784 if ($label == 'OrderSource') {
3785 return '';
3786 }
3787 return $label;
3788 }
3789
3796 public function getLibStatut($mode)
3797 {
3798 return $this->LibStatut($this->status, $this->billed, $mode);
3799 }
3800
3801 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3811 public function LibStatut($status, $billed, $mode, $donotshowbilled = 0)
3812 {
3813 // phpcs:enable
3814 global $langs, $hookmanager;
3815
3816 $billedtext = '';
3817 if (empty($donotshowbilled)) {
3818 $billedtext .= ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : '');
3819 }
3820 $billedtextlong = ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : '');
3821
3822 $labelTooltip = '';
3823
3824 $paramsBadge = array('badgeParams' => array('attr' => array(
3825 'data-status-element' => $this->element,
3826 'data-billed' => (int) $billed,
3827 'data-status' => (int) $status
3828 )));
3829
3830 if ($status == self::STATUS_CANCELED) {
3831 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderCanceled');
3832 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderCanceledShort');
3833 $statusType = 'status9';
3834 } elseif ($status == self::STATUS_DRAFT) {
3835 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderDraft');
3836 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderDraftShort');
3837 $statusType = 'status0';
3838 } elseif ($status == self::STATUS_VALIDATED) {
3839 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderValidated').$billedtextlong;
3840 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderValidatedShort').$billedtext;
3841 $statusType = 'status1';
3842 } elseif ($status == self::STATUS_SHIPMENTONPROCESS) {
3843 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderSent').$billedtextlong;
3844 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderSentShort').$billedtext;
3845 $labelTooltip = $langs->transnoentitiesnoconv("StatusOrderSent");
3846 if (!empty($this->delivery_date)) {
3847 $labelTooltip .= ' - '.$langs->transnoentitiesnoconv("DateDeliveryPlanned").dol_print_date($this->delivery_date, 'day').$billedtext;
3848 }
3849 $statusType = 'status4';
3850 } elseif ($status == self::STATUS_CLOSED) {
3851 $labelStatus = $langs->transnoentitiesnoconv('StatusOrderDelivered').$billedtextlong;
3852 $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderDeliveredShort').$billedtext;
3853 $statusType = 'status6';
3854 } else {
3855 $labelStatus = $langs->transnoentitiesnoconv('Unknown');
3856 $labelStatusShort = '';
3857 $statusType = '';
3858 $mode = 0;
3859 }
3860
3861 $paramsBadge['tooltip'] = $labelTooltip;
3862
3863 $parameters = array(
3864 'status' => $status,
3865 'mode' => $mode,
3866 'billed' => $billed,
3867 'donotshowbilled' => $donotshowbilled,
3868 'paramsBadge' => & $paramsBadge
3869 );
3870
3871 $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
3872
3873 if ($reshook > 0) {
3874 return $hookmanager->resPrint;
3875 }
3876
3877 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $paramsBadge);
3878 }
3879
3887 public function getTooltipContentArray($params)
3888 {
3889 global $conf, $langs, $user;
3890
3891 $langs->load('orders');
3892 $datas = [];
3893 $nofetch = !empty($params['nofetch']);
3894
3895 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3896 return ['optimize' => $langs->trans("Order")];
3897 }
3898
3899 if ($user->hasRight('commande', 'lire')) {
3900 $datas['picto'] = img_picto('', $this->picto, '', 0, 0, 0, '', 'paddingrightonly').'<u>'.$langs->trans("Order").'</u>';
3901 if (isset($this->status)) {
3902 $datas['status'] = ' '.$this->getLibStatut(5);
3903 }
3904 $datas['Ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
3905 if (!$nofetch) {
3906 $langs->load('companies');
3907 if (empty($this->thirdparty)) {
3908 $this->fetch_thirdparty();
3909 }
3910 $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
3911 }
3912 $datas['RefCustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.(empty($this->ref_customer) ? (empty($this->ref_client) ? '' : $this->ref_client) : $this->ref_customer);
3913 if (!$nofetch) {
3914 $langs->load('project');
3915 if (is_null($this->project) || (is_object($this->project) && empty($this->project->id))) {
3916 $res = $this->fetchProject();
3917 if ($res > 0 && $this->project instanceof Project) {
3918 $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, '1');
3919 }
3920 }
3921 }
3922 if (!empty($this->total_ht)) {
3923 $datas['AmountHT'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
3924 }
3925 if (!empty($this->total_tva)) {
3926 $datas['VAT'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
3927 }
3928 if (!empty($this->total_ttc)) {
3929 $datas['AmountTTC'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
3930 }
3931 if (!empty($this->date)) {
3932 $datas['Date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
3933 }
3934 if (!empty($this->delivery_date)) {
3935 $datas['DeliveryDate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
3936 }
3937 }
3938
3939 return $datas;
3940 }
3941
3955 public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0, $target = '')
3956 {
3957 global $conf, $langs, $user, $hookmanager;
3958
3959 if (!empty($conf->dol_no_mouse_hover)) {
3960 $notooltip = 1; // Force disable tooltips
3961 }
3962
3963 $result = '';
3964
3965 if (isModEnabled("shipping") && ($option == '1' || $option == '2')) {
3966 $baseurl = DOL_URL_ROOT . '/expedition/shipment.php';
3967 } else {
3968 $baseurl = DOL_URL_ROOT . '/commande/card.php';
3969 }
3970 $query = ['id' => $this->id];
3971 if (!$user->hasRight('commande', 'lire')) {
3972 $option = 'nolink';
3973 }
3974
3975 if ($option !== 'nolink') {
3976 // Add param to save lastsearch_values or not
3977 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
3978 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
3979 $add_save_lastsearch_values = 1;
3980 }
3981 if ($add_save_lastsearch_values) {
3982 $query = array_merge($query, ['save_lastsearch_values' => 1]);
3983 }
3984 }
3985 $url = dolBuildUrl($baseurl, $query);
3986
3987 if ($short) {
3988 return $url;
3989 }
3990 $params = [
3991 'id' => $this->id,
3992 'objecttype' => $this->element,
3993 'option' => $option,
3994 'nofetch' => 1,
3995 ];
3996 $classfortooltip = 'classfortooltip';
3997 $dataparams = '';
3998 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
3999 $classfortooltip = 'classforajaxtooltip';
4000 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
4001 $label = '';
4002 } else {
4003 $label = implode($this->getTooltipContentArray($params));
4004 }
4005
4006 $linkclose = '';
4007 if (empty($notooltip) && $user->hasRight('commande', 'lire')) {
4008 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
4009 $label = $langs->trans("Order");
4010 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
4011 }
4012 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
4013 $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
4014
4015 $target_value = array('_self', '_blank', '_parent', '_top');
4016 if (in_array($target, $target_value)) {
4017 $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
4018 }
4019 }
4020
4021 $linkstart = '<a href="'.$url.'"';
4022 $linkstart .= $linkclose.'>';
4023 $linkend = '</a>';
4024
4025 if ($option === 'nolink') {
4026 $linkstart = '';
4027 $linkend = '';
4028 }
4029
4030 $result .= $linkstart;
4031 if ($withpicto) {
4032 $result .= img_object(($notooltip ? '' : $label), $this->picto, (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
4033 }
4034 if ($withpicto != 2) {
4035 $result .= $this->ref;
4036 }
4037 $result .= $linkend;
4038
4039 if ($addlinktonotes) {
4040 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
4041 if ($txttoshow) {
4042 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
4043 $result .= ' <span class="note inline-block">';
4044 $result .= '<a href="'.DOL_URL_ROOT.'/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
4045 $result .= img_picto('', 'note');
4046 $result .= '</a>';
4047 //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
4048 //$result.='</a>';
4049 $result .= '</span>';
4050 }
4051 }
4052
4053 global $action;
4054 $hookmanager->initHooks(array($this->element . 'dao'));
4055 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
4056 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4057 if ($reshook > 0) {
4058 $result = $hookmanager->resPrint;
4059 } else {
4060 $result .= $hookmanager->resPrint;
4061 }
4062 return $result;
4063 }
4064
4065
4072 public function info($id)
4073 {
4074 $sql = 'SELECT c.rowid, date_creation as datec, tms as datem,';
4075 $sql .= ' date_valid as datev,';
4076 $sql .= ' date_cloture as datecloture,';
4077 $sql .= ' fk_user_author, fk_user_valid, fk_user_cloture';
4078 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as c';
4079 $sql .= ' WHERE c.rowid = '.((int) $id);
4080 $result = $this->db->query($sql);
4081 if ($result) {
4082 if ($this->db->num_rows($result)) {
4083 $obj = $this->db->fetch_object($result);
4084 $this->id = $obj->rowid;
4085 if ($obj->fk_user_author) {
4086 $this->user_creation_id = $obj->fk_user_author;
4087 }
4088 if ($obj->fk_user_valid) {
4089 $this->user_validation_id = $obj->fk_user_valid;
4090 }
4091 if ($obj->fk_user_cloture) {
4092 $this->user_closing_id = $obj->fk_user_cloture;
4093 }
4094
4095 $this->date_creation = $this->db->jdate($obj->datec);
4096 $this->date_modification = $this->db->jdate($obj->datem);
4097 $this->date_validation = $this->db->jdate($obj->datev);
4098 $this->date_cloture = $this->db->jdate($obj->datecloture);
4099 }
4100
4101 $this->db->free($result);
4102 } else {
4103 dol_print_error($this->db);
4104 }
4105 }
4106
4107
4116 public function initAsSpecimen($param = array())
4117 {
4118 global $conf, $langs;
4119
4120 dol_syslog(get_class($this)."::initAsSpecimen");
4121
4122 // Load array of products prodids
4123 $num_prods = 0;
4124 $prodids = array();
4125 $sql = "SELECT rowid";
4126 $sql .= " FROM ".MAIN_DB_PREFIX."product";
4127 $sql .= " WHERE entity IN (".getEntity('product').")";
4128 if (array_key_exists('tosell', $param)) {
4129 $sql .= " AND tosell = ".((int) $param['tosell']);
4130 }
4131 $sql .= $this->db->plimit(100);
4132
4133 $resql = $this->db->query($sql);
4134 if ($resql) {
4135 $num_prods = $this->db->num_rows($resql);
4136 $i = 0;
4137 while ($i < $num_prods) {
4138 $i++;
4139 $row = $this->db->fetch_row($resql);
4140 $prodids[$i] = $row[0];
4141 }
4142 }
4143
4144 // Initialise parameters
4145 $this->id = 0;
4146 $this->ref = 'SPECIMEN';
4147 $this->specimen = 1;
4148 $this->entity = $conf->entity;
4149 $this->socid = 1;
4150 $this->date = time();
4151 $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
4152 $this->cond_reglement_code = 'RECEP';
4153 $this->mode_reglement_code = 'CHQ';
4154 $this->availability_code = 'DSP';
4155 $this->demand_reason_code = 'SRC_00';
4156
4157 $this->note_public = 'This is a comment (public)';
4158 $this->note_private = 'This is a comment (private)';
4159
4160 $this->multicurrency_tx = 1;
4161 $this->multicurrency_code = $conf->currency;
4162
4163 $this->status = $this::STATUS_DRAFT;
4164
4165 // Lines
4166 $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)
4167 $xnbp = 0;
4168
4169 while ($xnbp < $nbp) {
4170 $line = new OrderLine($this->db);
4171
4172 $line->desc = $langs->trans("Description")." ".$xnbp;
4173 $line->qty = 1;
4174 $line->subprice = 100;
4175 $line->price = 100;
4176 $line->tva_tx = 20;
4177 if ($xnbp == 2) {
4178 $line->total_ht = 50;
4179 $line->total_ttc = 60;
4180 $line->total_tva = 10;
4181 $line->remise_percent = 50;
4182 } else {
4183 $line->total_ht = 100;
4184 $line->total_ttc = 120;
4185 $line->total_tva = 20;
4186 $line->remise_percent = 0;
4187 }
4188 if ($num_prods > 0) {
4189 $prodid = mt_rand(1, $num_prods);
4190 $line->fk_product = $prodids[$prodid];
4191 $line->product_ref = 'SPECIMEN';
4192 }
4193
4194 $this->lines[$xnbp] = $line;
4195
4196 $this->total_ht += $line->total_ht;
4197 $this->total_tva += $line->total_tva;
4198 $this->total_ttc += $line->total_ttc;
4199
4200 $xnbp++;
4201 }
4202
4203 return 1;
4204 }
4205
4206
4212 public function loadStateBoard()
4213 {
4214 global $user, $hookmanager;
4215
4216 $this->nb = array();
4217 $clause = "WHERE";
4218
4219 $sql = "SELECT count(c.rowid) as nb";
4220 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c";
4221 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
4222 if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
4223 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4224 $sql .= " WHERE sc.fk_user = ".((int) $user->id);
4225 $clause = "AND";
4226 }
4227 $sql .= " ".$clause." c.entity IN (".getEntity('commande').")";
4228 // Add where from hooks
4229 $parameters = array();
4230 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
4231 $sql .= $hookmanager->resPrint;
4232 $resql = $this->db->query($sql);
4233 if ($resql) {
4234 while ($obj = $this->db->fetch_object($resql)) {
4235 $this->nb["orders"] = $obj->nb;
4236 }
4237 $this->db->free($resql);
4238 return 1;
4239 } else {
4240 dol_print_error($this->db);
4241 $this->error = $this->db->error();
4242 return -1;
4243 }
4244 }
4245
4251 public function getLinesArray()
4252 {
4253 return $this->fetch_lines();
4254 }
4255
4267 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
4268 {
4269 global $langs;
4270
4271 $langs->load("orders");
4272 $outputlangs->load("products");
4273
4274 if (!dol_strlen($modele)) {
4275 $modele = 'einstein';
4276
4277 if (!empty($this->model_pdf)) {
4278 $modele = $this->model_pdf;
4279 } elseif (getDolGlobalString('COMMANDE_ADDON_PDF')) {
4280 $modele = getDolGlobalString('COMMANDE_ADDON_PDF');
4281 }
4282 }
4283
4284 $modelpath = "core/modules/commande/doc/";
4285
4286 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
4287 }
4288
4289
4298 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
4299 {
4300 $tables = array(
4301 'commande'
4302 );
4303
4304 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
4305 }
4306
4315 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
4316 {
4317 $tables = array(
4318 'commandedet',
4319 );
4320
4321 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
4322 }
4323
4329 public function hasDelay()
4330 {
4331 global $conf;
4332
4333 if (!($this->status > Commande::STATUS_DRAFT && $this->status < Commande::STATUS_CLOSED)) {
4334 return false; // Never late if not inside this status range
4335 }
4336
4337 $now = dol_now();
4338
4339 return max($this->date, $this->delivery_date) < ($now - $conf->commande->client->warning_delay);
4340 }
4341
4347 public function showDelay()
4348 {
4349 global $conf, $langs;
4350
4351 if (empty($this->delivery_date)) {
4352 $text = $langs->trans("OrderDate").' '.dol_print_date($this->date, 'day');
4353 } else {
4354 $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->delivery_date, 'day');
4355 }
4356 $text .= ' '.($conf->commande->client->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->client->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
4357
4358 return $text;
4359 }
4360
4370 public function setSignedStatus(User $user, int $status = 0, int $notrigger = 0, $triggercode = ''): int
4371 {
4372 return $this->setSignedStatusCommon($user, $status, $notrigger, $triggercode);
4373 }
4374
4382 public function getShippableInfos(array $options = array()): array
4383 {
4384 global $conf, $langs;
4385
4386 $langs->loadLangs(array('orders', 'sendings', 'stocks', 'products'));
4387
4388 $result = array(
4389 'has_product' => false,
4390 'shippable' => false,
4391 'texticon' => '',
4392 'textinfo' => '',
4393 'warning' => false,
4394 );
4395
4396 // Requested naming for statuses
4397 if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_CLOSED) {
4398 return $result;
4399 }
4400
4401
4402 $genericCommande = $this;
4403 $genericProduct = new Product($this->db);
4404
4405
4406 $productstatcache = array();
4407 $productstatcachevirtual = array();
4408
4409
4410 $genericCommande->getLinesArray(); // Load array ->lines
4411 $genericCommande->loadExpeditions(); // Load array ->expeditions
4412
4413 $notshippable = 0;
4414 $has_reliquat = 0;
4415 $warning = 0;
4416 $textinfo = '';
4417 $textwarning = '';
4418 $nbprod = 0;
4419
4420 $genericProduct = new Product($this->db);
4421
4422 $numlines = count($genericCommande->lines);
4423 for ($lig = 0; $lig < $numlines; $lig++) {
4424 $orderLine = $genericCommande->lines[$lig]; // @phan-var-force OrderLine $orderLine
4425
4426 if (isset($genericCommande->expeditions[$orderLine->id])) {
4427 $reliquat = $orderLine->qty - $genericCommande->expeditions[$orderLine->id];
4428 } else {
4429 $reliquat = $orderLine->qty;
4430 }
4431
4432 if ($orderLine->product_type == 0 && $orderLine->fk_product > 0) { // product, not service
4433 $nbprod = 1;
4434
4435 if (empty($productstatcache[$orderLine->fk_product])) {
4436 $genericProduct->fetch($orderLine->fk_product);
4437 $genericProduct->load_stock('nobatch,warehouseopen'); // loadvirtualstock included
4438
4439 $productstatcache[$orderLine->fk_product]['stockreel'] = $genericProduct->stock_reel;
4440 $productstatcachevirtual[$orderLine->fk_product]['stockreel'] = $genericProduct->stock_theorique;
4441 }
4442
4443 $genericProduct->stock_reel = $productstatcache[$orderLine->fk_product]['stockreel'];
4444 $genericProduct->stock_theorique = $productstatcachevirtual[$orderLine->fk_product]['stockreel'];
4445
4446 if ($reliquat > 0) {
4447 $has_reliquat = 1;
4448 if (!getDolGlobalString('SHIPPABLE_ORDER_ICON_IN_LIST')) {
4449 $textinfo .= $reliquat . ' x ' . $orderLine->product_ref . '&nbsp;' . dol_trunc($orderLine->product_label, 20);
4450 $textinfo .= ' - ' . $langs->trans("Stock") . ': <span class="' . ($genericProduct->stock_reel >= $reliquat ? 'ok' : 'error') . '">' . $genericProduct->stock_reel . '</span>';
4451 $textinfo .= ' - ' . $langs->trans("VirtualStock") . ': <span class="' . ($genericProduct->stock_theorique >= $reliquat ? 'ok' : 'error') . '">' . $genericProduct->stock_theorique . '</span>';
4452 if ($reliquat != $orderLine->qty) {
4453 $textinfo .= ' <span class="opacitymedium">' . $langs->trans("QtyInOtherShipments") . ' ' . ($orderLine->qty - $reliquat) . '</span>';
4454 }
4455 $textinfo .= '<br>';
4456 } else {
4457 // BUGGED CODE (kept for backward compatibility and hidden conf)
4458 $stockorder = 0;
4459 $stockordersupplier = 0;
4460
4461 if (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')) {
4462 if (isModEnabled('order')) {
4463 if (empty($productstatcache[$orderLine->fk_product]['statsordercustomer'])) {
4464 $genericProduct->fetch($orderLine->fk_product);
4465 $genericProduct->load_stats_commande(0, '1,2');
4466 $productstatcache[$orderLine->fk_product]['statsordercustomer'] = $genericProduct->stats_commande['qty'];
4467 }
4468 $genericProduct->stats_commande['qty'] = $productstatcache[$orderLine->fk_product]['statsordercustomer'];
4469 $stockorder = $genericProduct->stats_commande['qty'];
4470
4471 if (isModEnabled('supplier_order')) {
4472 if (empty($productstatcache[$orderLine->fk_product]['statsordersupplier'])) {
4473 $genericProduct->load_stats_commande_fournisseur(0, '3');
4474 $productstatcache[$orderLine->fk_product]['statsordersupplier'] = $genericProduct->stats_commande_fournisseur['qty'];
4475 }
4476 $genericProduct->stats_commande_fournisseur['qty'] = $productstatcache[$orderLine->fk_product]['statsordersupplier'];
4477 $stockordersupplier = $genericProduct->stats_commande_fournisseur['qty'];
4478 }
4479 }
4480 }
4481
4482 $textinfo .= $reliquat . ' x ' . $orderLine->ref . '&nbsp;' . dol_trunc($orderLine->product_label, 20);
4483 $textinfo .= ' ' . $langs->trans("Available") . '&nbsp;&nbsp;' . $genericProduct->stock_reel . '..' . $stockorder;
4484
4485 if ($stockorder && $genericProduct->stock_reel < ($genericProduct->stock_reel - $stockorder + $reliquat)) {
4486 $warning++;
4487 $textwarning .= '<span class="warning">' . $langs->trans("Available") . '&nbsp;&nbsp;' . $genericProduct->stock_reel . '..' . $stockorder . '</span>';
4488 } else {
4489 if ($reliquat > $genericProduct->stock_reel) {
4490 $textinfo .= ' <span class="warning">' . $langs->trans("Available") . '&nbsp;&nbsp;' . $genericProduct->stock_reel . '</span>';
4491 } else {
4492 $textinfo .= ' <span class="ok">' . $langs->trans("Available") . '&nbsp;&nbsp;' . $genericProduct->stock_reel . '</span>';
4493 }
4494 }
4495
4496 if (isModEnabled('supplier_order')) {
4497 $textinfo .= '&nbsp;' . $langs->trans("SupplierOrder") . '&nbsp;&nbsp;' . $stockordersupplier;
4498 }
4499 if ($reliquat != $orderLine->qty) {
4500 $textinfo .= ' <span class="opacitymedium">' . $langs->trans("QtyInOtherShipments") . ' ' . ($orderLine->qty - $reliquat) . '</span>';
4501 }
4502 $textinfo .= '<br>';
4503 }
4504
4505 if ($reliquat > $genericProduct->stock_reel) {
4506 $notshippable++;
4507 }
4508 }
4509 }
4510 }
4511
4512 if ($nbprod) {
4513 if (!$has_reliquat) {
4514 $texticon = img_picto('', 'statut5', '', 0, 0, 0, '', 'paddingleft');
4515 $textinfo = $texticon . ' ' . $langs->trans("Shipped");
4516 $result['shippable'] = true;
4517 } elseif ($notshippable) {
4518 $texticon = img_picto('', 'dolly', '', 0, 0, 0, '', 'error paddingleft');
4519 $textinfo = $texticon . ' ' . $langs->trans("NonShippable") . '<br>' . $textinfo;
4520 $result['shippable'] = false;
4521 } else {
4522 $texticon = img_picto('', 'dolly', '', 0, 0, 0, '', 'green paddingleft');
4523 $textinfo = $texticon . ' ' . $langs->trans("Shippable") . '<br>' . $textinfo;
4524 $result['shippable'] = true;
4525 }
4526 $result['has_product'] = true;
4527 $result['texticon'] = $texticon;
4528 $result['textinfo'] = $textinfo;
4529 $result['warning'] = !empty($warning);
4530 }
4531
4532 return $result;
4533 }
4534}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
Class to manage customers orders.
getNbOfServicesLines()
Return number of line with type service.
getNbOfShipments()
Count number of shipments for this order.
createFromProposal($object, User $user)
Load an object from a proposal and create a new order into database.
setDraft($user, $idwarehouse=-1)
Set draft status.
setDeliveryDate($user, $delivery_date, $notrigger=0)
Set the planned delivery date.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
getLinesArray()
Create an array of order lines.
showDelay()
Show the customer delayed info.
set_date($user, $date, $notrigger=0)
Set the order date.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
loadStateBoard()
Load the indicators this->nb for the state board.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load array lines.
const STATUS_SHIPMENTONPROCESS
Shipment on process.
LibStatut($status, $billed, $mode, $donotshowbilled=0)
Return label of status.
getLibStatut($mode)
Return status label of Order.
hasDelay()
Is the sales order delayed?
const STATUS_CLOSED
Closed (Sent, billed or not)
valid($user, $idwarehouse=0, $notrigger=0)
Validate order.
getLabelSource()
Return source label of order.
set_remise($user, $remise, $notrigger=0)
Applique une remise relative.
initAsSpecimen($param=array())
Initialise an instance with random values.
const STATUS_CANCELED
Canceled status.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1, $addlinktonotes=0, $target='')
Return clickable link of object (with eventually picto)
loadExpeditions($filtre_statut=-1, $fk_product=0)
Load array this->expeditions of lines of shipments with nb of products sent for each order line Note:...
__construct($db)
Constructor.
availability($availability_id, $notrigger=0)
Update delivery delay.
set_reopen($user)
Tag the order as validated (opened) Function used when order is reopend after being closed.
set_ref_client($user, $ref_client, $notrigger=0)
Set customer ref.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $date_start='', $date_end='', $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=array(), $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0, $ref_ext='', $noupdateafterinsertline=0)
Add an order line into database (linked to product/service or not)
getTooltipContentArray($params)
getTooltipContentArray
create($user, $notrigger=0)
Create sale order Note that this->ref can be set or empty.
demand_reason($demand_reason_id, $notrigger=0)
Update order demand_reason.
const STATUS_DRAFT
Draft status.
const STOCK_NOT_ENOUGH_FOR_ORDER
ERR Not enough stock.
insert_discount($idremise)
Add a discount line into a sale order (as a sale order line) using an existing absolute discount (Con...
getNbOfProductsLines()
Return number of line with type product.
update(User $user, $notrigger=0)
Update database.
classifyUnBilled(User $user, $notrigger=0)
Classify the order as not invoiced.
setDiscount($user, $remise, $notrigger=0)
Set a percentage discount.
setCategories($categories)
Sets object to given categories.
const STATUS_ACCEPTED
For backward compatibility.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $price_base_type='HT', $info_bits=0, $date_start='', $date_end='', $type=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=array(), $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a line in database.
classifyBilled(User $user, $notrigger=0)
Classify the order as invoiced.
info($id)
Charge les information d'ordre info dans l'objet commande.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
const STATUS_VALIDATED
Validated status.
deleteLine($user=null, $lineid=0, $id=0)
Delete an order line.
countNbOfShipments()
Returns an array with expeditions lines number.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='c.date_commande', $sortorder='DESC')
Return list of orders (eventuelly filtered on a user) into an array.
fetch($id, $ref='', $ref_ext='', $notused='')
Get object from database.
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
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:64
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
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)
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $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