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