53require_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
54require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/factureligne.class.php';
55require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
56require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
57require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
58require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
59require_once DOL_DOCUMENT_ROOT.
'/subtotals/class/commonsubtotal.class.php';
62 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
65 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
78 public $element =
'facture';
83 public $TRIGGER_PREFIX =
'BILL';
88 public $table_element =
'facture';
93 public $table_element_line =
'facturedet';
98 public $class_element_line =
'FactureLigne';
103 public $fk_element =
'fk_facture';
108 public $picto =
'bill';
114 public $restrictiononfksoc = 1;
130 public $fk_user_author;
136 public $fk_user_valid;
142 public $fk_user_modif;
152 public $delivery_date;
164 public $ref_customer;
180 public $module_source;
194 public $pos_print_counter = 0;
199 public $email_sent_counter = 0;
204 public $fk_fac_rec_source;
209 public $fk_facture_source;
219 public $lines = array();
228 public $extraparams = array();
239 public $situation_cycle_ref;
244 public $situation_counter;
249 public $situation_final;
254 public $tab_previous_situation_invoice = array();
259 public $tab_next_situation_invoice = array();
264 public $retained_warranty;
269 public $retained_warranty_date_limit;
274 public $retained_warranty_fk_cond_reglement;
279 public $availability_id;
284 public $date_closing;
295 public $remise_percent;
300 public $online_payment_url;
337 public $fields = array(
338 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 1),
339 'ref' => array(
'type' =>
'varchar(30)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'position' => 5),
340 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 20,
'index' => 1),
341 'ref_client' => array(
'type' =>
'varchar(255)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 10,
'uieditable' => 1,
'alwayseditable' => 1),
342 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'RefExt',
'enabled' => 1,
'visible' => 0,
'position' => 12),
343 'type' => array(
'type' =>
'smallint(6)',
'label' =>
'Type',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
344 'subtype' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoiceSubtype',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
346 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 50),
347 'datef' => array(
'type' =>
'date',
'label' =>
'DateInvoice',
'enabled' => 1,
'visible' => 1,
'position' => 20),
348 'date_valid' => array(
'type' =>
'date',
'label' =>
'DateValidation',
'enabled' => 1,
'visible' => -1,
'position' => 22),
349 'date_lim_reglement' => array(
'type' =>
'date',
'label' =>
'DateDue',
'enabled' => 1,
'visible' => 1,
'position' => 25),
350 'payment_reference' => array(
'type' =>
'varchar(25)',
'label' =>
'PaymentReference',
'enabled' => 1,
'visible' => -1,
'position' => 26),
351 'date_closing' => array(
'type' =>
'datetime',
'label' =>
'DateClosing',
'enabled' => 1,
'visible' => -1,
'position' => 30),
352 'paye' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoicePaidCompletely',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 80),
353 'close_code' => array(
'type' =>
'varchar(16)',
'label' =>
'EarlyClosingReason',
'enabled' => 1,
'visible' => -1,
'position' => 92),
354 'close_note' => array(
'type' =>
'varchar(128)',
'label' =>
'EarlyClosingComment',
'enabled' => 1,
'visible' => -1,
'position' => 93),
355 'total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountHT',
'enabled' => 1,
'visible' => 1,
'position' => 95,
'isameasure' => 1),
356 'total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountVAT',
'enabled' => 1,
'visible' => -1,
'position' => 100,
'isameasure' => 1),
357 'localtax1' => array(
'type' =>
'double(24,8)',
'label' =>
'LT1',
'enabled' => 1,
'visible' => -1,
'position' => 110,
'isameasure' => 1),
358 'localtax2' => array(
'type' =>
'double(24,8)',
'label' =>
'LT2',
'enabled' => 1,
'visible' => -1,
'position' => 120,
'isameasure' => 1),
359 'revenuestamp' => array(
'type' =>
'double(24,8)',
'label' =>
'RevenueStamp',
'enabled' => 1,
'visible' => -1,
'position' => 115,
'isameasure' => 1),
360 'total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountTTC',
'enabled' => 1,
'visible' => 1,
'position' => 130,
'isameasure' => 1),
361 'fk_facture_source' => array(
'type' =>
'integer',
'label' =>
'SourceInvoice',
'enabled' => 1,
'visible' => -1,
'position' => 170),
362 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' => 1,
'visible' => -1,
'position' => 175),
363 'fk_account' => array(
'type' =>
'integer',
'label' =>
'BankAccount',
'enabled' => 1,
'visible' => -1,
'position' => 180),
364 'fk_currency' => array(
'type' =>
'varchar(3)',
'label' =>
'CurrencyCode',
'enabled' => 1,
'visible' => -1,
'position' => 185),
365 'fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentTerm',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 190),
366 'fk_mode_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentMode',
'enabled' => 1,
'visible' => -1,
'position' => 195),
367 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 205,
'uieditable' => 1,
'alwayseditable' => 1),
368 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 210,
'uieditable' => 1,
'alwayseditable' => 1),
369 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 215),
370 'fk_input_reason' => array(
'type' =>
'integer',
'label' =>
'Source',
'enabled' => 1,
'visible' => -1,
'position' => 220),
371 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 225),
372 'situation_cycle_ref' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation cycle ref',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 230),
373 'situation_counter' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation counter',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 235),
374 'situation_final' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation final',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 240),
375 'retained_warranty' => array(
'type' =>
'double',
'label' =>
'Retained warranty',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 245),
376 'retained_warranty_date_limit' => array(
'type' =>
'date',
'label' =>
'Retained warranty date limit',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 250),
377 'retained_warranty_fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'Retained warranty fk cond reglement',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 255),
378 'fk_incoterms' => array(
'type' =>
'integer',
'label' =>
'IncotermCode',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 260),
379 'location_incoterms' => array(
'type' =>
'varchar(255)',
'label' =>
'IncotermLabel',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 265),
380 'date_pointoftax' => array(
'type' =>
'date',
'label' =>
'DatePointOfTax',
'enabled' =>
'getDolGlobalString("INVOICE_POINTOFTAX_DATE")',
'visible' => -1,
'position' => 270),
381 'fk_multicurrency' => array(
'type' =>
'integer',
'label' =>
'MulticurrencyID',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 275),
382 'multicurrency_code' => array(
'type' =>
'varchar(255)',
'label' =>
'Currency',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 280),
383 'multicurrency_tx' => array(
'type' =>
'double(24,8)',
'label' =>
'CurrencyRate',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 285,
'isameasure' => 1),
384 'multicurrency_total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountHT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 290,
'isameasure' => 1),
385 'multicurrency_total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountVAT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 291,
'isameasure' => 1),
386 'multicurrency_total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountTTC',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 292,
'isameasure' => 1),
387 'fk_fac_rec_source' => array(
'type' =>
'integer',
'label' =>
'RecurringInvoiceSource',
'enabled' => 1,
'visible' => -1,
'position' => 305),
388 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'LastMainDoc',
'enabled' => 1,
'visible' => -1,
'position' => 310),
389 'module_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSModule',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 315),
390 'pos_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSTerminal',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 320),
391 'pos_print_counter' => array(
'type' =>
'integer',
'label' =>
'PrintCount',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => 0,
'position' => 325),
392 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 500),
393 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModificationShort',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 502),
394 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'position' => 506),
395 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModification',
'enabled' => 1,
'visible' => -1,
'notnull' => -1,
'position' => 508),
396 'fk_user_valid' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserValidation',
'enabled' => 1,
'visible' => -1,
'position' => 510),
397 'fk_user_closing' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserClosing',
'enabled' => 1,
'visible' => -1,
'position' => 512),
398 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 900),
399 'fk_statut' => array(
'type' =>
'smallint(6)',
'label' =>
'Status',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'position' => 1000,
'arrayofkeyval' => array(0 =>
'Draft', 1 =>
'Validated', 2 =>
'Paid', 3 =>
'Abandonned')),
478 $this->ismultientitymanaged = 1;
479 $this->isextrafieldmanaged = 1;
481 $this->fields[
'ref_ext'][
'visible'] =
getDolGlobalInt(
'MAIN_LIST_SHOW_REF_EXT');
494 if ($field ==
'ref_client') {
498 return parent::persistFieldValue($user, $field);
512 public function create(
User $user, $notrigger = 0, $forceduedate = 0, $updatecurrencyrate = 0)
516 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
518 if (empty($this->
type)) {
522 $this->ref_client = trim((
string) $this->ref_client);
523 $this->ref_customer = trim((
string) $this->ref_customer);
525 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
526 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
527 $this->note_public = (isset($this->note_public) ? trim($this->note_public) :
'');
529 if (!$this->cond_reglement_id) {
530 $this->cond_reglement_id = 0;
532 if (!$this->mode_reglement_id) {
533 $this->mode_reglement_id = 0;
538 if (!empty($this->multicurrency_code)) {
540 if (empty($this->multicurrency_tx)) {
548 $this->fk_multicurrency = 0;
550 if (empty($this->fk_multicurrency)) {
551 $this->multicurrency_code =
$conf->currency;
552 $this->fk_multicurrency = 0;
553 $this->multicurrency_tx = 1;
557 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
560 if (empty($this->
date)) {
561 $this->error =
"Try to create an invoice with an empty parameter (date)";
562 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
566 $result = $soc->fetch($this->socid);
568 $this->error =
"Failed to fetch company: ".$soc->error;
569 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
574 if ($this->
type == self::TYPE_REPLACEMENT && $this->fk_facture_source > 0) {
575 $facreplaced =
new Facture($this->db);
576 if ($facreplaced->fetch($this->fk_facture_source) > 0 && $facreplaced->getVentilExportCompta() > 0) {
577 $langs->load(
'bills');
578 $this->error = $langs->trans(
"ErrorInvoiceReplacedAlreadyInAccountancy", $facreplaced->ref);
579 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
585 $this->date_creation = $now;
589 $originaldatewhen =
null;
590 $nextdatewhen =
null;
591 $previousdaynextdatewhen =
null;
596 if ($this->fac_rec > 0) {
597 $this->fk_fac_rec_source = $this->fac_rec;
599 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
601 $result = $_facrec->fetch($this->fac_rec);
602 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
606 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
610 $originaldatewhen = $_facrec->date_when;
611 $nextdatewhen =
null;
612 $previousdaynextdatewhen =
null;
614 if ($originaldatewhen) {
616 if ($_facrec->rule_for_lines_dates ==
'postpaid') {
618 $originaldatewhen =
dol_time_plus_duree($originaldatewhen, -$_facrec->frequency, $_facrec->unit_frequency, 0,
'tzserver');
620 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, (
int) $_facrec->frequency, $_facrec->unit_frequency, 0,
'tzserver');
626 if (!empty($_facrec->frequency)) {
627 $this->socid = $_facrec->socid;
631 $this->entity = $_facrec->entity;
636 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
637 $this->note_public =
GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
638 $this->note_private =
GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
639 $this->model_pdf =
GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
640 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
641 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
642 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
645 $this->total_ht = $_facrec->total_ht;
646 $this->total_ttc = $_facrec->total_ttc;
649 $this->fk_incoterms = $_facrec->fk_incoterms;
650 $this->location_incoterms = $_facrec->location_incoterms;
656 $this->ref_client = trim($this->ref_client);
657 $this->ref_customer = trim($this->ref_customer);
658 $this->note_public = trim($this->note_public);
659 $this->note_private = trim($this->note_private);
660 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
663 foreach ($_facrec->array_options as $key => $val) {
664 if (!isset($this->array_options[$key]) || $this->array_options[$key] ===
'') {
665 $this->array_options[$key] = $val;
669 if (!$this->mode_reglement_id) {
670 $this->mode_reglement_id = 0;
675 $this->linked_objects = $_facrec->linkedObjectsIds;
680 if ($_facrec->frequency > 0) {
681 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
682 if (empty($_facrec->date_when)) {
683 $_facrec->date_when = $now;
685 $next_date = $_facrec->getNextDate();
687 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
690 $result = $_facrec->setNextDate($next_date, 1);
694 $outputlangs = $langs;
697 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
698 $newlang = $this->thirdparty->default_lang;
701 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
702 $newlang = $this->default_lang;
704 if (!empty($newlang)) {
706 $outputlangs->setDefaultLang($newlang);
710 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $this);
721 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
722 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
723 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
724 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
725 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
736 if (empty($forceduedate)) {
742 $this->date_lim_reglement = $duedate;
744 $this->date_lim_reglement = $forceduedate;
748 $socid = $this->socid;
750 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
759 $sql .=
", date_pointoftax";
760 $sql .=
", note_private";
761 $sql .=
", note_public";
762 $sql .=
", ref_client";
763 $sql .=
", fk_account";
764 $sql .=
", module_source, pos_source, pos_print_counter, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
765 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
766 $sql .=
", fk_input_reason";
767 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
768 $sql .=
", fk_incoterms, location_incoterms";
769 $sql .=
", fk_multicurrency";
770 $sql .=
", multicurrency_code";
771 $sql .=
", multicurrency_tx";
772 $sql .=
", retained_warranty";
773 $sql .=
", retained_warranty_date_limit";
774 $sql .=
", retained_warranty_fk_cond_reglement";
779 $sql .=
", ".(int) $this->entity;
780 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
781 $sql .=
", ".((int) $this->
type);
782 $sql .=
", ".(isset($this->subtype) ? (int) $this->subtype :
"null");
783 $sql .=
", ".((int) $socid);
784 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
787 $sql .=
", '".$this->db->idate($this->
date).
"'";
788 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
789 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
790 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
791 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
792 $sql .=
", ".($this->fk_account > 0 ? ((int) $this->fk_account) :
'NULL');
793 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
794 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape((
string) $this->pos_source).
"'" :
"null");
795 $sql .=
", ".(int) $this->pos_print_counter;
796 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape((
string) $this->fk_fac_rec_source).
"'" :
"null");
797 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape((
string) $this->fk_facture_source).
"'" :
"null");
798 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
799 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
800 $sql .=
", ".((int) $this->cond_reglement_id);
801 $sql .=
", ".((int) $this->mode_reglement_id);
802 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
803 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
804 $sql .=
", ".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id :
"null");
805 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape((
string) $this->situation_cycle_ref).
"'" :
"null");
806 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape((
string) $this->situation_counter).
"'" :
"null");
807 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
808 $sql .=
", ".(int) $this->fk_incoterms;
809 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
810 $sql .=
", ".(int) $this->fk_multicurrency;
811 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
812 $sql .=
", ".(float) $this->multicurrency_tx;
813 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape((
string) $this->retained_warranty));
814 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
815 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
816 $sql .=
", ".(!empty($this->ip) ?
"'".$this->db->escape($this->ip).
"'" :
"null");
819 $resql = $this->db->query($sql);
821 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
824 if ($origin_user_author_id > 0) {
825 $this->user_creation_id = $origin_user_author_id;
826 $this->fk_user_author = $origin_user_author_id;
830 $this->
ref =
'(PROV'.$this->id.
')';
831 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
833 $resql = $this->db->query($sql);
838 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
839 $this->linked_objects = $this->linkedObjectsIds;
843 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
844 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
845 if (is_array($tmp_origin_id)) {
846 foreach ($tmp_origin_id as $origin_id) {
849 $this->error = $this->db->lasterror();
854 $origin_id = $tmp_origin_id;
857 $this->error = $this->db->lasterror();
865 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && (!empty($this->origin_type) || !empty($this->origin)) && !empty($this->origin_id)) {
866 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
867 $originidforcontact = $this->origin_id;
868 if ($originforcontact ==
'shipping') {
869 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
871 $exp->fetch($this->origin_id);
872 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
873 if (!empty($exp->linkedObjectsIds[
'commande']) && is_array($exp->linkedObjectsIds[
'commande'])) {
874 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
875 $originforcontact =
'commande';
876 if (is_object($value)) {
877 $originidforcontact = $value->id;
879 $originidforcontact = $value;
886 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople";
887 $sqlcontact .=
" FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
888 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
890 $resqlcontact = $this->db->query($sqlcontact);
892 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
893 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
896 dol_print_error($this->db);
901 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
904 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
905 foreach ($this->lines as $i => $val) {
906 $newinvoiceline = $this->lines[$i];
907 '@phan-var-force FactureLigne $newinvoiceline';
909 $newinvoiceline->context = $this->context;
911 $newinvoiceline->fk_facture = $this->id;
913 $newinvoiceline->origin = $this->lines[$i]->element;
914 $newinvoiceline->origin_type = $this->lines[$i]->element;
915 $newinvoiceline->origin_id = $this->lines[$i]->id;
918 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
919 $newinvoiceline->date_start = $originaldatewhen;
921 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
922 $newinvoiceline->date_end = $previousdaynextdatewhen;
927 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
932 $vatrate = $newinvoiceline->tva_tx;
933 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
934 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
937 $newinvoiceline->fk_parent_line = $fk_parent_line;
941 $discount->fetch($newinvoiceline->fk_remise_except);
943 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
944 $newinvoiceline->fk_remise_except = $discountId;
948 $line_price_base_type = $newinvoiceline->getPriceBaseType();
950 $newinvoiceline->desc,
951 (
float) $newinvoiceline->subprice,
952 $newinvoiceline->qty,
954 $newinvoiceline->localtax1_tx,
955 $newinvoiceline->localtax2_tx,
956 $newinvoiceline->fk_product,
957 $newinvoiceline->remise_percent,
958 $newinvoiceline->date_start,
959 $newinvoiceline->date_end,
960 $newinvoiceline->fk_code_ventilation,
961 $newinvoiceline->info_bits,
962 $newinvoiceline->fk_remise_except,
963 $line_price_base_type,
964 (
float) $newinvoiceline->subprice_ttc,
965 $newinvoiceline->product_type,
966 $newinvoiceline->rang,
967 $newinvoiceline->special_code,
968 $newinvoiceline->element,
971 $newinvoiceline->fk_fournprice,
972 $newinvoiceline->pa_ht,
973 $newinvoiceline->label,
974 $newinvoiceline->array_options,
975 $newinvoiceline->situation_percent,
976 $newinvoiceline->fk_prev_id,
977 $newinvoiceline->fk_unit,
978 $newinvoiceline->multicurrency_subprice,
979 $newinvoiceline->ref_ext,
990 if ($result > 0 && $newinvoiceline->product_type == 9) {
991 $fk_parent_line = $result;
995 } elseif (!$error && empty($this->fac_rec)) {
998 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
1002 $linestoadd = $this->lines;
1003 $this->lines = array();
1004 foreach ($linestoadd as $i => $val) {
1005 $line = $linestoadd[$i];
1006 '@phan-var-force FactureLigne $line';
1010 if (!is_object($line)) {
1011 $line = (object) $line;
1016 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1017 $fk_parent_line = 0;
1021 $vatrate = $line->tva_tx;
1022 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
1023 $vatrate .=
' ('.$line->vat_src_code.
')';
1027 $originid = $line->origin_id;
1028 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
1030 $originid = $line->id;
1031 $origintype = $this->element;
1035 if (empty($line->ref_ext)) {
1036 $line->ref_ext =
'';
1044 $line->localtax1_tx,
1045 $line->localtax2_tx,
1047 $line->remise_percent,
1050 $line->fk_code_ventilation,
1052 $line->fk_remise_except,
1055 $line->product_type,
1057 $line->special_code,
1061 $line->fk_fournprice,
1064 $line->array_options,
1065 $line->situation_percent,
1068 $line->multicurrency_subprice,
1073 $this->error = $this->db->lasterror();
1074 dol_print_error($this->db);
1075 $this->db->rollback();
1080 if ($result > 0 && $line->product_type == 9) {
1081 $fk_parent_line = $result;
1088 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1089 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1090 $fk_parent_line = 0;
1092 foreach ($_facrec->lines as $i => $val) {
1094 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1095 $fk_parent_line = 0;
1098 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1099 $tva_npr = (int) $_facrec->lines[$i]->info_bits;
1100 if (empty($tva_tx)) {
1103 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1104 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1106 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1107 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1110 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1111 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1113 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1118 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1119 $buyprice = $producttmp->cost_price;
1121 $buyprice = $producttmp->pmp;
1123 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1124 if ($producttmp->product_fourn_price_id > 0) {
1125 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1132 if ($updatecurrencyrate == 1) {
1134 } elseif ($updatecurrencyrate == 2) {
1138 $result_insert = $this->
addline(
1139 $_facrec->lines[$i]->desc,
1140 $_facrec->lines[$i]->subprice,
1141 $_facrec->lines[$i]->qty,
1145 $_facrec->lines[$i]->fk_product,
1146 $_facrec->lines[$i]->remise_percent,
1147 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1148 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1154 $_facrec->lines[$i]->product_type,
1155 $_facrec->lines[$i]->rang,
1156 $_facrec->lines[$i]->special_code,
1160 $fk_product_fournisseur_price,
1161 is_null($buyprice) ?
'' : $buyprice,
1162 $_facrec->lines[$i]->label,
1163 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1166 $_facrec->lines[$i]->fk_unit,
1167 $_facrec->lines[$i]->multicurrency_subprice,
1168 $_facrec->lines[$i]->ref_ext,
1172 foreach ($this->lines as $line) {
1173 if ($line->id == $result_insert) {
1174 $line->extraparams = $_facrec->lines[$i]->extraparams;
1175 $line->setExtraParameters();
1180 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1181 $fk_parent_line = $result_insert;
1184 if ($result_insert < 0) {
1186 $this->error = $this->db->error();
1195 $this->error = $langs->trans(
'FailedToUpdatePrice');
1196 $this->db->rollback();
1211 if (!$error && !$notrigger) {
1213 $result = $this->call_trigger(
'BILL_CREATE', $user);
1220 $this->db->commit();
1223 $this->db->rollback();
1227 $this->error = $this->db->error();
1228 $this->db->rollback();
1244 $facture =
new Facture($this->db);
1247 $facture->context[
'createfromclone'] = 1;
1252 if (empty($this->array_options)) {
1256 if (!empty($this->array_options)) {
1257 $facture->array_options = $this->array_options;
1260 foreach ($this->lines as &$line) {
1261 $line->fetch_optionals();
1264 $facture->fk_facture_source = $this->fk_facture_source;
1265 $facture->type = $this->type;
1266 $facture->subtype = $this->subtype;
1267 $facture->socid = $this->socid;
1268 $facture->date = $this->date;
1269 $facture->date_pointoftax = $this->date_pointoftax;
1270 $facture->note_public = $this->note_public;
1271 $facture->note_private = $this->note_private;
1272 $facture->ref_client = $this->ref_client;
1273 $facture->ref_customer = $this->ref_customer;
1274 $facture->model_pdf = $this->model_pdf;
1275 $facture->fk_project = $this->fk_project;
1276 $facture->cond_reglement_id = $this->cond_reglement_id;
1277 $facture->mode_reglement_id = $this->mode_reglement_id;
1279 $facture->origin = $this->origin;
1280 $facture->origin_id = $this->origin_id;
1281 $facture->fk_account = $this->fk_account;
1283 $facture->lines = $this->lines;
1284 $facture->situation_counter = $this->situation_counter;
1285 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1286 $facture->situation_final = $this->situation_final;
1288 $facture->retained_warranty = $this->retained_warranty;
1289 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1290 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1292 $facture->fk_user_author = $user->id;
1293 $facture->user_creation_id = $user->id;
1297 foreach ($facture->lines as $i => $tmpline) {
1298 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1299 if ($invertdetail) {
1300 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1301 $facture->lines[$i]->subprice_ttc = -$facture->lines[$i]->subprice_ttc;
1302 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1303 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1304 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1305 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1306 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1307 $facture->lines[$i]->ref_ext =
'';
1311 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1313 $facid = $facture->create($user);
1315 $this->error = $facture->error;
1316 $this->errors = $facture->errors;
1320 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1321 foreach ($Tfk_object as $fk_object) {
1322 $facture->add_object_linked($typeObject, $fk_object);
1326 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1343 global $hookmanager;
1363 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1364 $objsoc =
new Societe($this->db);
1366 if ($objsoc->fetch($this->socid) > 0) {
1368 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1369 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1371 $object->fk_delivery_address = 0;
1377 $object->entity = (!empty($forceentity) ? $forceentity :
$object->entity);
1385 $object->user_creation_id = $user->id;
1386 $object->user_validation_id =
null;
1387 $object->user_modification_id =
null;
1388 $object->fk_user_author = $user->id;
1389 $object->fk_user_valid =
null;
1390 $object->fk_facture_source = 0;
1391 $object->fk_fac_rec_source = 0;
1393 $object->date_modification =
'';
1394 $object->date_validation =
'';
1405 foreach (
$object->lines as $i => $line) {
1406 '@phan-var-force FactureLigne $line';
1407 if (($line->info_bits & 0x02) == 0x02) {
1414 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1426 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1427 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1431 $object->lines[$i]->date_start = $newFirst;
1432 $object->lines[$i]->date_end = $newLast;
1436 $object->lines[$i]->ref_ext =
'';
1439 $object->lines[$i]->fk_code_ventilation = 0;
1443 $object->context[
'createfromclone'] =
'createfromclone';
1444 $object->context[
'createfromclone_fromid'] = $objFrom->id;
1445 $object->context[
'createfromclone_fromref'] = $objFrom->ref;
1446 $result =
$object->create($user);
1453 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1456 } elseif (
$object->socid == $objFrom->socid) {
1458 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1467 if (is_object($hookmanager)) {
1468 $parameters = array(
'objFrom' => $objFrom,
'clonedObj' =>
$object);
1470 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1478 unset(
$object->context[
'createfromclone']);
1479 unset(
$object->context[
'createfromclone_fromid']);
1480 unset(
$object->context[
'createfromclone_fromref']);
1484 $this->db->commit();
1487 $this->db->rollback();
1501 global $hookmanager;
1510 $this->context[
'createfromclone'] = 1;
1513 for ($i = 0; $i < $num; $i++) {
1515 $src_line =
$object->lines[$i];
1516 '@phan-var-force FactureLigne $src_line';
1517 $line->libelle = $src_line->libelle;
1518 $line->label = $src_line->label;
1519 $line->desc = $src_line->desc;
1520 $line->subprice = $src_line->subprice;
1521 $line->subprice_ttc = $src_line->subprice_ttc;
1522 $line->total_ht = $src_line->total_ht;
1523 $line->total_tva = $src_line->total_tva;
1524 $line->total_localtax1 = $src_line->total_localtax1;
1525 $line->total_localtax2 = $src_line->total_localtax2;
1526 $line->total_ttc = $src_line->total_ttc;
1527 $line->vat_src_code = $src_line->vat_src_code;
1528 $line->tva_tx = $src_line->tva_tx;
1529 $line->localtax1_tx = $src_line->localtax1_tx;
1530 $line->localtax2_tx = $src_line->localtax2_tx;
1531 $line->qty = $src_line->qty;
1532 $line->fk_remise_except = $src_line->fk_remise_except;
1533 $line->remise_percent = $src_line->remise_percent;
1534 $line->fk_product = $src_line->fk_product;
1535 $line->info_bits = $src_line->info_bits;
1536 $line->product_type = $src_line->product_type;
1537 $line->rang = $src_line->rang;
1538 $line->special_code = $src_line->special_code;
1539 $line->fk_parent_line = $src_line->fk_parent_line;
1540 $line->fk_unit = $src_line->fk_unit;
1541 $line->date_start = $src_line->date_start;
1542 $line->date_end = $src_line->date_end;
1545 $line->fk_multicurrency = $src_line->fk_multicurrency;
1546 $line->multicurrency_code = $src_line->multicurrency_code;
1547 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1548 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1549 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1550 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1552 $line->fk_fournprice = $src_line->fk_fournprice;
1553 $marginInfos =
getMarginInfos($src_line->subprice, $src_line->remise_percent, $src_line->tva_tx, $src_line->localtax1_tx, $src_line->localtax2_tx, $src_line->fk_fournprice, $src_line->pa_ht);
1554 $line->pa_ht = $marginInfos[0];
1557 $src_line->fetch_optionals();
1558 foreach ($src_line->array_options as $options_key => $value) {
1559 $line->array_options[$options_key] = $value;
1562 $this->lines[$i] = $line;
1565 $this->socid =
$object->socid;
1566 $this->fk_project =
$object->fk_project;
1567 $this->fk_account =
$object->fk_account;
1568 $this->cond_reglement_id =
$object->cond_reglement_id;
1569 $this->mode_reglement_id =
$object->mode_reglement_id;
1570 $this->fk_incoterms =
$object->fk_incoterms;
1571 $this->location_incoterms =
$object->location_incoterms;
1572 $this->availability_id =
$object->availability_id;
1573 $this->demand_reason_id =
$object->demand_reason_id;
1574 $this->delivery_date =
$object->delivery_date;
1575 $this->fk_delivery_address =
$object->fk_delivery_address;
1576 $this->contact_id =
$object->contact_id;
1577 $this->ref_client =
$object->ref_client;
1578 $this->ref_customer =
$object->ref_client;
1581 $this->note_private =
$object->note_private;
1582 $this->note_public =
$object->note_public;
1585 $this->module_source =
$object->module_source;
1586 $this->pos_source =
$object->pos_source;
1588 $this->origin =
$object->element;
1589 $this->origin_type =
$object->element;
1590 $this->origin_id =
$object->id;
1592 $this->fk_user_author = $user->id;
1593 $this->user_creation_id = $user->id;
1597 foreach (
$object->array_options as $options_key => $value) {
1598 $this->array_options[$options_key] = $value;
1602 $this->linked_objects[$this->origin] = $this->origin_id;
1603 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1604 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1607 $ret = $this->
create($user);
1611 $hookmanager->initHooks(array(
'invoicedao'));
1613 $parameters = array(
'objFrom' =>
$object);
1615 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1624 unset($this->context[
'createfromclone']);
1643 global $hookmanager;
1651 $use_all_lines = empty($lines);
1653 for ($i = 0; $i < $num; $i++) {
1654 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1660 $line->libelle =
$object->lines[$i]->libelle;
1661 $line->label =
$object->lines[$i]->label;
1662 $line->desc =
$object->lines[$i]->desc;
1663 $line->subprice =
$object->lines[$i]->subprice;
1664 $line->subprice_ttc =
$object->lines[$i]->subprice_ttc;
1665 $line->total_ht =
$object->lines[$i]->total_ht;
1666 $line->total_tva =
$object->lines[$i]->total_tva;
1667 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1668 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1669 $line->total_ttc =
$object->lines[$i]->total_ttc;
1670 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1671 $line->tva_tx =
$object->lines[$i]->tva_tx;
1672 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1673 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1674 $line->qty =
$object->lines[$i]->qty;
1675 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1676 $line->remise_percent =
$object->lines[$i]->remise_percent;
1677 $line->fk_product =
$object->lines[$i]->fk_product;
1678 $line->info_bits =
$object->lines[$i]->info_bits;
1679 $line->product_type =
$object->lines[$i]->product_type;
1680 $line->rang =
$object->lines[$i]->rang;
1681 $line->special_code =
$object->lines[$i]->special_code;
1682 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1683 $line->fk_unit =
$object->lines[$i]->fk_unit;
1684 $line->date_start =
$object->lines[$i]->date_start;
1685 $line->date_end =
$object->lines[$i]->date_end;
1688 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1689 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1690 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1691 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1692 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1693 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1695 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1697 $line->pa_ht = $marginInfos[0];
1700 $object->lines[$i]->fetch_optionals();
1701 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1702 $line->array_options[$options_key] = $value;
1705 $this->lines[$i] = $line;
1708 $this->socid =
$object->socid;
1709 $this->fk_project =
$object->fk_project;
1710 $this->fk_account =
$object->fk_account;
1711 $this->cond_reglement_id =
$object->cond_reglement_id;
1712 $this->mode_reglement_id =
$object->mode_reglement_id;
1714 $this->demand_reason_id =
$object->demand_reason_id;
1716 $this->contact_id =
$object->contact_id;
1717 $this->ref_customer =
$object->ref_customer;
1718 $this->ref_client =
$object->ref_customer;
1721 $this->note_private =
$object->note_private;
1722 $this->note_public =
$object->note_public;
1728 $this->origin =
$object->element;
1729 $this->origin_id =
$object->id;
1731 $this->fk_user_author = $user->id;
1732 $this->user_creation_id = $user->id;
1736 foreach (
$object->array_options as $options_key => $value) {
1737 $this->array_options[$options_key] = $value;
1741 $this->linked_objects[$this->origin] = $this->origin_id;
1742 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1743 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1746 $ret = $this->
create($user);
1750 $hookmanager->initHooks(array(
'invoicedao'));
1752 $parameters = array(
'objFrom' =>
$object);
1754 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1784 global
$conf, $langs, $hookmanager, $action;
1786 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1787 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1792 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1796 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1799 $origin->error =
'ErrorDateIsInFuture';
1803 if ($payment_terms_id <= 0) {
1804 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1808 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1810 if (empty($payment_conditions_deposit_percent)) {
1811 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1815 if (empty($origin->deposit_percent)) {
1816 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1820 $deposit =
new self($origin->db);
1821 $deposit->socid = $origin->socid;
1823 $deposit->fk_project = $origin->fk_project;
1824 $deposit->ref_client = $origin->ref_client;
1825 $deposit->ref_customer = $origin->ref_client;
1826 $deposit->date = $date;
1827 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1828 $deposit->cond_reglement_id = $payment_terms_id;
1829 $deposit->availability_id = $origin->availability_id;
1830 $deposit->demand_reason_id = $origin->demand_reason_id;
1831 $deposit->fk_account = $origin->fk_account;
1832 $deposit->fk_incoterms = $origin->fk_incoterms;
1833 $deposit->location_incoterms = $origin->location_incoterms;
1834 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1835 $deposit->multicurrency_code = $origin->multicurrency_code;
1836 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1837 $deposit->module_source = $origin->module_source;
1838 $deposit->pos_source = $origin->pos_source;
1839 $deposit->model_pdf =
'sponge';
1841 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1850 $deposit->note_private = $origin->note_private;
1851 $deposit->note_public = $origin->note_public;
1854 $deposit->origin = $origin->element;
1855 $deposit->origin_type = $origin->element;
1856 $deposit->origin_id = $origin->id;
1858 $origin->fetch_optionals();
1860 foreach ($origin->array_options as $extrakey => $value) {
1861 $deposit->array_options[$extrakey] = $value;
1864 $deposit->linked_objects[$deposit->origin_type] = $deposit->origin_id;
1866 foreach ($overrideFields as $key => $value) {
1867 $deposit->$key = $value;
1870 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1872 $origin->db->begin();
1875 $createReturn = $deposit->create($user, $notrigger);
1877 if ($createReturn <= 0) {
1878 $origin->db->rollback();
1879 $origin->error = $deposit->error;
1880 $origin->errors = $deposit->errors;
1884 $amount_ttc_diff = 0;
1885 $amountdeposit = array();
1886 $descriptions = array();
1893 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1895 $TTotalByTva = array();
1896 foreach ($origin->lines as &$line) {
1897 if (!empty($line->special_code)) {
1900 $key = $line->tva_tx . ($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
1901 if (!array_key_exists($key, $TTotalByTva)) {
1902 $TTotalByTva[$key] = 0;
1903 $descriptions[$key] =
'';
1905 $TTotalByTva[$key] += $line->total_ttc;
1906 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1907 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1908 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1909 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1912 foreach ($TTotalByTva as $tva => &$total) {
1913 $tva_rate_only = preg_replace(
'/\s*\(.*\)/',
'', (
string) $tva);
1914 $coef = ($origin->total_ttc != 0 ? $total / $origin->total_ttc : 0);
1915 $am = $amount * $coef;
1916 $amount_ttc_diff += $am;
1917 if (!isset($amountdeposit[$tva])) {
1918 $amountdeposit[$tva] = 0;
1920 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100);
1922 unset($line, $total);
1925 $lines = $origin->lines;
1926 $numlines = count($lines);
1927 for ($i = 0; $i < $numlines; $i++) {
1928 if (empty($lines[$i]->qty)) {
1931 if (!empty($lines[$i]->special_code)) {
1935 $totalamount += $lines[$i]->total_ht;
1936 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ?
' ('.$lines[$i]->vat_src_code.
')' :
'');
1937 if (!isset($amountdeposit[$tva_key])) {
1938 $amountdeposit[$tva_key] = 0;
1939 $descriptions[$tva_key] =
'';
1941 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1942 $descriptions[$tva_key] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1943 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1944 $descriptions[$tva_key] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1945 $descriptions[$tva_key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1948 if ($totalamount == 0) {
1949 $amountdeposit[0] = 0;
1952 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1955 foreach ($amountdeposit as $tva => $amount) {
1956 if (empty($amount)) {
1960 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1963 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1964 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1967 $addlineResult = $deposit->addline(
1994 if ($addlineResult < 0) {
1995 $origin->db->rollback();
1996 $origin->error = $deposit->error;
1997 $origin->errors = $deposit->errors;
2002 $diff = $deposit->total_ttc - $amount_ttc_diff;
2005 $deposit->fetch_lines();
2006 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
2010 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ?
' ('.$deposit->lines[0]->vat_src_code.
')' :
'');
2011 $updatelineResult = $deposit->updateline(
2012 $deposit->lines[0]->id,
2013 $deposit->lines[0]->desc,
2015 $deposit->lines[0]->qty,
2016 $deposit->lines[0]->remise_percent,
2017 $deposit->lines[0]->date_start,
2018 $deposit->lines[0]->date_end,
2023 $deposit->lines[0]->info_bits,
2024 $deposit->lines[0]->product_type,
2028 $deposit->lines[0]->pa_ht,
2029 $deposit->lines[0]->label,
2035 if ($updatelineResult < 0) {
2036 $origin->db->rollback();
2037 $origin->error = $deposit->error;
2038 $origin->errors = $deposit->errors;
2043 $hookmanager->initHooks(array(
'invoicedao'));
2045 $parameters = array(
'objFrom' => $origin);
2046 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
2049 $origin->db->rollback();
2050 $origin->error = $hookmanager->error;
2051 $origin->errors = $hookmanager->errors;
2055 if (!empty($autoValidateDeposit)) {
2056 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
2058 if ($validateReturn < 0) {
2059 $origin->db->rollback();
2060 $origin->error = $deposit->error;
2061 $origin->errors = $deposit->errors;
2066 unset($deposit->context[
'createdepositfromorigin']);
2068 $origin->db->commit();
2084 $langs->load(
'bills');
2087 $nofetch = !empty($params[
'nofetch']);
2088 $moretitle = $params[
'moretitle'] ??
'';
2090 $picto = $this->picto;
2091 if ($this->
type == self::TYPE_REPLACEMENT) {
2094 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2097 if ($this->
type == self::TYPE_DEPOSIT) {
2101 if ($user->hasRight(
"facture",
"read")) {
2102 $datas[
'picto'] = img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
2104 $datas[
'picto'] .=
' '.$this->getLibType(1);
2107 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
2110 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2113 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
2116 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2117 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2120 $datas[
'picto'] .=
' - '.$moretitle;
2122 if (!empty($this->
ref)) {
2123 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2126 $langs->load(
'companies');
2127 if (empty($this->thirdparty)) {
2130 $datas[
'customer'] =
'<br><b>'.$langs->trans(
'Customer').
':</b> '.$this->thirdparty->getNomUrl(1,
'', 0, 1);
2132 $datas[
'RefCustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.(empty($this->ref_customer) ? (empty($this->ref_client) ?
'' : $this->ref_client) : $this->ref_customer);
2134 $langs->load(
'project');
2135 if (is_null($this->project) || (is_object($this->project) && $this->project->isEmpty())) {
2137 if ($res > 0 && $this->project instanceof
Project) {
2138 $datas[
'project'] =
'<br><b>'.$langs->trans(
'Project').
':</b> '.$this->project->getNomUrl(1,
'', 0,
'1');
2142 if (!empty($this->
date)) {
2143 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->
date,
'day');
2145 if (!empty($this->total_ht)) {
2146 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2148 if (!empty($this->total_tva)) {
2149 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2151 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2152 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1,
$conf->currency);
2154 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2156 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1',
$mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency);
2158 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2159 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2',
$mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency);
2161 if (!empty($this->total_ttc)) {
2162 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2183 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2185 global $langs,
$conf, $user;
2187 if (!empty(
$conf->dol_no_mouse_hover)) {
2193 if ($option ==
'withdraw') {
2194 $baseurl = DOL_URL_ROOT.
'/compta/facture/prelevement.php';
2195 $query = [
'facid' => $this->id];
2197 $baseurl = DOL_URL_ROOT.
'/compta/facture/card.php';
2198 $query = [
'id' => $this->id];
2201 if (!$user->hasRight(
"facture",
"read")) {
2205 if ($option !==
'nolink') {
2207 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2208 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2209 $add_save_lastsearch_values = 1;
2211 if ($add_save_lastsearch_values) {
2212 $query = array_merge($query, [
'save_lastsearch_values' => 1]);
2221 $picto = $this->picto;
2222 if ($this->
type == self::TYPE_REPLACEMENT) {
2225 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2228 if ($this->
type == self::TYPE_DEPOSIT) {
2234 'objecttype' => $this->element,
2235 'moretitle' => $moretitle,
2236 'option' => $option,
2239 $classfortooltip =
'classfortooltip';
2242 $classfortooltip =
'classforajaxtooltip';
2243 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2249 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2250 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2252 $label = $langs->trans(
"Invoice");
2253 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2255 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2256 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2259 $linkstart =
'<a href="'.$url.
'"';
2260 $linkstart .= $linkclose.
'>';
2263 if ($option ==
'nolink') {
2268 $result .= $linkstart;
2270 $result .= img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2272 if ($withpicto != 2) {
2273 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2275 $result .= $linkend;
2277 if ($addlinktonotes) {
2278 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2280 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2281 $result .=
' <span class="note inline-block">';
2282 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.dolPrintHTMLForAttribute($notetoshow).
'">';
2283 $result .= img_picto(
'',
'note');
2285 $result .=
'</span>';
2289 global $action, $hookmanager;
2290 $hookmanager->initHooks(array(
'invoicedao'));
2291 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2292 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2294 $result = $hookmanager->resPrint;
2296 $result .= $hookmanager->resPrint;
2312 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2314 global
$conf, $extrafields;
2316 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2320 $extraFieldsCheck =
false;
2321 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2323 if ($doFetchInOneSqlRequest) {
2325 if (!isset($extrafields) || !is_object($extrafields)) {
2326 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2331 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
2332 $extrafields->fetch_name_optionals_label($this->table_element);
2335 $extraFieldsCheck = (
2336 !empty($extrafields->attributes[$this->table_element][
'label'])
2337 && is_array($extrafields->attributes[$this->table_element][
'label'])
2338 && count($extrafields->attributes[$this->table_element][
'label']) > 0
2344 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2345 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2346 $sql .=
', f.datef as df, f.date_pointoftax';
2347 $sql .=
', f.date_lim_reglement as dlr';
2348 $sql .=
', f.datec as datec';
2349 $sql .=
', f.date_valid as datev';
2350 $sql .=
', f.tms as datem';
2351 $sql .=
', f.note_private, f.note_public, f.fk_statut as status, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.fk_user_modif, f.model_pdf, f.last_main_doc';
2352 $sql .=
", f.fk_input_reason";
2353 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2354 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2355 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2356 $sql .=
', f.fk_account';
2357 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2358 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2359 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2360 $sql .=
', f.fk_incoterms, f.location_incoterms';
2361 $sql .=
', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2362 $sql .=
", i.libelle as label_incoterms";
2363 $sql .=
", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement";
2364 $sql .=
", f.payment_reference, f.dispute_status";
2366 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2367 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2368 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2369 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2372 if ($type !==
'separate') {
2373 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2374 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2376 $sql .=
", ef.".$this->db->sanitize($key);
2382 $sql .=
' FROM '.$this->db->prefix().
'facture as f';
2385 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2387 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element.
'_extrafields as ef ON f.rowid = ef.fk_object';
2390 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2391 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_paiement as p ON f.fk_mode_reglement = p.id';
2392 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2393 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2396 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2398 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2400 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2403 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2407 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2408 $resql = $this->db->query($sql);
2410 if ($this->db->num_rows($resql)) {
2411 $obj = $this->db->fetch_object($resql);
2413 $this->
id = $obj->rowid;
2414 $this->entity = $obj->entity;
2416 $this->
ref = $obj->ref;
2417 $this->ref_client = $obj->ref_client;
2418 $this->ref_customer = $obj->ref_client;
2419 $this->ref_ext = $obj->ref_ext;
2420 $this->
type = $obj->type;
2421 $this->subtype = $obj->subtype;
2422 $this->
date = $this->db->jdate($obj->df);
2423 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2424 $this->date_creation = $this->db->jdate($obj->datec);
2425 $this->date_validation = $this->db->jdate($obj->datev);
2426 $this->date_modification = $this->db->jdate($obj->datem);
2427 $this->datem = $this->db->jdate($obj->datem);
2428 $this->total_ht = $obj->total_ht;
2429 $this->total_tva = $obj->total_tva;
2430 $this->total_localtax1 = $obj->localtax1;
2431 $this->total_localtax2 = $obj->localtax2;
2432 $this->total_ttc = $obj->total_ttc;
2433 $this->revenuestamp = $obj->revenuestamp;
2434 $this->paye = $obj->paye;
2435 $this->close_code = $obj->close_code;
2436 $this->close_note = $obj->close_note;
2438 $this->socid = $obj->fk_soc;
2439 $this->thirdparty =
null;
2441 $this->fk_project = $obj->fk_project;
2442 $this->project =
null;
2444 $this->statut = $obj->status;
2445 $this->
status = $obj->status;
2447 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2448 $this->mode_reglement_id = $obj->fk_mode_reglement;
2449 $this->mode_reglement_code = $obj->mode_reglement_code;
2450 $this->mode_reglement = $obj->mode_reglement_libelle;
2451 $this->cond_reglement_id = $obj->fk_cond_reglement;
2452 $this->cond_reglement_code = $obj->cond_reglement_code;
2453 $this->cond_reglement = $obj->cond_reglement_libelle;
2454 $this->cond_reglement_label = $obj->cond_reglement_libelle;
2455 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2456 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2457 $this->fk_facture_source = $obj->fk_facture_source;
2458 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2459 $this->note = $obj->note_private;
2460 $this->note_private = $obj->note_private;
2461 $this->note_public = $obj->note_public;
2462 $this->user_creation_id = $obj->fk_user_author;
2463 $this->user_validation_id = $obj->fk_user_valid;
2464 $this->user_modification_id = $obj->fk_user_modif;
2465 $this->fk_user_author = $obj->fk_user_author;
2466 $this->fk_user_valid = $obj->fk_user_valid;
2467 $this->fk_user_modif = $obj->fk_user_modif;
2468 $this->model_pdf = $obj->model_pdf;
2469 $this->last_main_doc = $obj->last_main_doc;
2470 $this->demand_reason_id = $obj->fk_input_reason;
2471 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2472 $this->situation_counter = $obj->situation_counter;
2473 $this->situation_final = $obj->situation_final;
2474 $this->retained_warranty = $obj->retained_warranty;
2475 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2476 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2478 $this->payment_reference = $obj->payment_reference;
2479 $this->dispute_status = $obj->dispute_status;
2481 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2484 $this->fk_incoterms = $obj->fk_incoterms;
2485 $this->location_incoterms = $obj->location_incoterms;
2486 $this->label_incoterms = $obj->label_incoterms;
2488 $this->module_source = $obj->module_source;
2489 $this->pos_source = $obj->pos_source;
2490 $this->pos_print_counter = (int) $obj->pos_print_counter;
2491 $this->email_sent_counter = $obj->email_sent_counter;
2494 $this->fk_multicurrency = $obj->fk_multicurrency;
2495 $this->multicurrency_code = $obj->multicurrency_code;
2496 $this->multicurrency_tx = $obj->multicurrency_tx;
2497 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2498 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2499 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2502 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2503 $this->array_options = array();
2505 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2506 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2507 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2510 if ($type !==
'separate') {
2511 $rawval = $obj->$key;
2514 if (in_array($type, array(
'date',
'datetime'))) {
2515 $this->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2516 } elseif ($type ==
'password') {
2517 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2518 $this->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2520 $this->array_options[
'options_' . $key] = $rawval;
2523 $this->array_options[
'options_' . $key] = $rawval;
2529 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2530 if (!empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
2531 if (empty(
$conf->disable_compute)) {
2532 global $objectoffield;
2533 $objectoffield = $this;
2534 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
2540 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2544 if (!$doFetchInOneSqlRequest) {
2551 $this->lines = array();
2555 $this->error = $this->db->error();
2559 $this->db->free($resql);
2563 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2565 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2569 $this->error = $this->db->lasterror();
2583 public function fetch_lines($only_type_product =
'', $loadalsotranslation = 0)
2585 global
$conf, $extrafields;
2588 $this->lines = array();
2590 $extraFieldsCheck =
false;
2591 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2593 if ($doFetchInOneSqlRequest) {
2595 if (!isset($extrafields) || !is_object($extrafields)) {
2596 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2601 if (empty($extrafields->attributes[$this->table_element_line][
'loaded'])) {
2602 $extrafields->fetch_name_optionals_label($this->table_element_line);
2605 $extraFieldsCheck = (
2606 !empty($extrafields->attributes[$this->table_element_line][
'label'])
2607 && is_array($extrafields->attributes[$this->table_element_line][
'label'])
2608 && count($extrafields->attributes[$this->table_element_line][
'label']) > 0
2612 $sql =
'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
2613 $sql .=
' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.subprice_ttc, l.ref_ext,';
2614 $sql .=
' l.situation_percent, l.fk_prev_id,';
2615 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2616 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2617 $sql .=
' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,';
2618 $sql .=
' l.fk_unit, l.extraparams,';
2619 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2620 $sql .=
' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc, p.barcode as product_barcode';
2622 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2623 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2624 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2625 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2628 if ($type !==
'separate') {
2629 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2630 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2632 $sql .=
", ef.".$this->db->sanitize($key);
2638 $sql .=
' FROM '.$this->db->prefix().
'facturedet as l';
2641 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2643 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element_line.
'_extrafields as ef ON l.rowid = ef.fk_object';
2646 $sql .=
' LEFT JOIN '.$this->db->prefix().
'product as p ON l.fk_product = p.rowid';
2647 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2648 if (is_int($only_type_product)) {
2649 $sql .=
" AND p.fk_product_type = ".((int) $only_type_product);
2651 $sql .=
' ORDER BY l.rang, l.rowid';
2653 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2654 $result = $this->db->query($sql);
2656 $num = $this->db->num_rows($result);
2659 $objp = $this->db->fetch_object($result);
2662 $line->id = $objp->rowid;
2663 $line->rowid = $objp->rowid;
2664 $line->fk_facture = $objp->fk_facture;
2665 $line->label = $objp->custom_label;
2666 $line->desc = $objp->description;
2667 $line->description = $objp->description;
2668 $line->product_type = $objp->product_type;
2669 $line->ref = $objp->product_ref;
2670 $line->product_ref = $objp->product_ref;
2671 $line->libelle = $objp->product_label;
2672 $line->product_label = $objp->product_label;
2673 $line->product_barcode = $objp->product_barcode;
2674 $line->product_desc = $objp->product_desc;
2675 $line->fk_product_type = $objp->fk_product_type;
2676 $line->qty = $objp->qty;
2677 $line->subprice = $objp->subprice;
2678 $line->subprice_ttc = $objp->subprice_ttc;
2679 $line->ref_ext = $objp->ref_ext;
2681 $line->vat_src_code = $objp->vat_src_code;
2682 $line->tva_tx = $objp->tva_tx;
2683 $line->localtax1_tx = $objp->localtax1_tx;
2684 $line->localtax2_tx = $objp->localtax2_tx;
2685 $line->localtax1_type = $objp->localtax1_type;
2686 $line->localtax2_type = $objp->localtax2_type;
2687 $line->remise_percent = $objp->remise_percent;
2688 $line->fk_remise_except = $objp->fk_remise_except;
2689 $line->fk_product = $objp->fk_product;
2690 $line->date_start = $this->db->jdate($objp->date_start);
2691 $line->date_end = $this->db->jdate($objp->date_end);
2692 $line->info_bits = $objp->info_bits;
2693 $line->total_ht = $objp->total_ht;
2694 $line->total_tva = $objp->total_tva;
2695 $line->total_localtax1 = $objp->total_localtax1;
2696 $line->total_localtax2 = $objp->total_localtax2;
2697 $line->total_ttc = $objp->total_ttc;
2699 $line->fk_fournprice = $objp->fk_fournprice;
2700 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2701 $line->pa_ht = $marginInfos[0];
2702 $line->marge_tx = (string) $marginInfos[1];
2703 $line->marque_tx = (string) $marginInfos[2];
2704 $line->rang = $objp->rang;
2705 $line->special_code = $objp->special_code;
2706 $line->fk_parent_line = $objp->fk_parent_line;
2707 $line->situation_percent = $objp->situation_percent;
2708 $line->fk_prev_id = $objp->fk_prev_id;
2709 $line->fk_unit = $objp->fk_unit;
2711 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
2713 $line->batch = $objp->batch;
2714 $line->fk_warehouse = $objp->fk_warehouse;
2717 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2720 $line->fk_multicurrency = $objp->fk_multicurrency;
2721 $line->multicurrency_code = $objp->multicurrency_code;
2722 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2723 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2724 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2725 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2727 $line->array_options = array();
2728 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2729 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2730 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2731 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2734 if ($type !==
'separate') {
2735 $rawval = $objp->$key;
2738 if (in_array($type, array(
'date',
'datetime'))) {
2739 $line->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2740 } elseif ($type ==
'password') {
2741 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2742 $line->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2744 $line->array_options[
'options_' . $key] = $rawval;
2747 $line->array_options[
'options_' . $key] = $rawval;
2753 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2754 if (!empty($extrafields->attributes[$this->table_element_line][
'computed'][$key])) {
2755 if (empty(
$conf->disable_compute)) {
2756 global $objectoffield;
2757 $objectoffield = $line;
2758 $line->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element_line][
'computed'][$key], 1, 0,
'2');
2764 if (!$doFetchInOneSqlRequest) {
2766 $line->fetch_optionals();
2770 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2771 $tmpproduct =
new Product($this->db);
2772 $tmpproduct->fetch($objp->fk_product);
2773 $tmpproduct->getMultiLangs();
2775 $line->multilangs = $tmpproduct->multilangs;
2778 $this->lines[$i] = $line;
2782 $this->db->free($result);
2785 $this->error = $this->db->error();
2798 $this->tab_previous_situation_invoice = array();
2799 $this->tab_next_situation_invoice = array();
2801 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2802 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2803 $sql .=
' AND entity = '.((int) $this->entity);
2804 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2805 $sql .=
' ORDER BY situation_counter ASC';
2807 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2808 $result = $this->db->query($sql);
2809 if ($result && $this->db->num_rows($result) > 0) {
2810 while ($objp = $this->db->fetch_object($result)) {
2811 $invoice =
new Facture($this->db);
2812 if ($invoice->fetch($objp->rowid) > 0) {
2813 if ($objp->situation_counter < $this->situation_counter
2814 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2816 $this->tab_previous_situation_invoice[] = $invoice;
2818 $this->tab_next_situation_invoice[] = $invoice;
2839 if (empty($this->
type)) {
2842 if (isset($this->subtype)) {
2843 $this->subtype = (int) $this->subtype;
2845 if (isset($this->
ref)) {
2846 $this->
ref = trim($this->
ref);
2848 if (isset($this->ref_ext)) {
2849 $this->ref_ext = trim($this->ref_ext);
2851 if (!empty($this->ref_customer)) {
2852 $this->ref_customer = trim($this->ref_customer);
2854 if (isset($this->increment)) {
2855 $this->increment = trim($this->increment);
2857 if (isset($this->close_code)) {
2858 $this->close_code = trim($this->close_code);
2860 if (isset($this->close_note)) {
2861 $this->close_note = trim($this->close_note);
2863 if (isset($this->note) || isset($this->note_private)) {
2864 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2866 if (isset($this->note) || isset($this->note_private)) {
2867 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2869 if (isset($this->note_public)) {
2870 $this->note_public = trim($this->note_public);
2872 if (isset($this->model_pdf)) {
2873 $this->model_pdf = trim($this->model_pdf);
2875 if (isset($this->import_key)) {
2876 $this->import_key = trim($this->import_key);
2878 if (isset($this->retained_warranty)) {
2879 $this->retained_warranty = (float) $this->retained_warranty;
2881 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2882 $this->user_creation_id = $this->fk_user_author;
2884 if (!isset($this->user_modification_id) && !empty($user->id)) {
2885 $this->user_modification_id = $user->id;
2887 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2888 $this->user_validation_id = $this->fk_user_valid;
2893 dol_syslog(get_class($this).
"::update ".$this->error, LOG_ERR);
2899 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2900 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2901 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2902 $sql .=
" type=".(isset($this->
type) ? ((int) $this->
type) :
"null").
",";
2903 $sql .=
" subtype=".(isset($this->subtype) ? (int) $this->subtype :
"null").
",";
2904 $sql .=
" ref_client=".(!empty($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2905 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2906 $sql .=
" fk_soc=".(isset($this->socid) ? ((int) $this->socid) :
"null").
",";
2907 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2908 $sql .=
" datef=".(strval($this->
date) !=
'' ?
"'".$this->db->idate($this->
date).
"'" :
'null').
",";
2909 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2910 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2911 $sql .=
" paye=".(isset($this->paye) ? ((int) $this->paye) : 0).
",";
2912 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2913 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2914 $sql .=
" total_tva=".((float) $this->total_tva).
",";
2915 $sql .=
" localtax1=".((float) $this->total_localtax1).
",";
2916 $sql .=
" localtax2=".((float) $this->total_localtax2).
",";
2917 $sql .=
" total_ht=".((float) $this->total_ht).
",";
2918 $sql .=
" total_ttc=".((float) $this->total_ttc).
",";
2919 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2920 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2921 $sql .=
" fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) :
"null").
",";
2922 $sql .=
" fk_user_modif=".(!empty($user->id) ? ((int) $user->id) :
"null").
",";
2923 $sql .=
" fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id :
"null").
",";
2924 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2925 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2926 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2927 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2928 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2929 $sql .=
" note_private = ".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2930 $sql .=
" note_public = ".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2931 $sql .=
" model_pdf = ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2932 $sql .=
" import_key = ".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2933 $sql .=
" module_source = ".(isset($this->module_source) ?
"'".$this->db->escape($this->module_source).
"'" :
"null").
",";
2934 $sql .=
" pos_source = ".(isset($this->pos_source) ?
"'".$this->db->escape($this->pos_source).
"'" :
"null").
",";
2935 $sql .=
" pos_print_counter = ".(int) $this->pos_print_counter.
",";
2936 $sql .=
" situation_cycle_ref = ".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2937 $sql .=
" situation_counter = ".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2938 $sql .=
" situation_final = ".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2939 $sql .=
" retained_warranty = ".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2940 $sql .=
" retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2941 $sql .=
" retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2942 $sql .=
" WHERE rowid = ".((int) $this->
id);
2946 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2947 $resql = $this->db->query($sql);
2950 $this->errors[] =
"Error ".$this->db->lasterror();
2960 if (!$error && !$notrigger) {
2962 $result = $this->call_trigger(
'BILL_MODIFY', $user);
2971 foreach ($this->errors as $errmsg) {
2972 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2973 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2975 $this->db->rollback();
2978 $this->db->commit();
2996 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2997 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
3002 $result = $remise->fetch($idremise);
3005 if ($this->socid > 0 && $remise->fk_soc != $this->socid) {
3006 $this->error = $langs->trans(
"ErrorDiscountNotSameCompany");
3007 $this->db->rollback();
3010 if ($remise->fk_facture) {
3011 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
3012 $this->db->rollback();
3017 $facligne->fk_facture = $this->id;
3018 $facligne->fk_remise_except = $remise->id;
3019 $facligne->desc = $remise->description;
3020 $facligne->vat_src_code = $remise->vat_src_code;
3021 $facligne->tva_tx = $remise->tva_tx;
3022 $facligne->localtax1_tx = $remise->localtax1_tx;
3023 $facligne->localtax1_type = (int) $remise->localtax1_type;
3024 $facligne->localtax2_tx = $remise->localtax2_tx;
3025 $facligne->localtax2_type = (int) $remise->localtax2_type;
3026 $facligne->subprice = -(float) $remise->total_ht;
3027 $facligne->fk_product = 0;
3029 $facligne->remise_percent = 0;
3030 $facligne->rang = -1;
3031 $facligne->info_bits = 2;
3034 $facligne->rang = 1;
3035 $linecount = count($this->lines);
3036 for ($ii = 1; $ii <= $linecount; $ii++) {
3042 if ($remise->fk_facture_source > 0) {
3043 $srcinvoice =
new Facture($this->db);
3044 $srcinvoice->fetch($remise->fk_facture_source);
3045 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
3049 $srclinesofvat = array();
3050 foreach ($srcinvoice->lines as $srcline) {
3052 $srclinesofvat[] = $srcline;
3055 if (count($srclinesofvat) > 0) {
3056 $srcinvoice->lines = $srclinesofvat;
3058 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
3059 $facligne->pa_ht = $arraytmp[
'pa_total'];
3060 if ((
float) $arraytmp[
'pv_total'] != 0 &&
price2num($arraytmp[
'pv_total'],
'MT') !=
price2num(abs((
float) $remise->total_ht),
'MT')) {
3061 $facligne->pa_ht = (float)
price2num($arraytmp[
'pa_total'] * abs((
float) $remise->total_ht / (
float) $arraytmp[
'pv_total']),
'MU');
3065 $facligne->total_ht = -(float) $remise->total_ht;
3066 $facligne->total_tva = -(float) $remise->total_tva;
3067 $facligne->total_ttc = -(float) $remise->total_ttc;
3068 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
3069 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
3072 $facligne->fk_multicurrency = $this->fk_multicurrency;
3073 $facligne->multicurrency_code = $this->multicurrency_code;
3074 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
3075 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
3076 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
3077 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
3079 $lineid = $facligne->insert();
3084 $result = $remise->link_to_invoice($lineid, 0);
3086 $this->error = $remise->error;
3087 $this->db->rollback();
3091 $this->db->commit();
3094 $this->error = $facligne->error;
3095 $this->db->rollback();
3099 $this->error = $facligne->error;
3100 $this->db->rollback();
3104 $this->db->rollback();
3126 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3127 if (empty($ref_client)) {
3128 $sql .=
" SET ref_client = NULL";
3130 $sql .=
" SET ref_client = '".$this->db->escape($ref_client).
"'";
3132 $sql .=
" WHERE rowid = ".((int) $this->
id);
3134 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
3135 $resql = $this->db->query($sql);
3137 $this->errors[] = $this->db->error();
3142 $this->ref_client = $ref_client;
3143 $this->ref_customer = $ref_client;
3146 if (!$notrigger && empty($error)) {
3148 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3156 $this->ref_client = $ref_client;
3157 $this->ref_customer = $ref_client;
3159 $this->db->commit();
3162 foreach ($this->errors as $errmsg) {
3163 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
3164 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
3166 $this->db->rollback();
3186 dol_syslog(__METHOD__.
' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3187 if ($this->
status >= self::STATUS_DRAFT) {
3189 $this->demand_reason_id = $inputReasonId;
3193 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3194 $sql .=
" SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId :
'null');
3195 $sql .=
" WHERE rowid = ".((int) $this->
id);
3198 $res = $this->db->query($sql);
3201 $this->error = $this->db->lasterror();
3202 $this->errors[] = $this->error;
3208 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3217 $this->db->commit();
3219 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3220 $this->db->rollback();
3221 dol_syslog(__METHOD__.
' Error : '.$this->errorsToString(), LOG_ERR);
3242 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3244 global $langs,
$conf;
3245 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3249 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
3259 if ($this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0 && $this->
status != self::STATUS_DRAFT) {
3260 $srcInvoice =
new Facture($this->db);
3261 if ($srcInvoice->fetch($this->fk_facture_source) > 0 && $srcInvoice->type == self::TYPE_DEPOSIT) {
3262 $langs->load(
'bills');
3263 $this->error = $langs->trans(
'CreditNoteOnDepositCantBeDeleted');
3272 if (!$error && !$notrigger) {
3274 $result = $this->call_trigger(
'BILL_DELETE', $user);
3283 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"categorie_invoice";
3284 $sql .=
" WHERE fk_invoice = ".((int) $this->
id);
3286 $result = $this->db->query($sql);
3289 $this->errors[] = $this->db->lasterror();
3298 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
3312 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
3313 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
3314 $sql .=
' AND fk_facture_line IS NULL';
3315 $resql = $this->db->query($sql);
3319 $list_rowid_det = array();
3320 foreach ($this->lines as $key => $invoiceline) {
3321 $list_rowid_det[] = $invoiceline->id;
3325 if (count($list_rowid_det)) {
3326 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3327 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
3328 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
3330 if (!$this->db->query($sql)) {
3331 $this->error = $this->db->error().
" sql=".$sql;
3332 $this->errors[] = $this->error;
3333 $this->db->rollback();
3340 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
3341 $sql .=
' SET fk_invoice = NULL';
3342 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
3344 if (!$this->db->query($sql)) {
3345 $this->error = $this->db->error().
" sql=".$sql;
3346 $this->errors[] = $this->error;
3347 $this->db->rollback();
3351 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
3352 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
3353 $sql .=
' WHERE invoice_id = '.((int) $rowid);
3355 if (!$this->db->query($sql)) {
3356 $this->error = $this->db->error().
" sql=".$sql;
3357 $this->errors[] = $this->error;
3358 $this->db->rollback();
3364 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3365 $langs->load(
"agenda");
3367 $num = count($this->lines);
3368 for ($i = 0; $i < $num; $i++) {
3369 if ($this->lines[$i]->fk_product > 0) {
3371 $mouvP->origin = &$this;
3372 $mouvP->setOrigin($this->element, $this->
id);
3374 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3375 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv(
"InvoiceDeleteDolibarr", $this->ref));
3377 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv(
"InvoiceDeleteDolibarr", $this->ref));
3384 $sql_main_table = MAIN_DB_PREFIX.
'facturedet';
3385 $sql_ef_table = $sql_main_table.
"_extrafields";
3386 $sqlef =
"DELETE FROM ".$sql_ef_table.
" WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table.
" WHERE fk_facture = ".((int) $rowid).
")";
3388 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
3391 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
3393 $resql = $this->db->query($sql);
3401 if ($conf->facture->dir_output && !empty($this->
ref)) {
3402 $dir =
$conf->facture->dir_output.
"/".$ref;
3403 $file =
$conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
3404 if (file_exists($file)) {
3408 $langs->load(
"errors");
3409 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
3410 $this->errors[] = $this->error;
3411 $this->db->rollback();
3415 if (file_exists($dir)) {
3417 $langs->load(
"errors");
3418 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
3419 $this->errors[] = $this->error;
3420 $this->db->rollback();
3426 $this->db->commit();
3429 $this->error = $this->db->lasterror().
" sql=".$sql;
3430 $this->errors[] = $this->error;
3431 $this->db->rollback();
3435 $this->error = $this->db->lasterror().
" sql=".$sql;
3436 $this->errors[] = $this->error;
3437 $this->db->rollback();
3441 $this->db->rollback();
3458 public function set_paid($user, $close_code =
'', $close_note =
'')
3461 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3462 return $this->
setPaid($user, $close_code, $close_note);
3475 public function setPaid($user, $close_code =
'', $close_note =
'')
3479 if ($this->paye != 1 || $this->
status != self::STATUS_CLOSED) {
3484 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3486 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3487 $sql .=
' fk_statut = '.self::STATUS_CLOSED;
3489 $sql .=
', paye = 1';
3492 $sql .=
", close_code = '".$this->db->escape($close_code).
"'";
3495 $sql .=
", close_note = '".$this->db->escape($close_note).
"'";
3497 $sql .=
', fk_user_closing = '.((int) $user->id);
3498 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3499 $sql .=
" WHERE rowid = ".((int) $this->
id);
3501 $resql = $this->db->query($sql);
3504 $result = $this->call_trigger(
'BILL_PAYED', $user);
3511 $this->error = $this->db->lasterror();
3517 $this->db->commit();
3520 $this->db->rollback();
3543 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3561 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3562 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3563 $sql .=
' date_closing=null,';
3564 $sql .=
' fk_user_closing=null';
3565 $sql .=
" WHERE rowid = ".((int) $this->
id);
3567 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3568 $resql = $this->db->query($sql);
3571 $result = $this->call_trigger(
'BILL_UNPAYED', $user);
3578 $this->error = $this->db->error();
3579 dol_print_error($this->db);
3583 $this->db->commit();
3586 $this->db->rollback();
3608 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3609 return $this->
setCanceled($user, $close_code, $close_note);
3622 public function setCanceled($user, $close_code =
'', $close_note =
'')
3624 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3629 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3630 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3632 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3635 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3637 $sql .=
', fk_user_closing = '.((int) $user->id);
3638 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3639 $sql .=
" WHERE rowid = ".((int) $this->
id);
3641 $resql = $this->db->query($sql);
3645 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3646 $sql .=
' SET fk_facture = NULL';
3647 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3649 $resql = $this->db->query($sql);
3652 $result = $this->call_trigger(
'BILL_CANCEL', $user);
3654 $this->db->rollback();
3659 $this->db->commit();
3662 $this->error = $this->db->error().
" sql=".$sql;
3663 $this->db->rollback();
3667 $this->error = $this->db->error().
" sql=".$sql;
3668 $this->db->rollback();
3685 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3688 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3690 $productStatic =
null;
3691 $warehouseStatic =
null;
3692 $productbatch =
null;
3693 if ($batch_rule > 0) {
3694 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3695 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3696 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3697 $productStatic =
new Product($this->db);
3698 $warehouseStatic =
new Entrepot($this->db);
3705 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3712 if ($this->
status != self::STATUS_DRAFT) {
3713 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3716 if (count($this->lines) <= 0) {
3717 $langs->load(
"errors");
3718 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3722 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3723 $this->error =
'Permission denied';
3724 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3727 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3735 if (!$last_of_type[0]) {
3742 $langs->loadLangs(array(
"errors",
"bills"));
3743 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"DatePointOfTax")).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3744 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3749 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3750 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'TVA_INTRA',
'ACCOUNTANCY_CODE_CUSTOMER');
3751 foreach ($array_to_check as $key) {
3752 $keymin = strtolower($key);
3753 if (!property_exists($this->thirdparty, $keymin)) {
3756 $vallabel = $this->thirdparty->$keymin;
3758 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3760 if ($this->thirdparty->isACompany()) {
3762 if (
$mysoc->country_id > 0 && $this->thirdparty->country_id ==
$mysoc->country_id) {
3763 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3765 $langs->load(
"errors");
3766 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3767 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3773 if ($key ==
'EMAIL') {
3776 $langs->load(
"errors");
3777 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3778 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3782 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3784 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3785 $langs->load(
"errors");
3786 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3787 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3791 if ($key ==
'TVA_INTRA') {
3794 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3795 $langs->load(
"errors");
3796 $this->error = $langs->trans(
'ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3797 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3800 } elseif (
getDolGlobalString(
'SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3801 $langs->load(
"errors");
3802 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3803 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3812 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3813 foreach ($array_to_check as $key => $val) {
3814 $keymin = strtolower($key);
3815 $vallabel = $this->$keymin;
3818 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3820 $langs->load(
"errors");
3822 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3827 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3828 $srcCheckInv =
new Facture($this->db);
3829 if ($srcCheckInv->fetch($this->fk_facture_source) > 0 && $srcCheckInv->type == self::TYPE_DEPOSIT) {
3830 $sqlcap =
'SELECT COALESCE(SUM(amount_ttc),0) as avail FROM '.MAIN_DB_PREFIX.
'societe_remise_except WHERE fk_facture_source='.((int) $this->fk_facture_source).
' AND fk_facture IS NULL AND fk_facture_line IS NULL';
3831 $rescap = $this->db->query($sqlcap);
3833 $available_ttc = (float) $this->db->fetch_object($rescap)->avail;
3834 if (
price2num(abs((
float) $this->total_ttc),
'MT') >
price2num($available_ttc,
'MT')) {
3835 $langs->load(
'bills');
3836 $this->error = $langs->trans(
'CreditNoteExceedsDepositCredit',
price($available_ttc));
3846 if ($this->
type == self::TYPE_REPLACEMENT) {
3848 if ($this->fk_facture_source <= 0) {
3849 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3850 $this->db->rollback();
3855 $facreplaced =
new Facture($this->db);
3856 $result = $facreplaced->fetch($this->fk_facture_source);
3858 $this->error = $langs->trans(
"ErrorBadInvoice");
3859 $this->db->rollback();
3864 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3865 if ($idreplacement && $idreplacement != $this->
id) {
3866 $facreplacement =
new Facture($this->db);
3867 $facreplacement->fetch($idreplacement);
3868 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3869 $this->db->rollback();
3875 if ($facreplaced->getVentilExportCompta() > 0) {
3876 $this->error = $langs->trans(
"ErrorInvoiceReplacedAlreadyInAccountancy", $facreplaced->ref);
3877 $this->db->rollback();
3881 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3883 $this->error = $facreplaced->error;
3884 $this->db->rollback();
3890 if ($force_number) {
3891 $num = $force_number;
3892 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3899 $num = (string) $this->
ref;
3905 $this->oldref = $this->ref;
3913 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3914 $sql .=
" SET ref = '".$this->db->escape($num).
"', fk_statut = ".self::STATUS_VALIDATED.
", fk_user_valid = ".($user->id > 0 ? ((int) $user->id) :
"null").
", date_valid = '".$this->db->idate($now).
"'";
3916 $sql .=
", datef='".$this->db->idate($this->
date).
"'";
3917 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3919 $sql .=
" WHERE rowid = ".((int) $this->
id);
3921 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3922 $resql = $this->db->query($sql);
3924 $this->error = $this->db->lasterror();
3931 $result = $this->thirdparty->setAsCustomer();
3935 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3936 $langs->load(
"agenda");
3939 $cpt = count($this->lines);
3940 for ($i = 0; $i < $cpt; $i++) {
3941 if ($this->lines[$i]->fk_product > 0) {
3943 $mouvP->origin = &$this;
3944 $mouvP->setOrigin($this->element, $this->
id);
3947 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3950 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3959 $is_batch_line =
false;
3960 if ($batch_rule > 0) {
3961 $productStatic->fetch($this->lines[$i]->fk_product);
3962 if ($productStatic->hasbatch() && is_object($productbatch)) {
3963 $is_batch_line =
true;
3964 $product_qty_remain = $this->lines[$i]->qty;
3970 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3971 $sortorder =
'ASC,ASC,ASC,ASC';
3974 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 :
null), $sortfield, $sortorder);
3975 if (!is_array($resBatchList)) {
3977 $this->error = $this->db->lasterror();
3981 $batchList = $resBatchList;
3982 if (empty($batchList)) {
3984 $langs->load(
'errors');
3985 $warehouseStatic->fetch($idwarehouse);
3986 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3987 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3990 foreach ($batchList as $batch) {
3991 if ($batch->qty <= 0) {
3996 if ($batch->qty >= $product_qty_remain) {
3997 $product_batch_qty = $product_qty_remain;
4000 $product_batch_qty = $batch->qty;
4002 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
4009 $product_qty_remain -= $product_batch_qty;
4011 if ($product_qty_remain <= 0) {
4016 if (!$error && $product_qty_remain > 0) {
4019 $langs->load(
'errors');
4020 $warehouseStatic->fetch($idwarehouse);
4021 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
4022 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
4025 $batch = $batchList[0];
4026 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
4037 if (!$is_batch_line) {
4038 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv(
"InvoiceValidatedInDolibarr", $num));
4053 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
4054 $invoice_situation =
new Facture($this->db);
4055 $result = $invoice_situation->fetch($this->fk_facture_source);
4056 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
4057 $invoice_situation->situation_final = 0;
4059 $result = $invoice_situation->setFinal($user, 1);
4062 $this->error = $invoice_situation->error;
4063 $this->errors = array_merge($this->errors, $invoice_situation->errors);
4069 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
4070 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
4071 $depositInvoice =
new Facture($this->db);
4072 if ($depositInvoice->fetch($this->fk_facture_source) > 0 && $depositInvoice->type == self::TYPE_DEPOSIT) {
4080 if (!$error && !$notrigger) {
4082 $result = $this->call_trigger(
'BILL_VALIDATE', $user);
4091 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
4093 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filename = CONCAT('".$this->db->escape($this->newref).
"', SUBSTR(filename, ".(strlen($this->
ref) + 1).
")), filepath = 'facture/".$this->db->escape($this->newref).
"'";
4094 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
4095 $resql = $this->db->query($sql);
4098 $this->error = $this->db->lasterror();
4100 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
4101 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
4102 $resql = $this->db->query($sql);
4105 $this->error = $this->db->lasterror();
4112 if (!$resupdatenext) {
4122 $this->date_validation = $now;
4128 include_once DOL_DOCUMENT_ROOT.
'/core/lib/paymentref.lib.php';
4136 $nboflines = count($this->lines);
4137 while (($i < $nboflines) && $final) {
4138 $line = $this->lines[$i];
4139 '@phan-var-force FactureLigne $line';
4141 $final = ($line->situation_percent == 100);
4143 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
4144 $current_progress = (float) $line->situation_percent;
4145 $full_progress = $previousprogress + $current_progress;
4146 $final = ($full_progress == 100);
4152 if ($this->situation_final) {
4154 $this->situation_final = 0;
4158 if (!$this->situation_final) {
4160 $this->situation_final = 1;
4170 if (!$error && preg_match(
'/^[\(]?PROV/i', $this->oldref)) {
4174 $dirsource =
$conf->facture->dir_output.
'/'.$oldref;
4175 $dirdest =
$conf->facture->dir_output.
'/'.$newref;
4176 if (!$error && file_exists($dirsource)) {
4177 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
4179 if (@rename($dirsource, $dirdest)) {
4182 $listoffiles =
dol_dir_list(
$conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
4183 foreach ($listoffiles as $fileentry) {
4184 $dirsource = $fileentry[
'name'];
4185 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
4186 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
4187 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
4188 @rename($dirsource, $dirdest);
4195 $this->db->commit();
4198 $this->db->rollback();
4220 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
4222 if ($amount_ttc <= 0) {
4226 $sql =
'SELECT rowid, amount_ttc, tva_tx, multicurrency_amount_ttc, description, fk_user, fk_soc, discount_type, vat_src_code';
4227 $sql .=
' FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
4228 $sql .=
' WHERE fk_facture_source = '.((int) $depositInvoice->id);
4229 $sql .=
' AND fk_facture IS NULL AND fk_facture_line IS NULL';
4230 $sql .=
' ORDER BY amount_ttc ASC';
4232 $resql = $this->db->query($sql);
4234 $this->error = $this->db->lasterror();
4238 $remaining = $amount_ttc;
4239 while ($remaining > 0 && ($row = $this->db->fetch_object($resql))) {
4240 $row_ttc = (float) $row->amount_ttc;
4241 if ($row_ttc <= $remaining + 0.001) {
4244 $disc->id = (int) $row->rowid;
4245 if ($disc->delete($user,
true) < 0) {
4246 $this->error = $disc->error;
4247 $this->db->free($resql);
4250 $remaining = (float)
price2num($remaining - $row_ttc,
'MT');
4253 $keep_ttc = (float)
price2num($row_ttc - $remaining,
'MT');
4254 $tva_tx = (float) $row->tva_tx;
4255 $mc_ratio = ($row_ttc > 0) ? ((
float) $row->multicurrency_amount_ttc / $row_ttc) : 1;
4258 $disc->id = (int) $row->rowid;
4259 if ($disc->delete($user,
true) < 0) {
4260 $this->error = $disc->error;
4261 $this->db->free($resql);
4266 $d->fk_facture_source = (int) $depositInvoice->id;
4267 $d->description = $row->description;
4268 $d->fk_user = (int) $row->fk_user;
4269 $d->fk_soc = (int) $row->fk_soc;
4270 $d->socid = (int) $row->fk_soc;
4271 $d->discount_type = (int) $row->discount_type;
4272 $d->tva_tx = $tva_tx;
4273 $d->vat_src_code = $row->vat_src_code;
4274 $d->amount_ttc = $keep_ttc;
4275 $d->amount_ht = (float)
price2num($keep_ttc / (1 + $tva_tx / 100),
'MT');
4276 $d->amount_tva = (float)
price2num($keep_ttc - $d->amount_ht);
4277 $d->multicurrency_amount_ttc = (float)
price2num($keep_ttc * $mc_ratio);
4278 $d->multicurrency_amount_ht = (float)
price2num($d->multicurrency_amount_ttc / (1 + $tva_tx / 100),
'MT');
4279 $d->multicurrency_amount_tva = (float)
price2num($d->multicurrency_amount_ttc - $d->multicurrency_amount_ht);
4281 if ($d->create($user) <= 0) {
4282 $this->error = $d->error;
4283 $this->db->free($resql);
4289 $this->db->free($resql);
4292 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
4293 $langs->load(
'bills');
4294 $label = $langs->trans(
'CreditNoteDepositCreditConsumed', (!empty($this->newref) ? $this->newref : $this->ref),
price($amount_ttc));
4295 foreach (array($depositInvoice->id, $this->id) as $facid) {
4297 $actioncomm->type_code =
'AC_OTH_AUTO';
4298 $actioncomm->code =
'AC_OTH_AUTO';
4299 $actioncomm->label = $label;
4300 $actioncomm->socid = $this->socid;
4301 $actioncomm->datep =
dol_now();
4302 $actioncomm->datef = $actioncomm->datep;
4303 $actioncomm->percentage = -1;
4304 $actioncomm->authorid = $user->id;
4305 $actioncomm->userownerid = $user->id;
4306 $actioncomm->elementtype =
'invoice';
4307 $actioncomm->elementid = $facid;
4308 $actioncomm->create($user);
4322 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4323 $is_last = $next_invoice->is_last_in_cycle();
4325 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4326 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4330 foreach ($next_invoice->lines as $line) {
4331 '@phan-var-force FactureLigne $line';
4332 $result = $next_invoice->updateline(
4337 $line->remise_percent,
4341 $line->localtax1_tx,
4342 $line->localtax2_tx,
4345 $line->product_type,
4346 $line->fk_parent_line,
4348 $line->fk_fournprice,
4351 $line->special_code,
4352 $line->array_options,
4353 $line->situation_percent,
4358 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4383 if ($this->
status == self::STATUS_DRAFT) {
4384 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
4391 if ($this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
4392 $sourceInvoice =
new Facture($this->db);
4393 if ($sourceInvoice->fetch($this->fk_facture_source) > 0 && $sourceInvoice->type == self::TYPE_DEPOSIT) {
4394 $langs->load(
'bills');
4395 $this->error = $langs->trans(
'CreditNoteOnDepositCantBeSetToDraft');
4402 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4403 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
4404 $sql .=
" WHERE rowid = ".((int) $this->
id);
4406 $result = $this->db->query($sql);
4409 $this->oldcopy = clone $this;
4414 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
4415 $langs->load(
"agenda");
4417 $num = count($this->lines);
4418 for ($i = 0; $i < $num; $i++) {
4419 if ($this->lines[$i]->fk_product > 0) {
4421 $mouvP->origin = &$this;
4422 $mouvP->setOrigin($this->element, $this->
id);
4424 if ($this->
type == self::TYPE_CREDIT_NOTE) {
4425 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv(
"InvoiceBackToDraftInDolibarr", $this->ref));
4427 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv(
"InvoiceBackToDraftInDolibarr", $this->ref));
4432 dol_syslog(__METHOD__.
" stock movement failed for line ".$i.
": ".$mouvP->error, LOG_ERR);
4439 $old_statut = $this->status;
4444 $result = $this->call_trigger(
'BILL_UNVALIDATE', $user);
4447 $this->statut = $old_statut;
4448 $this->
status = $old_statut;
4452 $this->db->rollback();
4457 $this->db->commit();
4460 $this->db->rollback();
4464 $this->error = $this->db->error();
4465 $this->db->rollback();
4519 $remise_percent = 0,
4522 $fk_code_ventilation = 0,
4524 $fk_remise_except = 0,
4525 $price_base_type =
'HT',
4532 $fk_parent_line = 0,
4533 $fk_fournprice =
null,
4536 $array_options = array(),
4537 $situation_percent = 100,
4542 $noupdateafterinsertline = 0
4546 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4552 dol_syslog(get_class($this).
"::addline id=$this->id, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, fk_code_ventilation=$fk_code_ventilation, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, type=$type, fk_unit=$fk_unit, desc=".
dol_trunc($desc, 25), LOG_DEBUG);
4554 if ($this->
status == self::STATUS_DRAFT) {
4555 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4558 if (empty($remise_percent)) {
4559 $remise_percent = 0;
4564 if (empty($info_bits)) {
4570 if (empty($fk_code_ventilation)) {
4571 $fk_code_ventilation = 0;
4573 if (empty($txtva)) {
4576 if (empty($txlocaltax1)) {
4579 if (empty($txlocaltax2)) {
4582 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4583 $fk_parent_line = 0;
4585 if (empty($fk_prev_id)) {
4586 $fk_prev_id =
'null';
4589 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4592 $situation_percent = 0;
4594 $situation_percent = 100;
4598 if (empty($ref_ext)) {
4602 $remise_percent = (float)
price2num($remise_percent);
4606 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4609 if (strpos((
string) $txtva,
'*') !==
false) {
4612 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4615 $txlocaltax1 = (float)
price2num($txlocaltax1);
4616 $txlocaltax2 = (float)
price2num($txlocaltax2);
4618 if ($price_base_type ==
'HT') {
4630 $langs->load(
"errors");
4631 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4637 $product_type = $type;
4638 if (!empty($fk_product) && $fk_product > 0) {
4639 $product =
new Product($this->db);
4640 $result = $product->fetch($fk_product);
4641 $product_type = $product->type;
4643 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4645 $productChildrenNb = 0;
4647 $productChildrenNb = $product->hasFatherOrChild(1);
4649 if ($productChildrenNb > 0) {
4651 $product_stock =
null;
4652 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4653 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4654 if ($product_stock ===
null) {
4655 $product_stock = $componentStockWarehouse->real;
4657 $product_stock = min($product_stock, $componentStockWarehouse->real);
4660 if ($product_stock ===
null) {
4664 $product_stock = $product->stock_reel;
4667 if ($product_stock < $qty) {
4668 $langs->load(
"errors");
4669 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4670 $this->db->rollback();
4676 $tmpproduct =
new Product($this->db);
4677 $result = $tmpproduct->fetch($fk_product);
4679 if ($newqty != $qty) {
4681 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4691 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4692 $vat_src_code = $reg[1];
4693 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4700 $tabprice =
calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type,
$mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise, $this->multicurrency_code);
4702 $total_ht = $tabprice[0];
4703 $total_tva = $tabprice[1];
4704 $total_ttc = $tabprice[2];
4705 $total_localtax1 = $tabprice[9];
4706 $total_localtax2 = $tabprice[10];
4707 $pu_ht = $tabprice[3];
4710 $multicurrency_total_ht = $tabprice[16];
4711 $multicurrency_total_tva = $tabprice[17];
4712 $multicurrency_total_ttc = $tabprice[18];
4713 $pu_ht_devise = $tabprice[19];
4717 if (empty($ranktouse) || $ranktouse == -1) {
4718 $rangmax = $this->
line_max($fk_parent_line);
4719 $ranktouse = $rangmax + 1;
4724 $apply_abs_price_on_credit_note =
false;
4726 $apply_abs_price_on_credit_note =
true;
4732 $this->line->context = $this->context;
4734 $this->line->fk_facture = $this->id;
4735 $this->line->label = $label;
4736 $this->line->desc = $desc;
4737 $this->line->ref_ext = $ref_ext;
4739 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : (float) $qty);
4740 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4742 $this->line->subprice_ttc = ($price_base_type ===
'TTC') ? ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ttc) : (float) $pu_ttc) : 0;
4744 $this->line->vat_src_code = $vat_src_code;
4745 $this->line->tva_tx = $txtva;
4746 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4747 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4748 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4749 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4751 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4752 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4753 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4754 $this->line->total_localtax1 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax1) : (float) $total_localtax1);
4755 $this->line->total_localtax2 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax2) : (float) $total_localtax2);
4757 $this->line->fk_product = $fk_product;
4758 $this->line->product_type = $product_type;
4759 $this->line->remise_percent = $remise_percent;
4761 $this->line->date_end = $date_end;
4762 $this->line->fk_code_ventilation = $fk_code_ventilation;
4763 $this->line->rang = $ranktouse;
4764 $this->line->info_bits = $info_bits;
4765 $this->line->fk_remise_except = $fk_remise_except;
4767 $this->line->special_code = $special_code;
4768 $this->line->fk_parent_line = $fk_parent_line;
4770 $this->line->origin = $origin;
4771 $this->line->origin_id = $origin_id;
4773 $this->line->situation_percent = $situation_percent;
4774 $this->line->fk_prev_id = $fk_prev_id;
4775 $this->line->fk_unit = $fk_unit;
4778 $this->line->fk_fournprice = $fk_fournprice;
4779 $this->line->pa_ht = $pa_ht;
4782 $this->line->fk_multicurrency = $this->fk_multicurrency;
4783 $this->line->multicurrency_code = $this->multicurrency_code;
4784 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4786 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4787 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4788 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4790 if (is_array($array_options) && count($array_options) > 0) {
4791 $this->line->array_options = $array_options;
4794 $result = $this->line->insert();
4797 if (empty($noupdateafterinsertline)) {
4801 if (!isset($this->context[
'createfromclone'])) {
4802 if (!empty($fk_parent_line)) {
4805 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4807 $linecount = count($this->lines);
4808 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4813 $this->lines[] = $this->line;
4816 foreach ($this->lines as $tmpline) {
4817 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
4818 $this->line->extraparams = $tmpline->extraparams;
4819 $this->line->setExtraParameters();
4825 $this->db->commit();
4826 return $this->line->id;
4828 $this->error = $this->db->lasterror();
4829 $this->db->rollback();
4833 $this->error = $this->line->error;
4834 $this->errors = $this->line->errors;
4835 $this->db->rollback();
4839 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4840 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4876 public function updateline($rowid, $desc, $pu, $qty, $remise_percent,
$date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type =
'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice =
null, $pa_ht = 0, $label =
'', $special_code = 0, $array_options = array(), $situation_percent = 100, $fk_unit =
null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext =
'', $rang = 0)
4881 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4887 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4890 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4894 dol_syslog(get_class($this).
"::updateline rowid=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, type=$type, fk_parent_line=$fk_parent_line pa_ht=$pa_ht, special_code=$special_code, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG);
4896 if ($this->
status == self::STATUS_DRAFT) {
4899 if (!$this->error) {
4900 $this->error = $langs->trans(
'invoiceLineProgressError');
4907 $langs->load(
"errors");
4908 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4918 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4919 $fk_parent_line = 0;
4921 if (empty($special_code) || $special_code == 3) {
4924 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
4927 $situation_percent = 0;
4929 $situation_percent = 100;
4932 if (empty($ref_ext)) {
4936 $remise_percent = (float)
price2num($remise_percent);
4940 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4943 if (strpos((
string) $txtva,
'*') !==
false) {
4946 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4949 $txlocaltax1 = (float)
price2num($txlocaltax1);
4950 $txlocaltax2 = (float)
price2num($txlocaltax2);
4966 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4967 $vat_src_code = $reg[1];
4968 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4975 if ($tmpline->fetch($rowid) > 0) {
4977 if ($newqty != $qty) {
4979 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4984 $tabprice =
calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type,
$mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise, $this->multicurrency_code);
4986 $total_ht = $tabprice[0];
4987 $total_tva = $tabprice[1];
4988 $total_ttc = $tabprice[2];
4989 $total_localtax1 = $tabprice[9];
4990 $total_localtax2 = $tabprice[10];
4991 $pu_ht = $tabprice[3];
4992 $pu_tva = $tabprice[4];
4993 $pu_ttc = $tabprice[5];
4996 $multicurrency_total_ht = $tabprice[16];
4997 $multicurrency_total_tva = $tabprice[17];
4998 $multicurrency_total_ttc = $tabprice[18];
4999 $pu_ht_devise = $tabprice[19];
5004 if ($remise_percent > 0) {
5005 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
5006 $price = ((float) $pu - $remise);
5012 $line->fetch($rowid);
5013 $line->fetch_optionals();
5015 if (!empty($line->fk_product)) {
5016 $product =
new Product($this->db);
5017 $result = $product->fetch($line->fk_product);
5018 $product_type = $product->type;
5020 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
5022 $productChildrenNb = 0;
5024 $productChildrenNb = $product->hasFatherOrChild(1);
5026 if ($productChildrenNb > 0) {
5028 $product_stock =
null;
5029 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
5030 foreach ($product->stock_warehouse as $componentStockWarehouse) {
5031 if ($product_stock ===
null) {
5032 $product_stock = $componentStockWarehouse->real;
5034 $product_stock = min($product_stock, $componentStockWarehouse->real);
5037 if ($product_stock ===
null) {
5041 $product_stock = $product->stock_reel;
5044 if ($product_stock < $qty) {
5045 $langs->load(
"errors");
5046 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', (
string) $product->ref);
5047 $this->db->rollback();
5053 $staticline = clone $line;
5055 $line->oldline = $staticline;
5056 $this->line = $line;
5057 $this->line->context = $this->context;
5058 $this->line->rang = $rang;
5061 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
5062 $rangmax = $this->
line_max($fk_parent_line);
5063 $this->line->rang = $rangmax + 1;
5065 $apply_abs_price_on_credit_note =
false;
5067 $apply_abs_price_on_credit_note =
true;
5072 $this->line->id = $rowid;
5073 $this->line->rowid = $rowid;
5074 $this->line->label = $label;
5075 $this->line->desc = $desc;
5076 $this->line->ref_ext = $ref_ext;
5077 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
5079 $this->line->vat_src_code = $vat_src_code;
5080 $this->line->tva_tx = $txtva;
5081 $this->line->localtax1_tx = $txlocaltax1;
5082 $this->line->localtax2_tx = $txlocaltax2;
5083 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
5084 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
5086 $this->line->remise_percent = $remise_percent;
5087 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
5089 $this->line->subprice_ttc = ($price_base_type ===
'TTC') ? ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ttc) : (float) $pu_ttc) : 0;
5091 $this->line->date_end = $date_end;
5092 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
5093 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
5094 $this->line->total_localtax1 = (float) $total_localtax1;
5095 $this->line->total_localtax2 = (float) $total_localtax2;
5096 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
5097 $this->line->info_bits = $info_bits;
5098 $this->line->special_code = $special_code;
5099 $this->line->product_type = $type;
5100 $this->line->fk_parent_line = $fk_parent_line;
5101 $this->line->skip_update_total = $skip_update_total;
5102 $this->line->situation_percent = $situation_percent;
5103 $this->line->fk_unit = $fk_unit;
5105 $this->line->fk_fournprice = $fk_fournprice;
5106 $this->line->pa_ht = $pa_ht;
5109 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
5110 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
5111 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
5112 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
5114 if (is_array($array_options) && count($array_options) > 0) {
5116 foreach ($array_options as $key => $value) {
5117 $this->line->array_options[$key] = $array_options[$key];
5121 $result = $this->line->update($user, $notrigger);
5124 if (!empty($fk_parent_line)) {
5130 $this->db->commit();
5133 $this->error = $this->line->error;
5134 $this->db->rollback();
5138 $this->error =
"Invoice statut makes operation forbidden";
5152 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
5153 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
5154 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
5156 $result = $this->db->query($sql);
5158 $this->error = $this->db->error();
5162 $obj = $this->db->fetch_object($result);
5164 if ($obj ===
null) {
5167 return ($situation_percent < $obj->situation_percent);
5186 if (($line->info_bits & 2) == 2) {
5190 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
5193 if ($percent > 100) {
5197 $line->situation_percent = $percent;
5198 $tabprice =
calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0,
'HT', 0, $line->product_type,
$mysoc, array(), $percent);
5200 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
5201 $current_progress = $percent - $previous_progress;
5202 $line->situation_percent = $current_progress;
5203 $tabprice =
calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0,
'HT', 0, $line->product_type,
$mysoc, array(), $current_progress);
5205 $line->total_ht = (float) $tabprice[0];
5206 $line->total_tva = (float) $tabprice[1];
5207 $line->total_ttc = (float) $tabprice[2];
5208 $line->total_localtax1 = (float) $tabprice[9];
5209 $line->total_localtax2 = (float) $tabprice[10];
5210 $line->multicurrency_total_ht = (float) $tabprice[16];
5211 $line->multicurrency_total_tva = (float) $tabprice[17];
5212 $line->multicurrency_total_ttc = (float) $tabprice[18];
5213 $line->update($user);
5216 if ($update_price) {
5232 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
5234 if ($this->
status != self::STATUS_DRAFT) {
5235 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
5241 $line->context = $this->context;
5244 $result = $line->fetch($rowid);
5245 if (!($result > 0)) {
5246 dol_print_error($this->db, $line->error, $line->errors);
5253 if ($id > 0 && (
int) $line->fk_facture !== (
int) $id) {
5254 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
5261 $staticline = clone $line;
5262 $line->oldline = $staticline;
5264 if ($line->delete($user) > 0) {
5268 $this->db->commit();
5271 $this->db->rollback();
5272 $this->error = $this->db->lasterror();
5276 $this->db->rollback();
5277 $this->error = $line->error;
5296 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
5298 return $this->
setDiscount($user, $remise, $notrigger);
5312 if (empty($remise)) {
5316 if ($user->hasRight(
'facture',
'creer')) {
5317 $remise = (float)
price2num($remise, 2);
5323 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
5324 $sql .=
" SET remise_percent = ".((float) $remise);
5325 $sql .=
" WHERE rowid = ".((int) $this->
id);
5326 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
5329 $resql = $this->db->query($sql);
5331 $this->errors[] = $this->db->error();
5335 if (!$notrigger && empty($error)) {
5337 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5345 $this->remise_percent = $remise;
5348 $this->db->commit();
5351 foreach ($this->errors as $errmsg) {
5352 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5353 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5355 $this->db->rollback();
5376 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
5377 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5390 global
$conf, $langs;
5392 if ($this->module_source ==
'takepos') {
5393 $langs->load(
'cashdesk');
5395 $moduleName =
'takepos';
5396 $moduleSourceName =
'Takepos';
5397 $addonConstName =
'TAKEPOS_REF_ADDON';
5401 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
5406 $langs->load(
'bills');
5408 $moduleName =
'facture';
5409 $moduleSourceName =
'Invoice';
5410 $addonConstName =
'FACTURE_ADDON';
5414 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5416 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5418 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
5424 if (!empty($addon)) {
5425 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
5429 $file = $addon.
'.php';
5430 $classname = $addon;
5434 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
5435 foreach ($dirmodels as $reldir) {
5436 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
5439 if (is_file($dir.$file) && is_readable($dir.$file)) {
5440 $mybool = ((bool) include_once $dir.$file) || $mybool;
5446 $file = $addon.
'/'.$addon.
'.modules.php';
5447 $classname =
'mod_'.$moduleName.
'_'.$addon;
5448 $classname = preg_replace(
'/\-.*$/',
'', $classname);
5450 foreach (
$conf->file->dol_document_root as $dirroot) {
5451 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
5454 if (is_file($dir.$file) && is_readable($dir.$file)) {
5455 $mybool = (include_once $dir.$file) || $mybool;
5461 dol_print_error(
null,
'Failed to include file '.$file);
5465 $obj =
new $classname();
5466 '@phan-var-force ModeleNumRefFactures $obj';
5468 $numref = $obj->getNextValue($soc, $this, $mode);
5475 if ($mode !=
'last' && !$numref) {
5476 $this->error = $obj->error;
5482 $langs->load(
'errors');
5483 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5496 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5497 $sql .=
' date_closing as dateclosing,';
5498 $sql .=
' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5499 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
5500 $sql .=
' WHERE c.rowid = '.((int) $id);
5502 $result = $this->db->query($sql);
5504 if ($this->db->num_rows($result)) {
5505 $obj = $this->db->fetch_object($result);
5507 $this->
id = $obj->rowid;
5508 $this->user_creation_id = $obj->fk_user_author;
5509 $this->user_modification_id = $obj->fk_user_modif;
5510 $this->user_validation_id = $obj->fk_user_valid;
5511 $this->user_closing_id = $obj->fk_user_closing;
5513 $this->date_creation = $this->db->jdate($obj->datec);
5514 $this->date_modification = $this->db->jdate($obj->datem);
5515 $this->date_validation = $this->db->jdate($obj->datev);
5516 $this->date_closing = $this->db->jdate($obj->dateclosing);
5518 $this->db->free($result);
5520 dol_print_error($this->db);
5539 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
5546 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
5547 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
5548 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
5549 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5550 $sql .=
" AND f.fk_soc = s.rowid";
5552 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
5554 if (is_object($excluser)) {
5555 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
5559 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5560 $search_sale = $user->id;
5563 if ($search_sale && $search_sale !=
'-1') {
5564 if ($search_sale == -2) {
5565 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5566 } elseif ($search_sale > 0) {
5567 $sql .=
" AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = ".((int) $search_sale).
")";
5572 $sql .=
" AND f.fk_soc = ".((int) $socid);
5574 $sql .= $this->db->order($sortfield, $sortorder);
5575 $sql .= $this->db->plimit($limit, $offset);
5577 $result = $this->db->query($sql);
5579 $numc = $this->db->num_rows($result);
5582 while ($i < $numc) {
5583 $obj = $this->db->fetch_object($result);
5585 if ($shortlist == 1) {
5586 $ga[$obj->fid] = $obj->ref;
5587 } elseif ($shortlist == 2) {
5588 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
5590 $ga[$i][
'id'] = $obj->fid;
5591 $ga[$i][
'ref'] = $obj->ref;
5592 $ga[$i][
'name'] = $obj->name;
5599 dol_print_error($this->db);
5621 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5622 $sql .=
" ff.rowid as rowidnext";
5624 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5625 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5626 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
5627 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
5628 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5629 $sql .=
" AND f.paye = 0";
5630 $sql .=
" AND pf.fk_paiement IS NULL";
5631 $sql .=
" AND ff.fk_statut IS NULL";
5632 $sql .=
" AND NOT EXISTS (SELECT ab.rowid FROM ".MAIN_DB_PREFIX.
"accounting_bookkeeping as ab WHERE ab.doc_type = 'customer_invoice' AND ab.fk_doc = f.rowid)";
5634 $sql .=
" AND f.fk_soc = ".((int) $socid);
5637 $sql .=
" ORDER BY f.ref";
5639 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
5640 $resql = $this->db->query($sql);
5642 while ($obj = $this->db->fetch_object($resql)) {
5643 $return[$obj->rowid] = array(
5644 'id' => $obj->rowid,
5646 'status' => $obj->status,
5647 'paid' => $obj->paid,
5654 $this->error = $this->db->error();
5677 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement, f.multicurrency_code";
5678 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5679 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5680 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
5681 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5682 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5686 $sql .=
" AND ff.type IS NULL";
5687 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
5691 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
5692 $sql .=
'(SELECT MAX(fs.rowid)';
5693 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
5694 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
5695 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
5696 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5698 $sql .=
" AND fs.fk_soc = ".((int) $socid);
5700 $sql .=
" GROUP BY fs.situation_cycle_ref)";
5703 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
5707 $sql .=
" AND f.fk_soc = ".((int) $socid);
5710 if (
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5711 $sql .=
" ORDER BY CASE WHEN f.rowid = ".((int)
GETPOST(
'fac_avoir')).
" THEN 0 ELSE 1 END, f.ref";
5713 $sql .= $this->db->plimit(
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5715 $sql .=
" ORDER BY f.ref";
5718 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
5719 $resql = $this->db->query($sql);
5721 while ($obj = $this->db->fetch_object($resql)) {
5723 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5726 if ($obj->fk_statut == self::STATUS_CLOSED) {
5731 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5732 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot,
'multicurrency_code' => $obj->multicurrency_code);
5738 $this->error = $this->db->error();
5754 global
$conf, $langs;
5756 $sanitizedclause =
" WHERE";
5765 $sql =
"SELECT COUNT(f.rowid) as nb, SUM(f.total_ht) as total,";
5766 $sql .=
" SUM(CASE WHEN f.date_lim_reglement IS NULL OR f.date_lim_reglement < '".$this->db->idate($now - $warningdelay).
"' THEN 1 ELSE 0 END) as nblate";
5767 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5768 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5769 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5770 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5771 $sanitizedclause =
" AND";
5773 $sql .= $sanitizedclause.
" f.paye=0";
5774 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5775 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5777 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5780 $resql = $this->db->query($sql);
5782 $langs->load(
"bills");
5784 $response->warning_delay = $warningdelay / 60 / 60 / 24;
5785 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5786 $response->labelShort = $langs->trans(
"Unpaid");
5787 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5788 $response->img = img_object(
'',
"bill");
5790 $obj = $this->db->fetch_object($resql);
5792 $response->nbtodo = (int) $obj->nb;
5793 $response->total = (float) $obj->total;
5794 $response->nbtodolate = (int) $obj->nblate;
5795 if ($response->nbtodolate > 0) {
5796 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5800 $this->db->free($resql);
5803 dol_print_error($this->db);
5804 $this->error = $this->db->error();
5843 global
$conf, $langs, $user;
5847 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5852 $sql =
"SELECT rowid";
5853 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5854 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5855 $sql .= $this->db->plimit(100);
5857 $resql = $this->db->query($sql);
5859 $num_prods = $this->db->num_rows($resql);
5861 while ($i < $num_prods) {
5863 $row = $this->db->fetch_row($resql);
5864 $prodids[$i] = $row[0];
5868 if (empty($num_prods)) {
5870 $prodids[$num_prods] = 1;
5875 $this->entity =
$conf->entity;
5876 $this->
ref =
'SPECIMEN';
5877 $this->specimen = 1;
5879 $this->
date = $nownotime;
5880 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5881 $this->cond_reglement_id = 1;
5882 $this->cond_reglement_code =
'RECEP';
5884 $this->mode_reglement_id = 0;
5885 $this->mode_reglement_code =
'';
5887 $this->note_public =
'This is a comment (public)';
5888 $this->note_private =
'This is a comment (private)';
5890 $this->user_creation_id = $user->id;
5892 $this->multicurrency_tx = 1;
5893 $this->multicurrency_code =
$conf->currency;
5895 $this->fk_incoterms = 0;
5896 $this->location_incoterms =
'';
5898 $this->pos_print_counter = 0;
5899 $this->email_sent_counter = 0;
5903 if (empty($option) || $option !=
'nolines') {
5907 while ($xnbp < $nbp) {
5909 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5911 $line->subprice = 100;
5912 $line->tva_tx = 19.6;
5913 $line->localtax1_tx = 0;
5914 $line->localtax2_tx = 0;
5915 $line->remise_percent = 0;
5916 if ($xnbp == 1 && $option !=
'takepos' && $option !=
'nonegativeup') {
5917 $prodid = mt_rand(1, $num_prods);
5918 if (isset($prodids[$prodid])) {
5919 $line->fk_product = $prodids[$prodid];
5922 $line->total_ht = -100;
5923 $line->total_ttc = -119.6;
5924 $line->total_tva = -19.6;
5925 $line->multicurrency_total_ht = -200;
5926 $line->multicurrency_total_ttc = -239.2;
5927 $line->multicurrency_total_tva = -39.2;
5928 } elseif ($xnbp == 2 && $option !=
'takepos' && $option !=
'nonegativeup') {
5929 $line->subprice = -100;
5930 $line->total_ht = -100;
5931 $line->total_ttc = -119.6;
5932 $line->total_tva = -19.6;
5933 $line->remise_percent = 0;
5934 $line->multicurrency_total_ht = -200;
5935 $line->multicurrency_total_ttc = -239.2;
5936 $line->multicurrency_total_tva = -39.2;
5937 } elseif ($xnbp == 3) {
5938 $prodid = mt_rand(1, $num_prods);
5939 if (isset($prodids[$prodid])) {
5940 $line->fk_product = $prodids[$prodid];
5942 $line->total_ht = 50;
5943 $line->total_ttc = 59.8;
5944 $line->total_tva = 9.8;
5945 $line->multicurrency_total_ht = 100;
5946 $line->multicurrency_total_ttc = 119.6;
5947 $line->multicurrency_total_tva = 19.6;
5948 $line->remise_percent = 50;
5950 $prodid = mt_rand(1, $num_prods);
5951 if (isset($prodids[$prodid])) {
5952 $line->fk_product = $prodids[$prodid];
5954 $line->total_ht = 100;
5955 $line->total_ttc = 119.6;
5956 $line->total_tva = 19.6;
5957 $line->multicurrency_total_ht = 200;
5958 $line->multicurrency_total_ttc = 239.2;
5959 $line->multicurrency_total_tva = 39.2;
5960 $line->remise_percent = 0;
5963 $this->lines[$xnbp] = $line;
5966 $this->total_ht += $line->total_ht;
5967 $this->total_tva += $line->total_tva;
5968 $this->total_ttc += $line->total_ttc;
5970 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5971 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5972 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5976 $this->revenuestamp = 0;
5979 if ($option !=
'takepos') {
5981 $line->desc = $langs->trans(
"Description").
" (offered line)";
5983 $line->subprice = 100;
5984 $line->tva_tx = 19.6;
5985 $line->localtax1_tx = 0;
5986 $line->localtax2_tx = 0;
5987 $line->remise_percent = 100;
5988 $line->total_ht = 0;
5989 $line->total_ttc = 0;
5990 $line->total_tva = 0;
5991 $line->multicurrency_total_ht = 0;
5992 $line->multicurrency_total_ttc = 0;
5993 $line->multicurrency_total_tva = 0;
5994 $prodid = mt_rand(1, $num_prods);
5995 if (isset($prodids[$prodid])) {
5996 $line->fk_product = $prodids[$prodid];
5999 $this->lines[$xnbp] = $line;
6016 $this->nb = array();
6018 $sanitizedclause =
"WHERE";
6020 $sql =
"SELECT count(f.rowid) as nb";
6021 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
6022 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
6023 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
6024 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
6025 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
6026 $sanitizedclause =
"AND";
6028 $sql .=
" ".$sanitizedclause.
" f.entity IN (".
getEntity(
'invoice').
")";
6030 $resql = $this->db->query($sql);
6032 while ($obj = $this->db->fetch_object($resql)) {
6033 $this->nb[
"invoices"] = $obj->nb;
6035 $this->db->free($resql);
6038 dol_print_error($this->db);
6039 $this->error = $this->db->error();
6051 $context = parent::getObjectLinesDisplayContext();
6052 $context[
'inputalsopricewithtax'] = 1;
6078 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
6080 $outputlangs->loadLangs(array(
"bills",
"products"));
6084 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
6086 if (!empty($this->model_pdf)) {
6087 $modele = $this->model_pdf;
6095 $modelpath =
"core/modules/facture/doc/";
6097 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
6107 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
6108 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
6109 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
6111 $resql = $this->db->query($sql);
6113 if ($this->db->num_rows($resql) > 0) {
6115 $obj = $this->db->fetch_object($resql);
6117 $ref = (int) $obj->maxsituationref;
6123 $this->db->free($resql);
6126 $this->error = $this->db->lasterror();
6127 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
6141 return ($this->situation_counter == 1);
6155 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
6156 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
6157 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
6158 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
6159 $resql = $this->db->query($sql);
6161 if ($resql && $this->db->num_rows($resql) > 0) {
6162 while ($row = $this->db->fetch_object($resql)) {
6164 $situation =
new Facture($this->db);
6165 $situation->fetch($id);
6166 $res[] = $situation;
6169 $this->error = $this->db->error();
6170 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
6190 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
6193 $resql = $this->db->query($sql);
6195 $this->errors[] = $this->db->error();
6199 if (!$notrigger && empty($error)) {
6201 $result = $this->call_trigger(
'BILL_MODIFY', $user);
6209 $this->db->commit();
6212 foreach ($this->errors as $errmsg) {
6213 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
6214 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
6216 $this->db->rollback();
6232 if (!empty($this->situation_cycle_ref)) {
6234 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
6235 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
6236 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
6237 $resql = $this->db->query($sql);
6239 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
6240 $last = $res[
'max(situation_counter)'];
6241 return ($last == $this->situation_counter);
6243 $this->error = $this->db->lasterror();
6244 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6302 $hasDelay = $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'));
6303 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
6305 $totalpaid = (float) $totalpaid;
6307 if ($totalpaid >= 0 && $retainedWarrantyAmount >= 0) {
6308 if (($totalpaid < $this->total_ttc - $retainedWarrantyAmount) && $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'))) {
6310 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now -
getWarningDelay(
'invoice',
'client'))) {
6328 return $this->situation_cycle_ref;
6341 $displayWarranty =
false;
6342 if (!empty($this->retained_warranty)) {
6343 $displayWarranty =
true;
6347 $displayWarranty =
false;
6348 if (!empty($this->situation_final)) {
6349 $displayWarranty =
true;
6352 $displayWarranty =
true;
6354 foreach ($this->lines as $i => $line) {
6355 if ($line->product_type < 2 && $line->situation_percent < 100) {
6356 $displayWarranty =
false;
6364 return $displayWarranty;
6375 if (empty($this->retained_warranty)) {
6379 $retainedWarrantyAmount = 0;
6383 $displayWarranty =
true;
6385 if (!empty($this->lines)) {
6386 foreach ($this->lines as $i => $line) {
6387 if ($line->product_type < 2 && $line->situation_percent < 100) {
6388 $displayWarranty =
false;
6394 if ($displayWarranty && !empty($this->situation_final)) {
6396 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6400 foreach ($TPreviousIncoice as &$fac) {
6401 $total2BillWT += $fac->total_ttc;
6403 $total2BillWT += $this->total_ttc;
6406 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6412 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6415 if (is_numeric($rounding) && $rounding < 0) {
6419 if (is_numeric($rounding) && $rounding > 0) {
6420 return round($retainedWarrantyAmount, $rounding);
6423 return (
float)
price2num($retainedWarrantyAmount, $rounding);
6434 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
6436 if ($this->
status >= 0) {
6437 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6438 $sql .=
" SET retained_warranty = ".((float) $value);
6439 $sql .=
' WHERE rowid='.((int) $this->
id);
6441 if ($this->db->query($sql)) {
6442 $this->retained_warranty = (float) $value;
6445 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
6446 $this->error = $this->db->error();
6450 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
6451 $this->error =
'Status of the object is incompatible '.$this->status;
6466 if (!$timestamp && $dateYmd) {
6467 $timestamp = $this->db->jdate($dateYmd);
6471 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
6472 if ($this->
status >= 0) {
6473 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6474 $sql .=
" SET retained_warranty_date_limit = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
6475 $sql .=
' WHERE rowid = '.((int) $this->
id);
6477 if ($this->db->query($sql)) {
6478 $this->retained_warranty_date_limit = $timestamp;
6481 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
6482 $this->error = $this->db->error();
6486 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6487 $this->error =
'Status of the object is incompatible '.$this->status;
6508 global
$conf, $langs, $user;
6514 $errorsMsg = array();
6516 $langs->load(
"bills");
6519 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Invoice"));
6522 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
6523 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6528 $arrayforcerecipient = array();
6529 foreach (explode(
';', (
string) $forcerecipient) as $tmpvalue) {
6530 $tmpvalue = trim($tmpvalue);
6531 if ($tmpvalue !==
'') {
6532 if (!in_array($tmpvalue, array(
'thirdpartyemail',
'externalbillingcontacts',
'salesrepresentative')) && !
isValidEmail($tmpvalue)) {
6533 $this->output .=
'Bad value "'.$tmpvalue.
'" for parameter forcerecipient. Must be an email, "thirdpartyemail", "externalbillingcontacts" or "salesrepresentative"';
6536 $arrayforcerecipient[] = $tmpvalue;
6539 $forcerecipient = implode(
';', $arrayforcerecipient);
6540 if (empty($arrayforcerecipient)) {
6541 $arrayforcerecipient = array(
'thirdpartyemail');
6550 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
6551 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
6552 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
6553 $formmail =
new FormMail($this->db);
6558 $tmpinvoice =
new Facture($this->db);
6563 $labelreminderok =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
6566 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
6567 if (!empty($paymentmode) && $paymentmode !=
'all') {
6568 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
6570 $sql .=
" WHERE f.paye = 0";
6571 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
6572 if ($datetouse ==
'invoicedate') {
6573 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
6575 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
6577 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
6578 if (!empty($paymentmode) && $paymentmode !=
'all') {
6579 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
6582 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
6583 $sql .=
" AND f.total_ttc > 0";
6585 $sql .=
" AND NOT EXISTS (SELECT a.id FROM ".MAIN_DB_PREFIX.
"actioncomm as a";
6586 $sql .=
" WHERE a.elementtype = 'invoice' AND a.fk_element = f.rowid AND a.code = 'AC_EMAIL'";
6587 $sql .=
" AND a.label = '".$this->db->escape($labelreminderok).
"'";
6589 if ($datetouse ==
'invoicedate') {
6590 $sql .= $this->db->order(
"datef",
"ASC");
6592 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
6595 $resql = $this->db->query($sql);
6598 if ($datetouse ==
'invoicedate') {
6599 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
6601 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
6603 if (!empty($paymentmode) && $paymentmode !=
'all') {
6604 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
6606 $this->output .=
'<br>';
6609 while ($obj = $this->db->fetch_object($resql)) {
6614 $res = $tmpinvoice->fetch($obj->id);
6616 $tmpinvoice->fetch_thirdparty();
6618 $tmpinvoice->getSommePaiement();
6619 $tmpinvoice->getSumCreditNotesUsed();
6620 $tmpinvoice->getSumDepositsUsed();
6623 if ($tmpinvoice->thirdparty->default_lang) {
6624 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6625 $outputlangs->loadLangs(array(
"main",
"bills"));
6627 $outputlangs = $langs;
6631 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
6632 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6633 $langs->load(
"errors");
6634 if (is_numeric($template)) {
6642 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
6651 $errorsMsg[] = $langs->trans(
'ErrorFailedToFindEmailTemplate', $template).
' (invoice '.$tmpinvoice->ref.
')';
6659 $tmpinvoice->totalpaid = $tmpinvoice->getSommePaiement();
6660 $tmpinvoice->totalcreditnotes = $tmpinvoice->getSumCreditNotesUsed();
6661 $tmpinvoice->totaldeposits = $tmpinvoice->getSumDepositsUsed();
6662 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $tmpinvoice);
6667 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6670 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6676 $res = $tmpinvoice->fetch_thirdparty();
6677 $recipient = $tmpinvoice->thirdparty;
6679 foreach ($arrayforcerecipient as $tmpforcerecipient) {
6680 if ($tmpforcerecipient ==
'thirdpartyemail') {
6681 if (!empty($recipient->email)) {
6682 $to[] = $recipient->email;
6684 } elseif ($tmpforcerecipient ==
'externalbillingcontacts') {
6685 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
6686 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6687 foreach ($tmparraycontact as $data_email) {
6688 if (!empty($data_email[
'email'])) {
6689 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
6693 } elseif ($tmpforcerecipient ==
'salesrepresentative') {
6694 $tmparraysalesrep = $recipient->getSalesRepresentatives($user);
6695 if (is_array($tmparraysalesrep)) {
6696 foreach ($tmparraysalesrep as $salesrep) {
6697 if (!empty($salesrep[
'email']) && !empty($salesrep[
'status'])) {
6698 $to[] = $salesrep[
'email'];
6703 $to[] = $tmpforcerecipient;
6706 $to = array_values(array_unique(array_filter($to)));
6708 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email found for recipients ".implode(
";", $arrayforcerecipient).
".";
6712 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6718 if (!empty($arraymessage->email_from)) {
6719 $email_from = (string) $arraymessage->email_from;
6721 if (empty($email_from)) {
6722 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6726 if (!$loopError && !empty($to)) {
6727 $to = implode(
',', $to);
6728 if (!empty($arraymessage->email_to)) {
6729 $to = $to.
','.$arraymessage->email_to;
6735 $trackid =
'inv'.$tmpinvoice->id;
6736 $sendcontext =
'standard';
6739 if (!empty($arraymessage->email_tocc)) {
6740 $email_tocc = (string) $arraymessage->email_tocc;
6744 if (!empty($arraymessage->email_tobcc)) {
6745 $email_tobcc = (string) $arraymessage->email_tobcc;
6752 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6753 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
6754 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6755 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
6759 $cMailFile =
new CMailFile($sendTopic, $to, $email_from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
6761 $resultsendmail = $cMailFile->sendfile();
6766 if ($resultsendmail) {
6770 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6775 $actioncomm->type_code =
'AC_OTH_AUTO';
6776 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6777 $actioncomm->contact_id = 0;
6779 $actioncomm->code =
'AC_EMAIL';
6780 $actioncomm->label = $labelreminderok;
6781 $actioncomm->note_private = $sendContent;
6782 $actioncomm->fk_project = $tmpinvoice->fk_project;
6783 $actioncomm->datep =
dol_now();
6784 $actioncomm->datef = $actioncomm->datep;
6785 $actioncomm->percentage = -1;
6786 $actioncomm->authorid = $user->id;
6787 $actioncomm->userownerid = $user->id;
6789 $actioncomm->email_msgid = $cMailFile->msgid;
6790 $actioncomm->email_subject = $sendTopic;
6791 $actioncomm->email_from = $email_from;
6792 $actioncomm->email_sender =
'';
6793 $actioncomm->email_to = $to;
6797 $actioncomm->errors_to = $errors_to;
6799 $actioncomm->elementtype =
'invoice';
6800 $actioncomm->elementid = $tmpinvoice->id;
6804 $actioncomm->create($user);
6806 $errormesg = $cMailFile->error.
' : '.$to;
6810 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6815 $actioncomm->type_code =
'AC_OTH_AUTO';
6816 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6817 $actioncomm->contact_id = 0;
6819 $actioncomm->code =
'AC_EMAIL';
6820 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
6821 $actioncomm->note_private = $errormesg;
6822 $actioncomm->fk_project = $tmpinvoice->fk_project;
6823 $actioncomm->datep =
dol_now();
6824 $actioncomm->datef = $actioncomm->datep;
6825 $actioncomm->percentage = -1;
6826 $actioncomm->authorid = $user->id;
6827 $actioncomm->userownerid = $user->id;
6829 $actioncomm->email_msgid = $cMailFile->msgid;
6830 $actioncomm->email_subject = $sendTopic;
6831 $actioncomm->email_from = $email_from;
6832 $actioncomm->email_sender =
'';
6833 $actioncomm->email_to = $to;
6837 $actioncomm->errors_to = $errors_to;
6839 $actioncomm->elementtype =
'invoice';
6840 $actioncomm->elementid = $tmpinvoice->id;
6844 $actioncomm->create($user);
6847 $this->db->commit();
6851 $errorsMsg[] = $errormesg;
6854 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6858 $error += $loopError;
6865 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6867 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6871 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6873 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6888 $sql =
"SELECT datef";
6889 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6890 $sql .=
" WHERE type = " . (int) $this->
type ;
6891 $sql .=
" AND date_valid IS NOT NULL";
6892 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6893 $sql .=
" ORDER BY datef DESC LIMIT 1";
6895 $result = $this->db->query($sql);
6898 if ($this->db->num_rows($result)) {
6899 $obj = $this->db->fetch_object($result);
6900 $last_date = $this->db->jdate($obj->datef);
6901 $invoice_date = $this->date;
6903 $is_last_of_same_type = $invoice_date >= $last_date;
6904 if ($allow_validated_drafts) {
6908 return array($is_last_of_same_type, $last_date);
6914 dol_print_error($this->db);
6931 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6933 $picto = $this->picto;
6934 if ($this->
type == self::TYPE_REPLACEMENT) {
6937 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6940 if ($this->
type == self::TYPE_DEPOSIT) {
6944 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6945 $return .=
'<div class="info-box info-box-sm">';
6946 $return .=
'<span class="info-box-icon bg-infobox-action">';
6947 $return .= img_picto(
'', $picto);
6948 $return .=
'</span>';
6949 $return .=
'<div class="info-box-content">';
6950 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6951 if ($selected >= 0) {
6952 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6954 if (!empty($arraydata[
'thirdparty'])) {
6955 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6957 if (property_exists($this,
'date')) {
6958 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->
date,
'day').
'</span>';
6960 if (property_exists($this,
'total_ht')) {
6961 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6962 $return .=
' '.$langs->trans(
"HT");
6963 $return .=
'</span>';
6965 if (method_exists($this,
'getLibStatut')) {
6966 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6967 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6969 $return .=
'</div>';
6970 $return .=
'</div>';
6971 $return .=
'</div>';
if(! $sortfield) if(! $sortorder) $object
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
checkPointOfTaxNotChanged()
Check that the point of tax date of a validated invoice is not changed by an update.
getSumCreditNotesUsed($multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice.
getSumDepositsUsed($multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage invoices.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Returns the IDs of the customer shipping contacts.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
createFromClone(User $user, $fromid=0, $forceentity=null)
Load an object from its id and create a new one in database.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Replace a thirdparty id with another one.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
__construct($db)
Constructor.
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines ...
update(User $user, $notrigger=0)
Update database.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
getIdBillingContact()
Returns the IDs of the customer billing contacts.
const STATUS_DRAFT
Draft status.
persistFieldValue(User $user, $field)
Save into database the current value of one field, called by updateFieldFromUi().
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=self::TYPE_STANDARD, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=array(), $situation_percent=100, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a detail line.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target='')
Return clickable link of object (with eventually picto)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
fetch($rowid, $ref='', $ref_ext='', $notused=0, $fetch_situation=false)
Get object from database.
setInputReason($inputReasonId, $notrigger=0)
Update invoice input reason.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
updatePriceNextInvoice(&$langs)
Update price of next invoice.
getRetainedWarrantyAmount($rounding='MT')
Calculate the amount of the retained warranty (from the percentage).
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Replace a product id with another one.
setRetainedWarrantyDateLimit($timestamp, $dateYmd='')
Change the retained_warranty_date_limit.
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $datetouse='duedate', $forcerecipient='')
Send reminders by emails for invoices validated that are due.
info($id)
Load miscellaneous information for tab "Info".
const TYPE_PROFORMA
Proforma invoice (should not be used.
consumeDepositCredits(User $user, Facture $depositInvoice, float $amount_ttc)
Consume unused deposit credit rows (llx_societe_remise_except) up to $amount_ttc.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setRetainedWarranty($value)
Change the retained warranty.
get_prev_sits()
Returns an array containing the previous situations as Invoice objects.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
getObjectLinesDisplayContext()
Return the display context of the lines, as defined by the card before printObjectLines() and formAdd...
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
newCycle()
Gets the smallest reference available for a new cycle.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
isSituationInvoice()
Check if an invoice is a situation invoice.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getTooltipContentArray($params)
getTooltipContentArray
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
fetch_lines($only_type_product='', $loadalsotranslation=0)
Load all detailed lines into this->lines.
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
const STATUS_VALIDATED
Validated (need to be paid)
hasDelay()
Is the customer invoice delayed?
getLinesArray()
Create an array of invoice lines.
set_unpaid($user)
Tags the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a di...
const TYPE_DEPOSIT
Deposit invoice.
set_paid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
const STATUS_ABANDONED
Classified abandoned and no payment done.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
setPaid($user, $close_code='', $close_note='')
Tag the invoice as :
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed.
const TYPE_CREDIT_NOTE
Credit note invoice.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
create(User $user, $notrigger=0, $forceduedate=0, $updatecurrencyrate=0)
Create invoice in database.
initAsSpecimen($option='')
Initialise an instance with random values.
deleteLine($rowid, $id=0)
Delete line in database.
addline( $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $fk_code_ventilation=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=array(), $situation_percent=100, $fk_prev_id=0, $fk_unit=null, $pu_ht_devise=0, $ref_ext='', $noupdateafterinsertline=0)
Add an invoice line into database (linked to product/service or not).
setUnpaid($user)
Tag the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a dir...
const STATUS_CLOSED
Classified paid.
setCategories($categories)
Sets object to given categories.
createFromContract($object, User $user, $lines=array())
Load an object from a contract and create a new invoice into database.
Class to manage invoice lines.
Class to manage invoice templates.
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 predefined suppliers products.
Class to manage products or services.
Manage record for batch number management.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
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...
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
dol_get_next_month($month, $year)
Return next month.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
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.
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEntity($currentobject)
Set entity id to use when to create an object.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getWarningDelay($module, $parmlevel1, $parmlevel2='')
Return a warning delay You can use it like this: if (getWarningDelay('module', 'paramlevel1')) It rep...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
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_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
dolPayRefGenerateForInvoice($object, $user, $store=1)
Generate and optionally store the payment reference of an invoice.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.