50require_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
51require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/factureligne.class.php';
52require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
53require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
54require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
55require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
56require_once DOL_DOCUMENT_ROOT.
'/subtotals/class/commonsubtotal.class.php';
59 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
62 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
75 public $element =
'facture';
80 public $TRIGGER_PREFIX =
'BILL';
85 public $table_element =
'facture';
90 public $table_element_line =
'facturedet';
95 public $class_element_line =
'FactureLigne';
100 public $fk_element =
'fk_facture';
105 public $picto =
'bill';
111 public $restrictiononfksoc = 1;
127 public $fk_user_author;
133 public $fk_user_valid;
139 public $fk_user_modif;
149 public $delivery_date;
161 public $ref_customer;
177 public $module_source;
185 public $pos_print_counter = 0;
190 public $email_sent_counter = 0;
195 public $fk_fac_rec_source;
200 public $fk_facture_source;
210 public $lines = array();
219 public $extraparams = array();
229 public $date_pointoftax;
235 public $situation_cycle_ref;
240 public $situation_counter;
245 public $situation_final;
250 public $tab_previous_situation_invoice = array();
255 public $tab_next_situation_invoice = array();
260 public $retained_warranty;
265 public $retained_warranty_date_limit;
270 public $retained_warranty_fk_cond_reglement;
275 public $availability_id;
280 public $date_closing;
291 public $remise_percent;
296 public $online_payment_url;
333 public $fields = array(
334 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 1),
335 'ref' => array(
'type' =>
'varchar(30)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'position' => 5),
336 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 20,
'index' => 1),
337 'ref_client' => array(
'type' =>
'varchar(255)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 10),
338 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'RefExt',
'enabled' => 1,
'visible' => 0,
'position' => 12),
339 'type' => array(
'type' =>
'smallint(6)',
'label' =>
'Type',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
340 'subtype' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoiceSubtype',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
342 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 50),
343 'datef' => array(
'type' =>
'date',
'label' =>
'DateInvoice',
'enabled' => 1,
'visible' => 1,
'position' => 20),
344 'date_valid' => array(
'type' =>
'date',
'label' =>
'DateValidation',
'enabled' => 1,
'visible' => -1,
'position' => 22),
345 'date_lim_reglement' => array(
'type' =>
'date',
'label' =>
'DateDue',
'enabled' => 1,
'visible' => 1,
'position' => 25),
346 'date_closing' => array(
'type' =>
'datetime',
'label' =>
'DateClosing',
'enabled' => 1,
'visible' => -1,
'position' => 30),
347 'paye' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoicePaidCompletely',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 80),
348 'close_code' => array(
'type' =>
'varchar(16)',
'label' =>
'EarlyClosingReason',
'enabled' => 1,
'visible' => -1,
'position' => 92),
349 'close_note' => array(
'type' =>
'varchar(128)',
'label' =>
'EarlyClosingComment',
'enabled' => 1,
'visible' => -1,
'position' => 93),
350 'total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountHT',
'enabled' => 1,
'visible' => 1,
'position' => 95,
'isameasure' => 1),
351 'total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountVAT',
'enabled' => 1,
'visible' => -1,
'position' => 100,
'isameasure' => 1),
352 'localtax1' => array(
'type' =>
'double(24,8)',
'label' =>
'LT1',
'enabled' => 1,
'visible' => -1,
'position' => 110,
'isameasure' => 1),
353 'localtax2' => array(
'type' =>
'double(24,8)',
'label' =>
'LT2',
'enabled' => 1,
'visible' => -1,
'position' => 120,
'isameasure' => 1),
354 'revenuestamp' => array(
'type' =>
'double(24,8)',
'label' =>
'RevenueStamp',
'enabled' => 1,
'visible' => -1,
'position' => 115,
'isameasure' => 1),
355 'total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountTTC',
'enabled' => 1,
'visible' => 1,
'position' => 130,
'isameasure' => 1),
356 'fk_facture_source' => array(
'type' =>
'integer',
'label' =>
'SourceInvoice',
'enabled' => 1,
'visible' => -1,
'position' => 170),
357 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' => 1,
'visible' => -1,
'position' => 175),
358 'fk_account' => array(
'type' =>
'integer',
'label' =>
'Fk account',
'enabled' => 1,
'visible' => -1,
'position' => 180),
359 'fk_currency' => array(
'type' =>
'varchar(3)',
'label' =>
'CurrencyCode',
'enabled' => 1,
'visible' => -1,
'position' => 185),
360 'fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentTerm',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 190),
361 'fk_mode_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentMode',
'enabled' => 1,
'visible' => -1,
'position' => 195),
362 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 205),
363 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 210),
364 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 215),
365 'fk_input_reason' => array(
'type' =>
'integer',
'label' =>
'Source',
'enabled' => 1,
'visible' => -1,
'position' => 220),
366 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 225),
367 'situation_cycle_ref' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation cycle ref',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 230),
368 'situation_counter' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation counter',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 235),
369 'situation_final' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation final',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 240),
370 'retained_warranty' => array(
'type' =>
'double',
'label' =>
'Retained warranty',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 245),
371 'retained_warranty_date_limit' => array(
'type' =>
'date',
'label' =>
'Retained warranty date limit',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 250),
372 'retained_warranty_fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'Retained warranty fk cond reglement',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 255),
373 'fk_incoterms' => array(
'type' =>
'integer',
'label' =>
'IncotermCode',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 260),
374 'location_incoterms' => array(
'type' =>
'varchar(255)',
'label' =>
'IncotermLabel',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 265),
375 'date_pointoftax' => array(
'type' =>
'date',
'label' =>
'DatePointOfTax',
'enabled' =>
'getDolGlobalString("INVOICE_POINTOFTAX_DATE")',
'visible' => -1,
'position' => 270),
376 'fk_multicurrency' => array(
'type' =>
'integer',
'label' =>
'MulticurrencyID',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 275),
377 'multicurrency_code' => array(
'type' =>
'varchar(255)',
'label' =>
'Currency',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 280),
378 'multicurrency_tx' => array(
'type' =>
'double(24,8)',
'label' =>
'CurrencyRate',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 285,
'isameasure' => 1),
379 'multicurrency_total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountHT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 290,
'isameasure' => 1),
380 'multicurrency_total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountVAT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 291,
'isameasure' => 1),
381 'multicurrency_total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountTTC',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 292,
'isameasure' => 1),
382 'fk_fac_rec_source' => array(
'type' =>
'integer',
'label' =>
'RecurringInvoiceSource',
'enabled' => 1,
'visible' => -1,
'position' => 305),
383 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'LastMainDoc',
'enabled' => 1,
'visible' => -1,
'position' => 310),
384 'module_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSModule',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 315),
385 'pos_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSTerminal',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 320),
386 'pos_print_counter' => array(
'type' =>
'integer',
'label' =>
'PrintCount',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => 0,
'position' => 325),
387 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 500),
388 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModificationShort',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 502),
389 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'position' => 506),
390 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModification',
'enabled' => 1,
'visible' => -1,
'notnull' => -1,
'position' => 508),
391 'fk_user_valid' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserValidation',
'enabled' => 1,
'visible' => -1,
'position' => 510),
392 'fk_user_closing' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserClosing',
'enabled' => 1,
'visible' => -1,
'position' => 512),
393 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 900),
394 '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')),
473 $this->ismultientitymanaged = 1;
474 $this->isextrafieldmanaged = 1;
476 $this->fields[
'ref_ext'][
'visible'] =
getDolGlobalInt(
'MAIN_LIST_SHOW_REF_EXT');
490 public function create(
User $user, $notrigger = 0, $forceduedate = 0, $updatecurrencyrate = 0)
494 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
496 if (empty($this->
type)) {
500 $this->ref_client = trim((
string) $this->ref_client);
501 $this->ref_customer = trim((
string) $this->ref_customer);
503 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
504 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
505 $this->note_public = (isset($this->note_public) ? trim($this->note_public) :
'');
507 if (!$this->cond_reglement_id) {
508 $this->cond_reglement_id = 0;
510 if (!$this->mode_reglement_id) {
511 $this->mode_reglement_id = 0;
516 if (!empty($this->multicurrency_code)) {
518 if (empty($this->multicurrency_tx)) {
526 $this->fk_multicurrency = 0;
528 if (empty($this->fk_multicurrency)) {
529 $this->multicurrency_code =
$conf->currency;
530 $this->fk_multicurrency = 0;
531 $this->multicurrency_tx = 1;
535 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
538 if (empty($this->
date)) {
539 $this->error =
"Try to create an invoice with an empty parameter (date)";
540 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
544 $result = $soc->fetch($this->socid);
546 $this->error =
"Failed to fetch company: ".$soc->error;
547 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
552 $this->date_creation = $now;
556 $originaldatewhen =
null;
557 $nextdatewhen =
null;
558 $previousdaynextdatewhen =
null;
563 if ($this->fac_rec > 0) {
564 $this->fk_fac_rec_source = $this->fac_rec;
566 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
568 $result = $_facrec->fetch($this->fac_rec);
569 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
573 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
577 $originaldatewhen = $_facrec->date_when;
578 $nextdatewhen =
null;
579 $previousdaynextdatewhen =
null;
581 if ($originaldatewhen) {
582 if ($_facrec->rule_for_lines_dates ==
'postpaid') {
584 $originaldatewhen =
dol_time_plus_duree($originaldatewhen, -$_facrec->frequency, $_facrec->unit_frequency);
586 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, (
int) $_facrec->frequency, $_facrec->unit_frequency);
592 if (!empty($_facrec->frequency)) {
593 $this->socid = $_facrec->socid;
597 $this->entity = $_facrec->entity;
602 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
603 $this->note_public = GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
604 $this->note_private = GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
605 $this->model_pdf = GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
606 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
607 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
608 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
611 $this->total_ht = $_facrec->total_ht;
612 $this->total_ttc = $_facrec->total_ttc;
615 $this->fk_incoterms = $_facrec->fk_incoterms;
616 $this->location_incoterms = $_facrec->location_incoterms;
622 $this->ref_client = trim($this->ref_client);
623 $this->ref_customer = trim($this->ref_customer);
624 $this->note_public = trim($this->note_public);
625 $this->note_private = trim($this->note_private);
626 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
629 foreach ($_facrec->array_options as $key => $val) {
630 if (!isset($this->array_options[$key]) || $this->array_options[$key] ===
'') {
631 $this->array_options[$key] = $val;
635 if (!$this->mode_reglement_id) {
636 $this->mode_reglement_id = 0;
641 $this->linked_objects = $_facrec->linkedObjectsIds;
646 if ($_facrec->frequency > 0) {
647 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
648 if (empty($_facrec->date_when)) {
649 $_facrec->date_when = $now;
651 $next_date = $_facrec->getNextDate();
653 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
656 $result = $_facrec->setNextDate($next_date, 1);
660 $outputlangs = $langs;
663 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
664 $newlang = $this->thirdparty->default_lang;
667 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
668 $newlang = $this->default_lang;
670 if (!empty($newlang)) {
672 $outputlangs->setDefaultLang($newlang);
676 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $this);
687 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
688 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
689 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
690 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
691 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
702 if (empty($forceduedate)) {
708 $this->date_lim_reglement = $duedate;
710 $this->date_lim_reglement = $forceduedate;
714 $socid = $this->socid;
716 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
725 $sql .=
", date_pointoftax";
726 $sql .=
", note_private";
727 $sql .=
", note_public";
728 $sql .=
", ref_client";
729 $sql .=
", fk_account";
730 $sql .=
", module_source, pos_source, pos_print_counter, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
731 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
732 $sql .=
", fk_input_reason";
733 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
734 $sql .=
", fk_incoterms, location_incoterms";
735 $sql .=
", fk_multicurrency";
736 $sql .=
", multicurrency_code";
737 $sql .=
", multicurrency_tx";
738 $sql .=
", retained_warranty";
739 $sql .=
", retained_warranty_date_limit";
740 $sql .=
", retained_warranty_fk_cond_reglement";
745 $sql .=
", ".(int) $this->entity;
746 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
747 $sql .=
", ".((int) $this->
type);
748 $sql .=
", ".(isset($this->subtype) ? (int) $this->subtype :
"null");
749 $sql .=
", ".((int) $socid);
750 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
753 $sql .=
", '".$this->db->idate($this->
date).
"'";
754 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
755 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
756 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
757 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
758 $sql .=
", ".($this->fk_account > 0 ? ((int) $this->fk_account) :
'NULL');
759 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
760 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape((
string) $this->pos_source).
"'" :
"null");
761 $sql .=
", ".(int) $this->pos_print_counter;
762 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape((
string) $this->fk_fac_rec_source).
"'" :
"null");
763 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape((
string) $this->fk_facture_source).
"'" :
"null");
764 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
765 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
766 $sql .=
", ".((int) $this->cond_reglement_id);
767 $sql .=
", ".((int) $this->mode_reglement_id);
768 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
769 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
770 $sql .=
", ".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id :
"null");
771 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape((
string) $this->situation_cycle_ref).
"'" :
"null");
772 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape((
string) $this->situation_counter).
"'" :
"null");
773 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
774 $sql .=
", ".(int) $this->fk_incoterms;
775 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
776 $sql .=
", ".(int) $this->fk_multicurrency;
777 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
778 $sql .=
", ".(float) $this->multicurrency_tx;
779 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape((
string) $this->retained_warranty));
780 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
781 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
782 $sql .=
", ".(!empty($this->ip) ?
"'".$this->db->escape($this->ip).
"'" :
"null");
785 $resql = $this->db->query($sql);
787 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
790 $this->
ref =
'(PROV'.$this->id.
')';
791 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
793 $resql = $this->db->query($sql);
798 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
799 $this->linked_objects = $this->linkedObjectsIds;
803 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
804 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
805 if (is_array($tmp_origin_id)) {
806 foreach ($tmp_origin_id as $origin_id) {
809 $this->error = $this->db->lasterror();
814 $origin_id = $tmp_origin_id;
817 $this->error = $this->db->lasterror();
825 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && (!empty($this->origin_type) || !empty($this->origin)) && !empty($this->origin_id)) {
826 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
827 $originidforcontact = $this->origin_id;
828 if ($originforcontact ==
'shipping') {
829 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
831 $exp->fetch($this->origin_id);
832 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
833 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
834 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
835 $originforcontact =
'commande';
836 if (is_object($value)) {
837 $originidforcontact = $value->id;
839 $originidforcontact = $value;
846 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople";
847 $sqlcontact .=
" FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
848 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
850 $resqlcontact = $this->db->query($sqlcontact);
852 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
853 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
861 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
864 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
865 foreach ($this->lines as $i => $val) {
866 $newinvoiceline = $this->lines[$i];
867 '@phan-var-force FactureLigne $newinvoiceline';
869 $newinvoiceline->context = $this->context;
871 $newinvoiceline->fk_facture = $this->id;
873 $newinvoiceline->origin = $this->lines[$i]->element;
874 $newinvoiceline->origin_type = $this->lines[$i]->element;
875 $newinvoiceline->origin_id = $this->lines[$i]->id;
878 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
879 $newinvoiceline->date_start = $originaldatewhen;
881 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
882 $newinvoiceline->date_end = $previousdaynextdatewhen;
887 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
892 $vatrate = $newinvoiceline->tva_tx;
893 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
894 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
897 $newinvoiceline->fk_parent_line = $fk_parent_line;
901 $discount->fetch($newinvoiceline->fk_remise_except);
903 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
904 $newinvoiceline->fk_remise_except = $discountId;
908 $line_price_base_type = $newinvoiceline->getPriceBaseType();
910 $newinvoiceline->desc,
911 (
float) $newinvoiceline->subprice,
912 $newinvoiceline->qty,
914 $newinvoiceline->localtax1_tx,
915 $newinvoiceline->localtax2_tx,
916 $newinvoiceline->fk_product,
917 $newinvoiceline->remise_percent,
918 $newinvoiceline->date_start,
919 $newinvoiceline->date_end,
920 $newinvoiceline->fk_code_ventilation,
921 $newinvoiceline->info_bits,
922 $newinvoiceline->fk_remise_except,
923 $line_price_base_type,
924 (
float) $newinvoiceline->subprice_ttc,
925 $newinvoiceline->product_type,
926 $newinvoiceline->rang,
927 $newinvoiceline->special_code,
928 $newinvoiceline->element,
931 $newinvoiceline->fk_fournprice,
932 $newinvoiceline->pa_ht,
933 $newinvoiceline->label,
934 $newinvoiceline->array_options,
935 $newinvoiceline->situation_percent,
936 $newinvoiceline->fk_prev_id,
937 $newinvoiceline->fk_unit,
938 $newinvoiceline->multicurrency_subprice,
939 $newinvoiceline->ref_ext,
950 if ($result > 0 && $newinvoiceline->product_type == 9) {
951 $fk_parent_line = $result;
955 } elseif (!$error && empty($this->fac_rec)) {
958 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
960 foreach ($this->lines as $i => $val) {
961 $line = $this->lines[$i];
962 '@phan-var-force FactureLigne $line';
966 if (!is_object($line)) {
967 $line = (object) $line;
972 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
977 $vatrate = $line->tva_tx;
978 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
979 $vatrate .=
' ('.$line->vat_src_code.
')';
983 $originid = $line->origin_id;
984 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
986 $originid = $line->id;
987 $origintype = $this->element;
991 if (empty($line->ref_ext)) {
1000 $line->localtax1_tx,
1001 $line->localtax2_tx,
1003 $line->remise_percent,
1006 $line->fk_code_ventilation,
1008 $line->fk_remise_except,
1011 $line->product_type,
1013 $line->special_code,
1017 $line->fk_fournprice,
1020 $line->array_options,
1021 $line->situation_percent,
1024 $line->multicurrency_subprice,
1029 $this->error = $this->db->lasterror();
1031 $this->db->rollback();
1036 if ($result > 0 && $line->product_type == 9) {
1037 $fk_parent_line = $result;
1044 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1045 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1046 $fk_parent_line = 0;
1048 foreach ($_facrec->lines as $i => $val) {
1050 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1051 $fk_parent_line = 0;
1054 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1055 $tva_npr = (int) $_facrec->lines[$i]->info_bits;
1056 if (empty($tva_tx)) {
1059 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1060 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1062 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1063 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1066 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1067 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1069 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1074 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1075 $buyprice = $producttmp->cost_price;
1077 $buyprice = $producttmp->pmp;
1079 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1080 if ($producttmp->product_fourn_price_id > 0) {
1081 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1088 if ($updatecurrencyrate == 1) {
1090 } elseif ($updatecurrencyrate == 2) {
1094 $result_insert = $this->
addline(
1095 $_facrec->lines[$i]->desc,
1096 $_facrec->lines[$i]->subprice,
1097 $_facrec->lines[$i]->qty,
1101 $_facrec->lines[$i]->fk_product,
1102 $_facrec->lines[$i]->remise_percent,
1103 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1104 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1110 $_facrec->lines[$i]->product_type,
1111 $_facrec->lines[$i]->rang,
1112 $_facrec->lines[$i]->special_code,
1116 $fk_product_fournisseur_price,
1117 is_null($buyprice) ?
'' : $buyprice,
1118 $_facrec->lines[$i]->label,
1119 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1122 $_facrec->lines[$i]->fk_unit,
1123 $_facrec->lines[$i]->multicurrency_subprice,
1124 $_facrec->lines[$i]->ref_ext,
1128 foreach ($this->lines as $line) {
1129 if ($line->id == $result_insert) {
1130 $line->extraparams = $_facrec->lines[$i]->extraparams;
1131 $line->setExtraParameters();
1136 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1137 $fk_parent_line = $result_insert;
1140 if ($result_insert < 0) {
1142 $this->error = $this->db->error();
1151 $this->error = $langs->trans(
'FailedToUpdatePrice');
1152 $this->db->rollback();
1167 if (!$error && !$notrigger) {
1169 $result = $this->call_trigger(
'BILL_CREATE', $user);
1176 $this->db->commit();
1179 $this->db->rollback();
1183 $this->error = $this->db->error();
1184 $this->db->rollback();
1200 $facture =
new Facture($this->db);
1203 $facture->context[
'createfromclone'] = 1;
1208 if (empty($this->array_options)) {
1212 if (!empty($this->array_options)) {
1213 $facture->array_options = $this->array_options;
1216 foreach ($this->lines as &$line) {
1217 $line->fetch_optionals();
1220 $facture->fk_facture_source = $this->fk_facture_source;
1221 $facture->type = $this->type;
1222 $facture->subtype = $this->subtype;
1223 $facture->socid = $this->socid;
1224 $facture->date = $this->date;
1225 $facture->date_pointoftax = $this->date_pointoftax;
1226 $facture->note_public = $this->note_public;
1227 $facture->note_private = $this->note_private;
1228 $facture->ref_client = $this->ref_client;
1229 $facture->ref_customer = $this->ref_customer;
1230 $facture->model_pdf = $this->model_pdf;
1231 $facture->fk_project = $this->fk_project;
1232 $facture->cond_reglement_id = $this->cond_reglement_id;
1233 $facture->mode_reglement_id = $this->mode_reglement_id;
1235 $facture->origin = $this->origin;
1236 $facture->origin_id = $this->origin_id;
1237 $facture->fk_account = $this->fk_account;
1239 $facture->lines = $this->lines;
1240 $facture->situation_counter = $this->situation_counter;
1241 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1242 $facture->situation_final = $this->situation_final;
1244 $facture->retained_warranty = $this->retained_warranty;
1245 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1246 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1248 $facture->fk_user_author = $user->id;
1249 $facture->user_creation_id = $user->id;
1253 foreach ($facture->lines as $i => $tmpline) {
1254 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1255 if ($invertdetail) {
1256 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1257 $facture->lines[$i]->subprice_ttc = -$facture->lines[$i]->subprice_ttc;
1258 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1259 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1260 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1261 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1262 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1263 $facture->lines[$i]->ref_ext =
'';
1267 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1269 $facid = $facture->create($user);
1271 $this->error = $facture->error;
1272 $this->errors = $facture->errors;
1276 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1277 foreach ($Tfk_object as $fk_object) {
1278 $facture->add_object_linked($typeObject, $fk_object);
1282 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1299 global $hookmanager;
1319 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1320 $objsoc =
new Societe($this->db);
1322 if ($objsoc->fetch($this->socid) > 0) {
1324 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1325 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1327 $object->fk_delivery_address = 0;
1333 $object->entity = (!empty($forceentity) ? $forceentity :
$object->entity);
1341 $object->user_creation_id = $user->id;
1342 $object->user_validation_id =
null;
1343 $object->user_modification_id =
null;
1344 $object->fk_user_author = $user->id;
1345 $object->fk_user_valid =
null;
1346 $object->fk_facture_source = 0;
1347 $object->fk_fac_rec_source = 0;
1349 $object->date_modification =
'';
1350 $object->date_validation =
'';
1361 foreach (
$object->lines as $i => $line) {
1362 '@phan-var-force FactureLigne $line';
1363 if (($line->info_bits & 0x02) == 0x02) {
1370 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1382 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1383 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1387 $object->lines[$i]->date_start = $newFirst;
1388 $object->lines[$i]->date_end = $newLast;
1392 $object->lines[$i]->ref_ext =
'';
1395 $object->lines[$i]->fk_code_ventilation = 0;
1399 $object->context[
'createfromclone'] =
'createfromclone';
1400 $result =
$object->create($user);
1407 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1410 } elseif (
$object->socid == $objFrom->socid) {
1412 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1421 if (is_object($hookmanager)) {
1422 $parameters = array(
'objFrom' => $objFrom,
'clonedObj' =>
$object);
1424 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1432 unset(
$object->context[
'createfromclone']);
1436 $this->db->commit();
1439 $this->db->rollback();
1453 global $hookmanager;
1462 $this->context[
'createfromclone'] = 1;
1465 for ($i = 0; $i < $num; $i++) {
1467 $src_line =
$object->lines[$i];
1468 '@phan-var-force FactureLigne $src_line';
1469 $line->libelle = $src_line->libelle;
1470 $line->label = $src_line->label;
1471 $line->desc = $src_line->desc;
1472 $line->subprice = $src_line->subprice;
1473 $line->subprice_ttc = $src_line->subprice_ttc;
1474 $line->total_ht = $src_line->total_ht;
1475 $line->total_tva = $src_line->total_tva;
1476 $line->total_localtax1 = $src_line->total_localtax1;
1477 $line->total_localtax2 = $src_line->total_localtax2;
1478 $line->total_ttc = $src_line->total_ttc;
1479 $line->vat_src_code = $src_line->vat_src_code;
1480 $line->tva_tx = $src_line->tva_tx;
1481 $line->localtax1_tx = $src_line->localtax1_tx;
1482 $line->localtax2_tx = $src_line->localtax2_tx;
1483 $line->qty = $src_line->qty;
1484 $line->fk_remise_except = $src_line->fk_remise_except;
1485 $line->remise_percent = $src_line->remise_percent;
1486 $line->fk_product = $src_line->fk_product;
1487 $line->info_bits = $src_line->info_bits;
1488 $line->product_type = $src_line->product_type;
1489 $line->rang = $src_line->rang;
1490 $line->special_code = $src_line->special_code;
1491 $line->fk_parent_line = $src_line->fk_parent_line;
1492 $line->fk_unit = $src_line->fk_unit;
1493 $line->date_start = $src_line->date_start;
1494 $line->date_end = $src_line->date_end;
1497 $line->fk_multicurrency = $src_line->fk_multicurrency;
1498 $line->multicurrency_code = $src_line->multicurrency_code;
1499 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1500 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1501 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1502 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1504 $line->fk_fournprice = $src_line->fk_fournprice;
1505 $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);
1506 $line->pa_ht = $marginInfos[0];
1509 $src_line->fetch_optionals();
1510 foreach ($src_line->array_options as $options_key => $value) {
1511 $line->array_options[$options_key] = $value;
1514 $this->lines[$i] = $line;
1517 $this->socid =
$object->socid;
1518 $this->fk_project =
$object->fk_project;
1519 $this->fk_account =
$object->fk_account;
1520 $this->cond_reglement_id =
$object->cond_reglement_id;
1521 $this->mode_reglement_id =
$object->mode_reglement_id;
1522 $this->fk_incoterms =
$object->fk_incoterms;
1523 $this->location_incoterms =
$object->location_incoterms;
1524 $this->availability_id =
$object->availability_id;
1525 $this->demand_reason_id =
$object->demand_reason_id;
1526 $this->delivery_date =
$object->delivery_date;
1527 $this->fk_delivery_address =
$object->fk_delivery_address;
1528 $this->contact_id =
$object->contact_id;
1529 $this->ref_client =
$object->ref_client;
1530 $this->ref_customer =
$object->ref_client;
1533 $this->note_private =
$object->note_private;
1534 $this->note_public =
$object->note_public;
1537 $this->module_source =
$object->module_source;
1538 $this->pos_source =
$object->pos_source;
1540 $this->origin =
$object->element;
1541 $this->origin_type =
$object->element;
1542 $this->origin_id =
$object->id;
1544 $this->fk_user_author = $user->id;
1545 $this->user_creation_id = $user->id;
1549 foreach (
$object->array_options as $options_key => $value) {
1550 $this->array_options[$options_key] = $value;
1554 $this->linked_objects[$this->origin] = $this->origin_id;
1555 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1556 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1559 $ret = $this->
create($user);
1563 $hookmanager->initHooks(array(
'invoicedao'));
1565 $parameters = array(
'objFrom' =>
$object);
1567 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1576 unset($this->context[
'createfromclone']);
1595 global $hookmanager;
1603 $use_all_lines = empty($lines);
1605 for ($i = 0; $i < $num; $i++) {
1606 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1612 $line->libelle =
$object->lines[$i]->libelle;
1613 $line->label =
$object->lines[$i]->label;
1614 $line->desc =
$object->lines[$i]->desc;
1615 $line->subprice =
$object->lines[$i]->subprice;
1616 $line->subprice_ttc =
$object->lines[$i]->subprice_ttc;
1617 $line->total_ht =
$object->lines[$i]->total_ht;
1618 $line->total_tva =
$object->lines[$i]->total_tva;
1619 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1620 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1621 $line->total_ttc =
$object->lines[$i]->total_ttc;
1622 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1623 $line->tva_tx =
$object->lines[$i]->tva_tx;
1624 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1625 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1626 $line->qty =
$object->lines[$i]->qty;
1627 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1628 $line->remise_percent =
$object->lines[$i]->remise_percent;
1629 $line->fk_product =
$object->lines[$i]->fk_product;
1630 $line->info_bits =
$object->lines[$i]->info_bits;
1631 $line->product_type =
$object->lines[$i]->product_type;
1632 $line->rang =
$object->lines[$i]->rang;
1633 $line->special_code =
$object->lines[$i]->special_code;
1634 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1635 $line->fk_unit =
$object->lines[$i]->fk_unit;
1636 $line->date_start =
$object->lines[$i]->date_start;
1637 $line->date_end =
$object->lines[$i]->date_end;
1640 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1641 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1642 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1643 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1644 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1645 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1647 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1649 $line->pa_ht = $marginInfos[0];
1652 $object->lines[$i]->fetch_optionals();
1653 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1654 $line->array_options[$options_key] = $value;
1657 $this->lines[$i] = $line;
1660 $this->socid =
$object->socid;
1661 $this->fk_project =
$object->fk_project;
1662 $this->fk_account =
$object->fk_account;
1663 $this->cond_reglement_id =
$object->cond_reglement_id;
1664 $this->mode_reglement_id =
$object->mode_reglement_id;
1665 $this->availability_id =
$object->availability_id;
1666 $this->demand_reason_id =
$object->demand_reason_id;
1667 $this->delivery_date =
$object->delivery_date;
1668 $this->fk_delivery_address =
$object->fk_delivery_address;
1669 $this->contact_id =
$object->contact_id;
1670 $this->ref_client =
$object->ref_client;
1673 $this->note_private =
$object->note_private;
1674 $this->note_public =
$object->note_public;
1677 $this->module_source =
$object->module_source;
1678 $this->pos_source =
$object->pos_source;
1680 $this->origin =
$object->element;
1681 $this->origin_id =
$object->id;
1683 $this->fk_user_author = $user->id;
1684 $this->user_creation_id = $user->id;
1688 foreach (
$object->array_options as $options_key => $value) {
1689 $this->array_options[$options_key] = $value;
1693 $this->linked_objects[$this->origin] = $this->origin_id;
1694 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1695 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1698 $ret = $this->
create($user);
1702 $hookmanager->initHooks(array(
'invoicedao'));
1704 $parameters = array(
'objFrom' =>
$object);
1706 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1736 global
$conf, $langs, $hookmanager, $action;
1738 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1739 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1744 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1748 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1751 $origin->error =
'ErrorDateIsInFuture';
1755 if ($payment_terms_id <= 0) {
1756 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1760 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1762 if (empty($payment_conditions_deposit_percent)) {
1763 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1767 if (empty($origin->deposit_percent)) {
1768 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1772 $deposit =
new self($origin->db);
1773 $deposit->socid = $origin->socid;
1775 $deposit->fk_project = $origin->fk_project;
1776 $deposit->ref_client = $origin->ref_client;
1777 $deposit->ref_customer = $origin->ref_client;
1778 $deposit->date = $date;
1779 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1780 $deposit->cond_reglement_id = $payment_terms_id;
1781 $deposit->availability_id = $origin->availability_id;
1782 $deposit->demand_reason_id = $origin->demand_reason_id;
1783 $deposit->fk_account = $origin->fk_account;
1784 $deposit->fk_incoterms = $origin->fk_incoterms;
1785 $deposit->location_incoterms = $origin->location_incoterms;
1786 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1787 $deposit->multicurrency_code = $origin->multicurrency_code;
1788 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1789 $deposit->module_source = $origin->module_source;
1790 $deposit->pos_source = $origin->pos_source;
1791 $deposit->model_pdf =
'sponge';
1793 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1802 $deposit->note_private = $origin->note_private;
1803 $deposit->note_public = $origin->note_public;
1806 $deposit->origin = $origin->element;
1807 $deposit->origin_type = $origin->element;
1808 $deposit->origin_id = $origin->id;
1810 $origin->fetch_optionals();
1812 foreach ($origin->array_options as $extrakey => $value) {
1813 $deposit->array_options[$extrakey] = $value;
1816 $deposit->linked_objects[$deposit->origin_type] = $deposit->origin_id;
1818 foreach ($overrideFields as $key => $value) {
1819 $deposit->$key = $value;
1822 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1824 $origin->db->begin();
1827 $createReturn = $deposit->create($user, $notrigger);
1829 if ($createReturn <= 0) {
1830 $origin->db->rollback();
1831 $origin->error = $deposit->error;
1832 $origin->errors = $deposit->errors;
1836 $amount_ttc_diff = 0;
1837 $amountdeposit = array();
1838 $descriptions = array();
1845 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1847 $TTotalByTva = array();
1848 foreach ($origin->lines as &$line) {
1849 if (!empty($line->special_code)) {
1852 $key = $line->tva_tx . ($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
1853 if (!array_key_exists($key, $TTotalByTva)) {
1854 $TTotalByTva[$key] = 0;
1855 $descriptions[$key] =
'';
1857 $TTotalByTva[$key] += $line->total_ttc;
1858 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1859 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1860 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1861 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1864 foreach ($TTotalByTva as $tva => &$total) {
1865 $tva_rate_only = preg_replace(
'/\s*\(.*\)/',
'', (
string) $tva);
1866 $coef = $total / $origin->total_ttc;
1867 $am = $amount * $coef;
1868 $amount_ttc_diff += $am;
1869 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100);
1873 $lines = $origin->lines;
1874 $numlines = count($lines);
1875 for ($i = 0; $i < $numlines; $i++) {
1876 if (empty($lines[$i]->qty)) {
1879 if (!empty($lines[$i]->special_code)) {
1883 $totalamount += $lines[$i]->total_ht;
1884 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ?
' ('.$lines[$i]->vat_src_code.
')' :
'');
1885 if (!isset($amountdeposit[$tva_key])) {
1886 $amountdeposit[$tva_key] = 0;
1887 $descriptions[$tva_key] =
'';
1889 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1890 $descriptions[$tva_key] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1891 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1892 $descriptions[$tva_key] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1893 $descriptions[$tva_key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1896 if ($totalamount == 0) {
1897 $amountdeposit[0] = 0;
1900 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1903 foreach ($amountdeposit as $tva => $amount) {
1904 if (empty($amount)) {
1908 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1911 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1912 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1915 $addlineResult = $deposit->addline(
1942 if ($addlineResult < 0) {
1943 $origin->db->rollback();
1944 $origin->error = $deposit->error;
1945 $origin->errors = $deposit->errors;
1950 $diff = $deposit->total_ttc - $amount_ttc_diff;
1953 $deposit->fetch_lines();
1954 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1958 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ?
' ('.$deposit->lines[0]->vat_src_code.
')' :
'');
1959 $updatelineResult = $deposit->updateline(
1960 $deposit->lines[0]->id,
1961 $deposit->lines[0]->desc,
1963 $deposit->lines[0]->qty,
1964 $deposit->lines[0]->remise_percent,
1965 $deposit->lines[0]->date_start,
1966 $deposit->lines[0]->date_end,
1971 $deposit->lines[0]->info_bits,
1972 $deposit->lines[0]->product_type,
1976 $deposit->lines[0]->pa_ht,
1977 $deposit->lines[0]->label,
1983 if ($updatelineResult < 0) {
1984 $origin->db->rollback();
1985 $origin->error = $deposit->error;
1986 $origin->errors = $deposit->errors;
1991 $hookmanager->initHooks(array(
'invoicedao'));
1993 $parameters = array(
'objFrom' => $origin);
1994 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1997 $origin->db->rollback();
1998 $origin->error = $hookmanager->error;
1999 $origin->errors = $hookmanager->errors;
2003 if (!empty($autoValidateDeposit)) {
2004 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
2006 if ($validateReturn < 0) {
2007 $origin->db->rollback();
2008 $origin->error = $deposit->error;
2009 $origin->errors = $deposit->errors;
2014 unset($deposit->context[
'createdepositfromorigin']);
2016 $origin->db->commit();
2032 $langs->load(
'bills');
2035 $moretitle = $params[
'moretitle'] ??
'';
2037 $picto = $this->picto;
2038 if ($this->
type == self::TYPE_REPLACEMENT) {
2041 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2044 if ($this->
type == self::TYPE_DEPOSIT) {
2048 if ($user->hasRight(
"facture",
"read")) {
2049 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
2051 $datas[
'picto'] .=
' '.$this->getLibType(1);
2054 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
2057 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2060 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
2063 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2064 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2067 $datas[
'picto'] .=
' - '.$moretitle;
2069 if (!empty($this->
ref)) {
2070 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2072 if (!empty($this->ref_customer)) {
2073 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
2075 if (!empty($this->
date)) {
2076 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->
date,
'day');
2078 if (!empty($this->total_ht)) {
2079 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2081 if (!empty($this->total_tva)) {
2082 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2084 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2085 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1,
$conf->currency);
2087 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2089 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1',
$mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency);
2091 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2092 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2',
$mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency);
2094 if (!empty($this->total_ttc)) {
2095 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2116 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2118 global $langs,
$conf, $user;
2120 if (!empty(
$conf->dol_no_mouse_hover)) {
2126 if ($option ==
'withdraw') {
2127 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2129 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2132 if (!$user->hasRight(
"facture",
"read")) {
2136 if ($option !==
'nolink') {
2138 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2139 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2140 $add_save_lastsearch_values = 1;
2142 if ($add_save_lastsearch_values) {
2143 $url .=
'&save_lastsearch_values=1';
2151 $picto = $this->picto;
2152 if ($this->
type == self::TYPE_REPLACEMENT) {
2155 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2158 if ($this->
type == self::TYPE_DEPOSIT) {
2164 'objecttype' => $this->element,
2165 'moretitle' => $moretitle,
2166 'option' => $option,
2168 $classfortooltip =
'classfortooltip';
2171 $classfortooltip =
'classforajaxtooltip';
2172 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2178 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2179 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2181 $label = $langs->trans(
"Invoice");
2182 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2184 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2185 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2188 $linkstart =
'<a href="'.$url.
'"';
2189 $linkstart .= $linkclose.
'>';
2192 if ($option ==
'nolink') {
2197 $result .= $linkstart;
2199 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2201 if ($withpicto != 2) {
2202 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2204 $result .= $linkend;
2206 if ($addlinktonotes) {
2207 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2209 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2210 $result .=
' <span class="note inline-block">';
2211 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dolPrintHTMLForAttribute($notetoshow).
'">';
2214 $result .=
'</span>';
2218 global $action, $hookmanager;
2219 $hookmanager->initHooks(array(
'invoicedao'));
2220 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2221 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2223 $result = $hookmanager->resPrint;
2225 $result .= $hookmanager->resPrint;
2241 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2243 global
$conf, $extrafields;
2245 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2249 $extraFieldsCheck =
false;
2250 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2252 if ($doFetchInOneSqlRequest) {
2254 if (!isset($extrafields) || !is_object($extrafields)) {
2255 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2260 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
2261 $extrafields->fetch_name_optionals_label($this->table_element);
2264 $extraFieldsCheck = (
2265 !empty($extrafields->attributes[$this->table_element][
'label'])
2266 && is_array($extrafields->attributes[$this->table_element][
'label'])
2267 && count($extrafields->attributes[$this->table_element][
'label']) > 0
2273 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2274 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2275 $sql .=
', f.datef as df, f.date_pointoftax';
2276 $sql .=
', f.date_lim_reglement as dlr';
2277 $sql .=
', f.datec as datec';
2278 $sql .=
', f.date_valid as datev';
2279 $sql .=
', f.tms as datem';
2280 $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';
2281 $sql .=
", f.fk_input_reason";
2282 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2283 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2284 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2285 $sql .=
', f.fk_account';
2286 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2287 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2288 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2289 $sql .=
', f.fk_incoterms, f.location_incoterms';
2290 $sql .=
', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2291 $sql .=
", i.libelle as label_incoterms";
2292 $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";
2293 $sql .=
", f.payment_reference, f.dispute_status";
2295 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2296 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2297 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2298 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2301 if ($type !==
'separate') {
2302 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2303 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2305 $sql .=
", ef.".$this->db->sanitize($key);
2311 $sql .=
' FROM '.$this->db->prefix().
'facture as f';
2314 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2316 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element.
'_extrafields as ef ON f.rowid = ef.fk_object';
2319 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2320 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_paiement as p ON f.fk_mode_reglement = p.id';
2321 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2322 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2325 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2327 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2329 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2332 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2336 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2337 $resql = $this->db->query($sql);
2339 if ($this->db->num_rows($resql)) {
2340 $obj = $this->db->fetch_object($resql);
2342 $this->
id = $obj->rowid;
2343 $this->entity = $obj->entity;
2345 $this->
ref = $obj->ref;
2346 $this->ref_client = $obj->ref_client;
2347 $this->ref_customer = $obj->ref_client;
2348 $this->ref_ext = $obj->ref_ext;
2349 $this->
type = $obj->type;
2350 $this->subtype = $obj->subtype;
2351 $this->
date = $this->db->jdate($obj->df);
2352 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2353 $this->date_creation = $this->db->jdate($obj->datec);
2354 $this->date_validation = $this->db->jdate($obj->datev);
2355 $this->date_modification = $this->db->jdate($obj->datem);
2356 $this->datem = $this->db->jdate($obj->datem);
2357 $this->total_ht = $obj->total_ht;
2358 $this->total_tva = $obj->total_tva;
2359 $this->total_localtax1 = $obj->localtax1;
2360 $this->total_localtax2 = $obj->localtax2;
2361 $this->total_ttc = $obj->total_ttc;
2362 $this->revenuestamp = $obj->revenuestamp;
2363 $this->paye = $obj->paye;
2364 $this->close_code = $obj->close_code;
2365 $this->close_note = $obj->close_note;
2367 $this->socid = $obj->fk_soc;
2368 $this->thirdparty =
null;
2370 $this->fk_project = $obj->fk_project;
2371 $this->project =
null;
2373 $this->statut = $obj->status;
2374 $this->
status = $obj->status;
2376 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2377 $this->mode_reglement_id = $obj->fk_mode_reglement;
2378 $this->mode_reglement_code = $obj->mode_reglement_code;
2379 $this->mode_reglement = $obj->mode_reglement_libelle;
2380 $this->cond_reglement_id = $obj->fk_cond_reglement;
2381 $this->cond_reglement_code = $obj->cond_reglement_code;
2382 $this->cond_reglement = $obj->cond_reglement_libelle;
2383 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2384 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2385 $this->fk_facture_source = $obj->fk_facture_source;
2386 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2387 $this->note = $obj->note_private;
2388 $this->note_private = $obj->note_private;
2389 $this->note_public = $obj->note_public;
2390 $this->user_creation_id = $obj->fk_user_author;
2391 $this->user_validation_id = $obj->fk_user_valid;
2392 $this->user_modification_id = $obj->fk_user_modif;
2393 $this->fk_user_author = $obj->fk_user_author;
2394 $this->fk_user_valid = $obj->fk_user_valid;
2395 $this->fk_user_modif = $obj->fk_user_modif;
2396 $this->model_pdf = $obj->model_pdf;
2397 $this->last_main_doc = $obj->last_main_doc;
2398 $this->demand_reason_id = $obj->fk_input_reason;
2399 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2400 $this->situation_counter = $obj->situation_counter;
2401 $this->situation_final = $obj->situation_final;
2402 $this->retained_warranty = $obj->retained_warranty;
2403 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2404 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2406 $this->payment_reference = $obj->payment_reference;
2407 $this->dispute_status = $obj->dispute_status;
2409 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2412 $this->fk_incoterms = $obj->fk_incoterms;
2413 $this->location_incoterms = $obj->location_incoterms;
2414 $this->label_incoterms = $obj->label_incoterms;
2416 $this->module_source = $obj->module_source;
2417 $this->pos_source = $obj->pos_source;
2418 $this->pos_print_counter = (int) $obj->pos_print_counter;
2419 $this->email_sent_counter = $obj->email_sent_counter;
2422 $this->fk_multicurrency = $obj->fk_multicurrency;
2423 $this->multicurrency_code = $obj->multicurrency_code;
2424 $this->multicurrency_tx = $obj->multicurrency_tx;
2425 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2426 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2427 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2430 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2431 $this->array_options = array();
2433 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2434 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2435 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2438 if ($type !==
'separate') {
2439 $rawval = $obj->$key;
2442 if (in_array($type, array(
'date',
'datetime'))) {
2443 $this->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2444 } elseif ($type ==
'password') {
2445 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2446 $this->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2448 $this->array_options[
'options_' . $key] = $rawval;
2451 $this->array_options[
'options_' . $key] = $rawval;
2457 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2458 if (!empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
2459 if (empty(
$conf->disable_compute)) {
2460 global $objectoffield;
2461 $objectoffield = $this;
2462 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
2468 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2472 if (!$doFetchInOneSqlRequest) {
2479 $this->lines = array();
2483 $this->error = $this->db->error();
2487 $this->db->free($resql);
2491 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2493 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2497 $this->error = $this->db->lasterror();
2511 public function fetch_lines($only_type_product =
'', $loadalsotranslation = 0)
2513 global
$conf, $extrafields;
2516 $this->lines = array();
2518 $extraFieldsCheck =
false;
2519 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2521 if ($doFetchInOneSqlRequest) {
2523 if (!isset($extrafields) || !is_object($extrafields)) {
2524 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2529 if (empty($extrafields->attributes[$this->table_element_line][
'loaded'])) {
2530 $extrafields->fetch_name_optionals_label($this->table_element_line);
2533 $extraFieldsCheck = (
2534 !empty($extrafields->attributes[$this->table_element_line][
'label'])
2535 && is_array($extrafields->attributes[$this->table_element_line][
'label'])
2536 && count($extrafields->attributes[$this->table_element_line][
'label']) > 0
2540 $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,';
2541 $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,';
2542 $sql .=
' l.situation_percent, l.fk_prev_id,';
2543 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2544 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2545 $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,';
2546 $sql .=
' l.fk_unit, l.extraparams,';
2547 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2548 $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';
2550 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2551 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2552 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2553 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2556 if ($type !==
'separate') {
2557 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2558 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2560 $sql .=
", ef.".$this->db->sanitize($key);
2566 $sql .=
' FROM '.$this->db->prefix().
'facturedet as l';
2569 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2571 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element_line.
'_extrafields as ef ON l.rowid = ef.fk_object';
2574 $sql .=
' LEFT JOIN '.$this->db->prefix().
'product as p ON l.fk_product = p.rowid';
2575 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2576 if (is_int($only_type_product)) {
2577 $sql .=
" AND p.fk_product_type = ".((int) $only_type_product);
2579 $sql .=
' ORDER BY l.rang, l.rowid';
2581 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2582 $result = $this->db->query($sql);
2584 $num = $this->db->num_rows($result);
2587 $objp = $this->db->fetch_object($result);
2590 $line->id = $objp->rowid;
2591 $line->rowid = $objp->rowid;
2592 $line->fk_facture = $objp->fk_facture;
2593 $line->label = $objp->custom_label;
2594 $line->desc = $objp->description;
2595 $line->description = $objp->description;
2596 $line->product_type = $objp->product_type;
2597 $line->ref = $objp->product_ref;
2598 $line->product_ref = $objp->product_ref;
2599 $line->libelle = $objp->product_label;
2600 $line->product_label = $objp->product_label;
2601 $line->product_barcode = $objp->product_barcode;
2602 $line->product_desc = $objp->product_desc;
2603 $line->fk_product_type = $objp->fk_product_type;
2604 $line->qty = $objp->qty;
2605 $line->subprice = $objp->subprice;
2606 $line->subprice_ttc = $objp->subprice_ttc;
2607 $line->ref_ext = $objp->ref_ext;
2609 $line->vat_src_code = $objp->vat_src_code;
2610 $line->tva_tx = $objp->tva_tx;
2611 $line->localtax1_tx = $objp->localtax1_tx;
2612 $line->localtax2_tx = $objp->localtax2_tx;
2613 $line->localtax1_type = $objp->localtax1_type;
2614 $line->localtax2_type = $objp->localtax2_type;
2615 $line->remise_percent = $objp->remise_percent;
2616 $line->fk_remise_except = $objp->fk_remise_except;
2617 $line->fk_product = $objp->fk_product;
2618 $line->date_start = $this->db->jdate($objp->date_start);
2619 $line->date_end = $this->db->jdate($objp->date_end);
2620 $line->info_bits = $objp->info_bits;
2621 $line->total_ht = $objp->total_ht;
2622 $line->total_tva = $objp->total_tva;
2623 $line->total_localtax1 = $objp->total_localtax1;
2624 $line->total_localtax2 = $objp->total_localtax2;
2625 $line->total_ttc = $objp->total_ttc;
2627 $line->fk_fournprice = $objp->fk_fournprice;
2628 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2629 $line->pa_ht = $marginInfos[0];
2630 $line->marge_tx = (
string) $marginInfos[1];
2631 $line->marque_tx = (
string) $marginInfos[2];
2632 $line->rang = $objp->rang;
2633 $line->special_code = $objp->special_code;
2634 $line->fk_parent_line = $objp->fk_parent_line;
2635 $line->situation_percent = $objp->situation_percent;
2636 $line->fk_prev_id = $objp->fk_prev_id;
2637 $line->fk_unit = $objp->fk_unit;
2639 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
2641 $line->batch = $objp->batch;
2642 $line->fk_warehouse = $objp->fk_warehouse;
2645 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2648 $line->fk_multicurrency = $objp->fk_multicurrency;
2649 $line->multicurrency_code = $objp->multicurrency_code;
2650 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2651 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2652 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2653 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2655 $line->array_options = array();
2656 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2657 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2658 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2659 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2662 if ($type !==
'separate') {
2663 $rawval = $objp->$key;
2666 if (in_array($type, array(
'date',
'datetime'))) {
2667 $line->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2668 } elseif ($type ==
'password') {
2669 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2670 $line->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2672 $line->array_options[
'options_' . $key] = $rawval;
2675 $line->array_options[
'options_' . $key] = $rawval;
2681 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2682 if (!empty($extrafields->attributes[$this->table_element_line][
'computed'][$key])) {
2683 if (empty(
$conf->disable_compute)) {
2684 global $objectoffield;
2685 $objectoffield = $line;
2686 $line->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element_line][
'computed'][$key], 1, 0,
'2');
2692 if (!$doFetchInOneSqlRequest) {
2694 $line->fetch_optionals();
2698 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2699 $tmpproduct =
new Product($this->db);
2700 $tmpproduct->fetch($objp->fk_product);
2701 $tmpproduct->getMultiLangs();
2703 $line->multilangs = $tmpproduct->multilangs;
2706 $this->lines[$i] = $line;
2710 $this->db->free($result);
2713 $this->error = $this->db->error();
2726 $this->tab_previous_situation_invoice = array();
2727 $this->tab_next_situation_invoice = array();
2729 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2730 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2731 $sql .=
' AND entity = '.((int) $this->entity);
2732 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2733 $sql .=
' ORDER BY situation_counter ASC';
2735 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2736 $result = $this->db->query($sql);
2737 if ($result && $this->db->num_rows($result) > 0) {
2738 while ($objp = $this->db->fetch_object($result)) {
2739 $invoice =
new Facture($this->db);
2740 if ($invoice->fetch($objp->rowid) > 0) {
2741 if ($objp->situation_counter < $this->situation_counter
2742 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2744 $this->tab_previous_situation_invoice[] = $invoice;
2746 $this->tab_next_situation_invoice[] = $invoice;
2767 if (empty($this->
type)) {
2770 if (isset($this->subtype)) {
2771 $this->subtype = (int) $this->subtype;
2773 if (isset($this->
ref)) {
2774 $this->
ref = trim($this->
ref);
2776 if (isset($this->ref_ext)) {
2777 $this->ref_ext = trim($this->ref_ext);
2779 if (!empty($this->ref_customer)) {
2780 $this->ref_customer = trim($this->ref_customer);
2782 if (isset($this->increment)) {
2783 $this->increment = trim($this->increment);
2785 if (isset($this->close_code)) {
2786 $this->close_code = trim($this->close_code);
2788 if (isset($this->close_note)) {
2789 $this->close_note = trim($this->close_note);
2791 if (isset($this->note) || isset($this->note_private)) {
2792 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2794 if (isset($this->note) || isset($this->note_private)) {
2795 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2797 if (isset($this->note_public)) {
2798 $this->note_public = trim($this->note_public);
2800 if (isset($this->model_pdf)) {
2801 $this->model_pdf = trim($this->model_pdf);
2803 if (isset($this->import_key)) {
2804 $this->import_key = trim($this->import_key);
2806 if (isset($this->retained_warranty)) {
2807 $this->retained_warranty = (float) $this->retained_warranty;
2809 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2810 $this->user_creation_id = $this->fk_user_author;
2812 if (!isset($this->user_modification_id) && !empty($user->id)) {
2813 $this->user_modification_id = $user->id;
2815 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2816 $this->user_validation_id = $this->fk_user_valid;
2821 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2822 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2823 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2824 $sql .=
" type=".(isset($this->
type) ? ((int) $this->
type) :
"null").
",";
2825 $sql .=
" subtype=".(isset($this->subtype) ? (int) $this->subtype :
"null").
",";
2826 $sql .=
" ref_client=".(!empty($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2827 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2828 $sql .=
" fk_soc=".(isset($this->socid) ? ((int) $this->socid) :
"null").
",";
2829 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2830 $sql .=
" datef=".(strval($this->
date) !=
'' ?
"'".$this->db->idate($this->
date).
"'" :
'null').
",";
2831 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2832 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2833 $sql .=
" paye=".(isset($this->paye) ? ((int) $this->paye) : 0).
",";
2834 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2835 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2836 $sql .=
" total_tva=".((float) $this->total_tva).
",";
2837 $sql .=
" localtax1=".((float) $this->total_localtax1).
",";
2838 $sql .=
" localtax2=".((float) $this->total_localtax2).
",";
2839 $sql .=
" total_ht=".((float) $this->total_ht).
",";
2840 $sql .=
" total_ttc=".((float) $this->total_ttc).
",";
2841 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2842 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2843 $sql .=
" fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) :
"null").
",";
2844 $sql .=
" fk_user_modif=".(!empty($user->id) ? ((int) $user->id) :
"null").
",";
2845 $sql .=
" fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id :
"null").
",";
2846 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2847 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2848 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2849 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2850 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2851 $sql .=
" note_private = ".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2852 $sql .=
" note_public = ".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2853 $sql .=
" model_pdf = ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2854 $sql .=
" import_key = ".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2855 $sql .=
" module_source = ".(isset($this->module_source) ?
"'".$this->db->escape($this->module_source).
"'" :
"null").
",";
2856 $sql .=
" pos_source = ".(isset($this->pos_source) ?
"'".$this->db->escape($this->pos_source).
"'" :
"null").
",";
2857 $sql .=
" pos_print_counter = ".(int) $this->pos_print_counter.
",";
2858 $sql .=
" situation_cycle_ref = ".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2859 $sql .=
" situation_counter = ".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2860 $sql .=
" situation_final = ".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2861 $sql .=
" retained_warranty = ".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2862 $sql .=
" retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2863 $sql .=
" retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2864 $sql .=
" WHERE rowid = ".((int) $this->
id);
2868 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2869 $resql = $this->db->query($sql);
2872 $this->errors[] =
"Error ".$this->db->lasterror();
2882 if (!$error && !$notrigger) {
2884 $result = $this->call_trigger(
'BILL_MODIFY', $user);
2893 foreach ($this->errors as $errmsg) {
2894 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2895 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2897 $this->db->rollback();
2900 $this->db->commit();
2918 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2919 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2924 $result = $remise->fetch($idremise);
2927 if ($remise->fk_facture) {
2928 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2929 $this->db->rollback();
2934 $facligne->fk_facture = $this->id;
2935 $facligne->fk_remise_except = $remise->id;
2936 $facligne->desc = $remise->description;
2937 $facligne->vat_src_code = $remise->vat_src_code;
2938 $facligne->tva_tx = $remise->tva_tx;
2939 $facligne->localtax1_tx = $remise->localtax1_tx;
2940 $facligne->localtax1_type = (int) $remise->localtax1_type;
2941 $facligne->localtax2_tx = $remise->localtax2_tx;
2942 $facligne->localtax2_type = (int) $remise->localtax2_type;
2943 $facligne->subprice = -(float) $remise->total_ht;
2944 $facligne->fk_product = 0;
2946 $facligne->remise_percent = 0;
2947 $facligne->rang = -1;
2948 $facligne->info_bits = 2;
2951 $facligne->rang = 1;
2952 $linecount = count($this->lines);
2953 for ($ii = 1; $ii <= $linecount; $ii++) {
2959 if ($remise->fk_facture_source > 0) {
2960 $srcinvoice =
new Facture($this->db);
2961 $srcinvoice->fetch($remise->fk_facture_source);
2962 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2964 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2965 $facligne->pa_ht = $arraytmp[
'pa_total'];
2968 $facligne->total_ht = -(float) $remise->total_ht;
2969 $facligne->total_tva = -(float) $remise->total_tva;
2970 $facligne->total_ttc = -(float) $remise->total_ttc;
2971 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
2972 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
2974 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2975 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
2976 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
2977 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
2979 $lineid = $facligne->insert();
2984 $result = $remise->link_to_invoice($lineid, 0);
2986 $this->error = $remise->error;
2987 $this->db->rollback();
2991 $this->db->commit();
2994 $this->error = $facligne->error;
2995 $this->db->rollback();
2999 $this->error = $facligne->error;
3000 $this->db->rollback();
3004 $this->db->rollback();
3026 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3027 if (empty($ref_client)) {
3028 $sql .=
" SET ref_client = NULL";
3030 $sql .=
" SET ref_client = '".$this->db->escape($ref_client).
"'";
3032 $sql .=
" WHERE rowid = ".((int) $this->
id);
3034 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
3035 $resql = $this->db->query($sql);
3037 $this->errors[] = $this->db->error();
3042 $this->ref_client = $ref_client;
3043 $this->ref_customer = $ref_client;
3046 if (!$notrigger && empty($error)) {
3048 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3056 $this->ref_client = $ref_client;
3057 $this->ref_customer = $ref_client;
3059 $this->db->commit();
3062 foreach ($this->errors as $errmsg) {
3063 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
3064 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
3066 $this->db->rollback();
3086 dol_syslog(__METHOD__.
' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3087 if ($this->
status >= self::STATUS_DRAFT) {
3089 $this->demand_reason_id = $inputReasonId;
3093 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3094 $sql .=
" SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId :
'null');
3095 $sql .=
" WHERE rowid = ".((int) $this->
id);
3098 $res = $this->db->query($sql);
3101 $this->error = $this->db->lasterror();
3102 $this->errors[] = $this->error;
3108 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3117 $this->db->commit();
3119 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3120 $this->db->rollback();
3121 dol_syslog(__METHOD__.
' Error : '.$this->errorsToString(), LOG_ERR);
3142 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3144 global $langs,
$conf;
3145 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3149 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
3162 if (!$error && !$notrigger) {
3164 $result = $this->call_trigger(
'BILL_DELETE', $user);
3173 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"categorie_invoice";
3174 $sql .=
" WHERE fk_invoice = ".((int) $this->
id);
3176 $result = $this->db->query($sql);
3179 $this->errors[] = $this->db->lasterror();
3188 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
3202 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
3203 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
3204 $sql .=
' AND fk_facture_line IS NULL';
3205 $resql = $this->db->query($sql);
3209 $list_rowid_det = array();
3210 foreach ($this->lines as $key => $invoiceline) {
3211 $list_rowid_det[] = $invoiceline->id;
3215 if (count($list_rowid_det)) {
3216 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3217 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
3218 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
3220 if (!$this->db->query($sql)) {
3221 $this->error = $this->db->error().
" sql=".$sql;
3222 $this->errors[] = $this->error;
3223 $this->db->rollback();
3230 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
3231 $sql .=
' SET fk_invoice = NULL';
3232 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
3234 if (!$this->db->query($sql)) {
3235 $this->error = $this->db->error().
" sql=".$sql;
3236 $this->errors[] = $this->error;
3237 $this->db->rollback();
3241 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
3242 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
3243 $sql .=
' WHERE invoice_id = '.((int) $rowid);
3245 if (!$this->db->query($sql)) {
3246 $this->error = $this->db->error().
" sql=".$sql;
3247 $this->errors[] = $this->error;
3248 $this->db->rollback();
3254 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3255 $langs->load(
"agenda");
3257 $num = count($this->lines);
3258 for ($i = 0; $i < $num; $i++) {
3259 if ($this->lines[$i]->fk_product > 0) {
3261 $mouvP->origin = &$this;
3262 $mouvP->setOrigin($this->element, $this->
id);
3264 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3265 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3267 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3274 $sql_main_table = MAIN_DB_PREFIX.
'facturedet';
3275 $sql_ef_table = $sql_main_table.
"_extrafields";
3276 $sqlef =
"DELETE FROM ".$sql_ef_table.
" WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table.
" WHERE fk_facture = ".((int) $rowid).
")";
3278 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
3281 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
3283 $resql = $this->db->query($sql);
3291 if ($conf->facture->dir_output && !empty($this->
ref)) {
3292 $dir =
$conf->facture->dir_output.
"/".$ref;
3293 $file =
$conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
3294 if (file_exists($file)) {
3298 $langs->load(
"errors");
3299 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
3300 $this->errors[] = $this->error;
3301 $this->db->rollback();
3305 if (file_exists($dir)) {
3307 $langs->load(
"errors");
3308 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
3309 $this->errors[] = $this->error;
3310 $this->db->rollback();
3316 $this->db->commit();
3319 $this->error = $this->db->lasterror().
" sql=".$sql;
3320 $this->errors[] = $this->error;
3321 $this->db->rollback();
3325 $this->error = $this->db->lasterror().
" sql=".$sql;
3326 $this->errors[] = $this->error;
3327 $this->db->rollback();
3331 $this->db->rollback();
3348 public function set_paid($user, $close_code =
'', $close_note =
'')
3351 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3352 return $this->
setPaid($user, $close_code, $close_note);
3365 public function setPaid($user, $close_code =
'', $close_note =
'')
3369 if ($this->paye != 1 || $this->
status != self::STATUS_CLOSED) {
3374 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3376 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3377 $sql .=
' fk_statut = '.self::STATUS_CLOSED;
3379 $sql .=
', paye = 1';
3382 $sql .=
", close_code = '".$this->db->escape($close_code).
"'";
3385 $sql .=
", close_note = '".$this->db->escape($close_note).
"'";
3387 $sql .=
', fk_user_closing = '.((int) $user->id);
3388 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3389 $sql .=
" WHERE rowid = ".((int) $this->
id);
3391 $resql = $this->db->query($sql);
3394 $result = $this->call_trigger(
'BILL_PAYED', $user);
3401 $this->error = $this->db->lasterror();
3407 $this->db->commit();
3410 $this->db->rollback();
3433 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3451 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3452 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3453 $sql .=
' date_closing=null,';
3454 $sql .=
' fk_user_closing=null';
3455 $sql .=
" WHERE rowid = ".((int) $this->
id);
3457 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3458 $resql = $this->db->query($sql);
3461 $result = $this->call_trigger(
'BILL_UNPAYED', $user);
3468 $this->error = $this->db->error();
3473 $this->db->commit();
3476 $this->db->rollback();
3498 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3499 return $this->
setCanceled($user, $close_code, $close_note);
3512 public function setCanceled($user, $close_code =
'', $close_note =
'')
3514 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3519 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3520 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3522 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3525 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3527 $sql .=
', fk_user_closing = '.((int) $user->id);
3528 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3529 $sql .=
" WHERE rowid = ".((int) $this->
id);
3531 $resql = $this->db->query($sql);
3535 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3536 $sql .=
' SET fk_facture = NULL';
3537 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3539 $resql = $this->db->query($sql);
3542 $result = $this->call_trigger(
'BILL_CANCEL', $user);
3544 $this->db->rollback();
3549 $this->db->commit();
3552 $this->error = $this->db->error().
" sql=".$sql;
3553 $this->db->rollback();
3557 $this->error = $this->db->error().
" sql=".$sql;
3558 $this->db->rollback();
3575 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3578 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3580 $productStatic =
null;
3581 $warehouseStatic =
null;
3582 $productbatch =
null;
3583 if ($batch_rule > 0) {
3584 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3585 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3586 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3587 $productStatic =
new Product($this->db);
3588 $warehouseStatic =
new Entrepot($this->db);
3595 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3602 if ($this->
status != self::STATUS_DRAFT) {
3603 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3606 if (count($this->lines) <= 0) {
3607 $langs->load(
"errors");
3608 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3612 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3613 $this->error =
'Permission denied';
3614 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3617 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3625 if (!$last_of_type[0]) {
3632 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3633 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'TVA_INTRA',
'ACCOUNTANCY_CODE_CUSTOMER');
3634 foreach ($array_to_check as $key) {
3635 $keymin = strtolower($key);
3636 if (!property_exists($this->thirdparty, $keymin)) {
3639 $vallabel = $this->thirdparty->$keymin;
3641 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3643 if ($this->thirdparty->isACompany()) {
3645 if (
$mysoc->country_id > 0 && $this->thirdparty->country_id ==
$mysoc->country_id) {
3646 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3648 $langs->load(
"errors");
3649 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3650 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3656 if ($key ==
'EMAIL') {
3659 $langs->load(
"errors");
3660 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3661 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3665 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3667 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3668 $langs->load(
"errors");
3669 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3670 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3674 if ($key ==
'TVA_INTRA') {
3677 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3678 $langs->load(
"errors");
3679 $this->error = $langs->trans(
'ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3680 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3683 } elseif (
getDolGlobalString(
'SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3684 $langs->load(
"errors");
3685 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3686 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3695 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3696 foreach ($array_to_check as $key => $val) {
3697 $keymin = strtolower($key);
3698 $vallabel = $this->$keymin;
3701 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3703 $langs->load(
"errors");
3705 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3712 if ($this->
type == self::TYPE_REPLACEMENT) {
3714 if ($this->fk_facture_source <= 0) {
3715 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3716 $this->db->rollback();
3721 $facreplaced =
new Facture($this->db);
3722 $result = $facreplaced->fetch($this->fk_facture_source);
3724 $this->error = $langs->trans(
"ErrorBadInvoice");
3725 $this->db->rollback();
3730 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3731 if ($idreplacement && $idreplacement != $this->
id) {
3732 $facreplacement =
new Facture($this->db);
3733 $facreplacement->fetch($idreplacement);
3734 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3735 $this->db->rollback();
3739 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3741 $this->error = $facreplaced->error;
3742 $this->db->rollback();
3748 if ($force_number) {
3749 $num = $force_number;
3750 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3763 $this->oldref = $this->ref;
3771 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3772 $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).
"'";
3774 $sql .=
", datef='".$this->db->idate($this->
date).
"'";
3775 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3777 $sql .=
" WHERE rowid = ".((int) $this->
id);
3779 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3780 $resql = $this->db->query($sql);
3782 $this->error = $this->db->lasterror();
3789 $result = $this->thirdparty->setAsCustomer();
3793 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3794 $langs->load(
"agenda");
3797 $cpt = count($this->lines);
3798 for ($i = 0; $i < $cpt; $i++) {
3799 if ($this->lines[$i]->fk_product > 0) {
3801 $mouvP->origin = &$this;
3802 $mouvP->setOrigin($this->element, $this->
id);
3805 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3808 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3817 $is_batch_line =
false;
3818 if ($batch_rule > 0) {
3819 $productStatic->fetch($this->lines[$i]->fk_product);
3820 if ($productStatic->hasbatch() && is_object($productbatch)) {
3821 $is_batch_line =
true;
3822 $product_qty_remain = $this->lines[$i]->qty;
3828 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3829 $sortorder =
'ASC,ASC,ASC,ASC';
3832 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 :
null), $sortfield, $sortorder);
3833 if (!is_array($resBatchList)) {
3835 $this->error = $this->db->lasterror();
3839 $batchList = $resBatchList;
3840 if (empty($batchList)) {
3842 $langs->load(
'errors');
3843 $warehouseStatic->fetch($idwarehouse);
3844 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3845 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3848 foreach ($batchList as $batch) {
3849 if ($batch->qty <= 0) {
3854 if ($batch->qty >= $product_qty_remain) {
3855 $product_batch_qty = $product_qty_remain;
3858 $product_batch_qty = $batch->qty;
3860 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3867 $product_qty_remain -= $product_batch_qty;
3869 if ($product_qty_remain <= 0) {
3874 if (!$error && $product_qty_remain > 0) {
3877 $langs->load(
'errors');
3878 $warehouseStatic->fetch($idwarehouse);
3879 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3880 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3883 $batch = $batchList[0];
3884 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3895 if (!$is_batch_line) {
3896 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3911 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3912 $invoice_situation =
new Facture($this->db);
3913 $result = $invoice_situation->fetch($this->fk_facture_source);
3914 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3915 $invoice_situation->situation_final = 0;
3917 $result = $invoice_situation->setFinal($user, 1);
3920 $this->error = $invoice_situation->error;
3921 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3927 if (!$error && !$notrigger) {
3929 $result = $this->call_trigger(
'BILL_VALIDATE', $user);
3938 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3940 $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).
"'";
3941 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3942 $resql = $this->db->query($sql);
3945 $this->error = $this->db->lasterror();
3947 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3948 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3949 $resql = $this->db->query($sql);
3952 $this->error = $this->db->lasterror();
3959 if (!$resupdatenext) {
3969 $this->date_validation = $now;
3974 $nboflines = count($this->lines);
3975 while (($i < $nboflines) && $final) {
3976 $line = $this->lines[$i];
3977 '@phan-var-force FactureLigne $line';
3979 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3980 $current_progress = (float) $line->situation_percent;
3981 $full_progress = $previousprogress + $current_progress;
3982 $final = ($full_progress == 100);
3984 $final = ($line->situation_percent == 100);
3990 if ($this->situation_final) {
3992 $this->situation_final = 0;
3996 if (!$this->situation_final) {
3998 $this->situation_final = 1;
4008 if (!$error && preg_match(
'/^[\(]?PROV/i', $this->oldref)) {
4012 $dirsource =
$conf->facture->dir_output.
'/'.$oldref;
4013 $dirdest =
$conf->facture->dir_output.
'/'.$newref;
4014 if (!$error && file_exists($dirsource)) {
4015 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
4017 if (@rename($dirsource, $dirdest)) {
4020 $listoffiles =
dol_dir_list(
$conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
4021 foreach ($listoffiles as $fileentry) {
4022 $dirsource = $fileentry[
'name'];
4023 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
4024 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
4025 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
4026 @rename($dirsource, $dirdest);
4033 $this->db->commit();
4036 $this->db->rollback();
4049 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4050 $is_last = $next_invoice->is_last_in_cycle();
4052 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4053 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4057 foreach ($next_invoice->lines as $line) {
4058 '@phan-var-force FactureLigne $line';
4059 $result = $next_invoice->updateline(
4064 $line->remise_percent,
4068 $line->localtax1_tx,
4069 $line->localtax2_tx,
4072 $line->product_type,
4073 $line->fk_parent_line,
4075 $line->fk_fournprice,
4078 $line->special_code,
4079 $line->array_options,
4080 $line->situation_percent,
4085 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4110 if ($this->
status == self::STATUS_DRAFT) {
4111 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
4119 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4120 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
4121 $sql .=
" WHERE rowid = ".((int) $this->
id);
4123 $result = $this->db->query($sql);
4126 $this->oldcopy = clone $this;
4131 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
4132 $langs->load(
"agenda");
4134 $num = count($this->lines);
4135 for ($i = 0; $i < $num; $i++) {
4136 if ($this->lines[$i]->fk_product > 0) {
4138 $mouvP->origin = &$this;
4139 $mouvP->setOrigin($this->element, $this->
id);
4141 if ($this->
type == self::TYPE_CREDIT_NOTE) {
4142 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
4144 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
4151 $old_statut = $this->status;
4156 $result = $this->call_trigger(
'BILL_UNVALIDATE', $user);
4159 $this->statut = $old_statut;
4160 $this->
status = $old_statut;
4164 $this->db->rollback();
4169 $this->db->commit();
4172 $this->db->rollback();
4176 $this->error = $this->db->error();
4177 $this->db->rollback();
4231 $remise_percent = 0,
4234 $fk_code_ventilation = 0,
4236 $fk_remise_except = 0,
4237 $price_base_type =
'HT',
4244 $fk_parent_line = 0,
4245 $fk_fournprice =
null,
4248 $array_options = array(),
4249 $situation_percent = 100,
4254 $noupdateafterinsertline = 0
4258 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4264 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);
4266 if ($this->
status == self::STATUS_DRAFT) {
4267 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4270 if (empty($remise_percent)) {
4271 $remise_percent = 0;
4276 if (empty($info_bits)) {
4282 if (empty($fk_code_ventilation)) {
4283 $fk_code_ventilation = 0;
4285 if (empty($txtva)) {
4288 if (empty($txlocaltax1)) {
4291 if (empty($txlocaltax2)) {
4294 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4295 $fk_parent_line = 0;
4297 if (empty($fk_prev_id)) {
4298 $fk_prev_id =
'null';
4301 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4304 $situation_percent = 0;
4306 $situation_percent = 100;
4310 if (empty($ref_ext)) {
4314 $remise_percent = (float)
price2num($remise_percent);
4318 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4321 if (strpos((
string) $txtva,
'*') !==
false) {
4324 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4327 $txlocaltax1 = (float)
price2num($txlocaltax1);
4328 $txlocaltax2 = (float)
price2num($txlocaltax2);
4330 if ($price_base_type ==
'HT') {
4342 $langs->load(
"errors");
4343 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4349 $product_type = $type;
4350 if (!empty($fk_product) && $fk_product > 0) {
4351 $product =
new Product($this->db);
4352 $result = $product->fetch($fk_product);
4353 $product_type = $product->type;
4355 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4357 $productChildrenNb = 0;
4359 $productChildrenNb = $product->hasFatherOrChild(1);
4361 if ($productChildrenNb > 0) {
4363 $product_stock =
null;
4364 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4365 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4366 if ($product_stock ===
null) {
4367 $product_stock = $componentStockWarehouse->real;
4369 $product_stock = min($product_stock, $componentStockWarehouse->real);
4372 if ($product_stock ===
null) {
4376 $product_stock = $product->stock_reel;
4379 if ($product_stock < $qty) {
4380 $langs->load(
"errors");
4381 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4382 $this->db->rollback();
4388 $tmpproduct =
new Product($this->db);
4389 $result = $tmpproduct->fetch($fk_product);
4390 if (abs((
float) $qty) < $tmpproduct->packaging) {
4391 $qty = (float) $tmpproduct->packaging;
4392 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4394 if (!empty($tmpproduct->packaging) && (
float)
price2num(fmod((
float) $qty, (
float) $tmpproduct->packaging),
'MS')) {
4395 $coeff = intval(abs((
float) $qty) / $tmpproduct->packaging) + 1;
4396 $qty =
price2num((
float) $tmpproduct->packaging * $coeff,
'MS');
4397 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4408 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4409 $vat_src_code = $reg[1];
4410 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4417 $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);
4419 $total_ht = $tabprice[0];
4420 $total_tva = $tabprice[1];
4421 $total_ttc = $tabprice[2];
4422 $total_localtax1 = $tabprice[9];
4423 $total_localtax2 = $tabprice[10];
4424 $pu_ht = $tabprice[3];
4427 $multicurrency_total_ht = $tabprice[16];
4428 $multicurrency_total_tva = $tabprice[17];
4429 $multicurrency_total_ttc = $tabprice[18];
4430 $pu_ht_devise = $tabprice[19];
4434 if (empty($ranktouse) || $ranktouse == -1) {
4435 $rangmax = $this->
line_max($fk_parent_line);
4436 $ranktouse = $rangmax + 1;
4441 $apply_abs_price_on_credit_note =
false;
4443 $apply_abs_price_on_credit_note =
true;
4449 $this->line->context = $this->context;
4451 $this->line->fk_facture = $this->id;
4452 $this->line->label = $label;
4453 $this->line->desc = $desc;
4454 $this->line->ref_ext = $ref_ext;
4456 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : (float) $qty);
4457 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4459 $this->line->subprice_ttc = ($price_base_type ===
'TTC') ? ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ttc) : (float) $pu_ttc) : 0;
4461 $this->line->vat_src_code = $vat_src_code;
4462 $this->line->tva_tx = $txtva;
4463 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4464 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4465 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4466 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4468 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4469 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4470 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4471 $this->line->total_localtax1 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax1) : (float) $total_localtax1);
4472 $this->line->total_localtax2 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax2) : (float) $total_localtax2);
4474 $this->line->fk_product = $fk_product;
4475 $this->line->product_type = $product_type;
4476 $this->line->remise_percent = $remise_percent;
4478 $this->line->date_end = $date_end;
4479 $this->line->fk_code_ventilation = $fk_code_ventilation;
4480 $this->line->rang = $ranktouse;
4481 $this->line->info_bits = $info_bits;
4482 $this->line->fk_remise_except = $fk_remise_except;
4484 $this->line->special_code = $special_code;
4485 $this->line->fk_parent_line = $fk_parent_line;
4487 $this->line->origin = $origin;
4488 $this->line->origin_id = $origin_id;
4490 $this->line->situation_percent = $situation_percent;
4491 $this->line->fk_prev_id = $fk_prev_id;
4492 $this->line->fk_unit = $fk_unit;
4495 $this->line->fk_fournprice = $fk_fournprice;
4496 $this->line->pa_ht = $pa_ht;
4499 $this->line->fk_multicurrency = $this->fk_multicurrency;
4500 $this->line->multicurrency_code = $this->multicurrency_code;
4501 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4503 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4504 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4505 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4507 if (is_array($array_options) && count($array_options) > 0) {
4508 $this->line->array_options = $array_options;
4511 $result = $this->line->insert();
4514 if (empty($noupdateafterinsertline)) {
4518 if (!isset($this->context[
'createfromclone'])) {
4519 if (!empty($fk_parent_line)) {
4522 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4524 $linecount = count($this->lines);
4525 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4530 $this->lines[] = $this->line;
4533 foreach ($this->lines as $tmpline) {
4534 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
4535 $this->line->extraparams = $tmpline->extraparams;
4536 $this->line->setExtraParameters();
4542 $this->db->commit();
4543 return $this->line->id;
4545 $this->error = $this->db->lasterror();
4546 $this->db->rollback();
4550 $this->error = $this->line->error;
4551 $this->errors = $this->line->errors;
4552 $this->db->rollback();
4556 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4557 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4593 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)
4599 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4602 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4606 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);
4608 if ($this->
status == self::STATUS_DRAFT) {
4611 if (!$this->error) {
4612 $this->error = $langs->trans(
'invoiceLineProgressError');
4619 $langs->load(
"errors");
4620 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4630 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4631 $fk_parent_line = 0;
4633 if (empty($special_code) || $special_code == 3) {
4636 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
4639 $situation_percent = 0;
4641 $situation_percent = 100;
4644 if (empty($ref_ext)) {
4648 $remise_percent = (float)
price2num($remise_percent);
4652 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4655 if (strpos((
string) $txtva,
'*') !==
false) {
4658 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4661 $txlocaltax1 = (float)
price2num($txlocaltax1);
4662 $txlocaltax2 = (float)
price2num($txlocaltax2);
4678 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4679 $vat_src_code = $reg[1];
4680 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4683 $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);
4685 $total_ht = $tabprice[0];
4686 $total_tva = $tabprice[1];
4687 $total_ttc = $tabprice[2];
4688 $total_localtax1 = $tabprice[9];
4689 $total_localtax2 = $tabprice[10];
4690 $pu_ht = $tabprice[3];
4691 $pu_tva = $tabprice[4];
4692 $pu_ttc = $tabprice[5];
4695 $multicurrency_total_ht = $tabprice[16];
4696 $multicurrency_total_tva = $tabprice[17];
4697 $multicurrency_total_ttc = $tabprice[18];
4698 $pu_ht_devise = $tabprice[19];
4703 if ($remise_percent > 0) {
4704 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4705 $price = ((float) $pu - $remise);
4711 $line->fetch($rowid);
4712 $line->fetch_optionals();
4714 if (!empty($line->fk_product)) {
4715 $product =
new Product($this->db);
4716 $result = $product->fetch($line->fk_product);
4717 $product_type = $product->type;
4719 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4721 $productChildrenNb = 0;
4723 $productChildrenNb = $product->hasFatherOrChild(1);
4725 if ($productChildrenNb > 0) {
4727 $product_stock =
null;
4728 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4729 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4730 if ($product_stock ===
null) {
4731 $product_stock = $componentStockWarehouse->real;
4733 $product_stock = min($product_stock, $componentStockWarehouse->real);
4736 if ($product_stock ===
null) {
4740 $product_stock = $product->stock_reel;
4743 if ($product_stock < $qty) {
4744 $langs->load(
"errors");
4745 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', (
string) $product->ref);
4746 $this->db->rollback();
4752 $staticline = clone $line;
4754 $line->oldline = $staticline;
4755 $this->line = $line;
4756 $this->line->context = $this->context;
4757 $this->line->rang = $rang;
4760 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4761 $rangmax = $this->
line_max($fk_parent_line);
4762 $this->line->rang = $rangmax + 1;
4764 $apply_abs_price_on_credit_note =
false;
4766 $apply_abs_price_on_credit_note =
true;
4771 if ($qty < $this->line->packaging) {
4772 $qty = $this->line->packaging;
4773 setEventMessage($langs->trans(
'QtyRecalculatedWithPackaging'),
'warnings');
4775 if (!empty($this->line->packaging)
4776 && is_numeric($this->line->packaging)
4777 && (
float) $this->line->packaging > 0
4778 && (
float)
price2num(fmod((
float) $qty, (
float) $this->line->packaging),
'MS')) {
4779 $coeff = intval($qty / $this->line->packaging) + 1;
4780 $qty = $this->line->packaging * $coeff;
4781 setEventMessage($langs->trans(
'QtyRecalculatedWithPackaging'),
'warnings');
4786 $this->line->id = $rowid;
4787 $this->line->rowid = $rowid;
4788 $this->line->label = $label;
4789 $this->line->desc = $desc;
4790 $this->line->ref_ext = $ref_ext;
4791 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4793 $this->line->vat_src_code = $vat_src_code;
4794 $this->line->tva_tx = $txtva;
4795 $this->line->localtax1_tx = $txlocaltax1;
4796 $this->line->localtax2_tx = $txlocaltax2;
4797 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4798 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4800 $this->line->remise_percent = $remise_percent;
4801 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4803 $this->line->subprice_ttc = ($price_base_type ===
'TTC') ? ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ttc) : (float) $pu_ttc) : 0;
4805 $this->line->date_end = $date_end;
4806 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4807 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4808 $this->line->total_localtax1 = (float) $total_localtax1;
4809 $this->line->total_localtax2 = (float) $total_localtax2;
4810 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4811 $this->line->info_bits = $info_bits;
4812 $this->line->special_code = $special_code;
4813 $this->line->product_type = $type;
4814 $this->line->fk_parent_line = $fk_parent_line;
4815 $this->line->skip_update_total = $skip_update_total;
4816 $this->line->situation_percent = $situation_percent;
4817 $this->line->fk_unit = $fk_unit;
4819 $this->line->fk_fournprice = $fk_fournprice;
4820 $this->line->pa_ht = $pa_ht;
4823 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4824 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4825 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4826 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4828 if (is_array($array_options) && count($array_options) > 0) {
4830 foreach ($array_options as $key => $value) {
4831 $this->line->array_options[$key] = $array_options[$key];
4835 $result = $this->line->update($user, $notrigger);
4838 if (!empty($fk_parent_line)) {
4844 $this->db->commit();
4847 $this->error = $this->line->error;
4848 $this->db->rollback();
4852 $this->error =
"Invoice statut makes operation forbidden";
4866 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4867 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4868 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4870 $result = $this->db->query($sql);
4872 $this->error = $this->db->error();
4876 $obj = $this->db->fetch_object($result);
4878 if ($obj ===
null) {
4881 return ($situation_percent < $obj->situation_percent);
4900 if (($line->info_bits & 2) == 2) {
4904 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4907 if ($percent > 100) {
4911 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4912 $current_progress = $percent - $previous_progress;
4913 $line->situation_percent = $current_progress;
4914 $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);
4916 $line->situation_percent = $percent;
4917 $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);
4919 $line->total_ht = (float) $tabprice[0];
4920 $line->total_tva = (float) $tabprice[1];
4921 $line->total_ttc = (float) $tabprice[2];
4922 $line->total_localtax1 = (float) $tabprice[9];
4923 $line->total_localtax2 = (float) $tabprice[10];
4924 $line->multicurrency_total_ht = (float) $tabprice[16];
4925 $line->multicurrency_total_tva = (float) $tabprice[17];
4926 $line->multicurrency_total_ttc = (float) $tabprice[18];
4927 $line->update($user);
4930 if ($update_price) {
4946 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4948 if ($this->
status != self::STATUS_DRAFT) {
4949 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4955 $line->context = $this->context;
4958 $result = $line->fetch($rowid);
4959 if (!($result > 0)) {
4964 if ($id > 0 && $line->fk_facture != $id) {
4965 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4972 $staticline = clone $line;
4973 $line->oldline = $staticline;
4975 if ($line->delete($user) > 0) {
4979 $this->db->commit();
4982 $this->db->rollback();
4983 $this->error = $this->db->lasterror();
4987 $this->db->rollback();
4988 $this->error = $line->error;
5007 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
5009 return $this->
setDiscount($user, $remise, $notrigger);
5023 if (empty($remise)) {
5027 if ($user->hasRight(
'facture',
'creer')) {
5028 $remise = (float)
price2num($remise, 2);
5034 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
5035 $sql .=
" SET remise_percent = ".((float) $remise);
5036 $sql .=
" WHERE rowid = ".((int) $this->
id);
5037 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
5040 $resql = $this->db->query($sql);
5042 $this->errors[] = $this->db->error();
5046 if (!$notrigger && empty($error)) {
5048 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5056 $this->remise_percent = $remise;
5059 $this->db->commit();
5062 foreach ($this->errors as $errmsg) {
5063 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5064 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5066 $this->db->rollback();
5087 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
5088 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5101 global
$conf, $langs;
5103 if ($this->module_source ==
'takepos') {
5104 $langs->load(
'cashdesk');
5106 $moduleName =
'takepos';
5107 $moduleSourceName =
'Takepos';
5108 $addonConstName =
'TAKEPOS_REF_ADDON';
5112 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
5117 $langs->load(
'bills');
5119 $moduleName =
'facture';
5120 $moduleSourceName =
'Invoice';
5121 $addonConstName =
'FACTURE_ADDON';
5125 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5127 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5129 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
5135 if (!empty($addon)) {
5136 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
5140 $file = $addon.
'.php';
5141 $classname = $addon;
5145 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
5146 foreach ($dirmodels as $reldir) {
5147 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
5150 if (is_file($dir.$file) && is_readable($dir.$file)) {
5151 $mybool = ((bool) include_once $dir.$file) || $mybool;
5157 $file = $addon.
'/'.$addon.
'.modules.php';
5158 $classname =
'mod_'.$moduleName.
'_'.$addon;
5159 $classname = preg_replace(
'/\-.*$/',
'', $classname);
5161 foreach (
$conf->file->dol_document_root as $dirroot) {
5162 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
5165 if (is_file($dir.$file) && is_readable($dir.$file)) {
5166 $mybool = (include_once $dir.$file) || $mybool;
5176 $obj =
new $classname();
5177 '@phan-var-force ModeleNumRefFactures $obj';
5179 $numref = $obj->getNextValue($soc, $this, $mode);
5186 if ($mode !=
'last' && !$numref) {
5187 $this->error = $obj->error;
5193 $langs->load(
'errors');
5194 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5207 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5208 $sql .=
' date_closing as dateclosing,';
5209 $sql .=
' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5210 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
5211 $sql .=
' WHERE c.rowid = '.((int) $id);
5213 $result = $this->db->query($sql);
5215 if ($this->db->num_rows($result)) {
5216 $obj = $this->db->fetch_object($result);
5218 $this->
id = $obj->rowid;
5219 $this->user_creation_id = $obj->fk_user_author;
5220 $this->user_modification_id = $obj->fk_user_modif;
5221 $this->user_validation_id = $obj->fk_user_valid;
5222 $this->user_closing_id = $obj->fk_user_closing;
5224 $this->date_creation = $this->db->jdate($obj->datec);
5225 $this->date_modification = $this->db->jdate($obj->datem);
5226 $this->date_validation = $this->db->jdate($obj->datev);
5227 $this->date_closing = $this->db->jdate($obj->dateclosing);
5229 $this->db->free($result);
5250 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
5257 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
5258 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
5259 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
5260 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5261 $sql .=
" AND f.fk_soc = s.rowid";
5263 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
5265 if (is_object($excluser)) {
5266 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
5270 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5271 $search_sale = $user->id;
5274 if ($search_sale && $search_sale !=
'-1') {
5275 if ($search_sale == -2) {
5276 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5277 } elseif ($search_sale > 0) {
5278 $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).
")";
5283 $sql .=
" AND f.fk_soc = ".((int) $socid);
5285 $sql .= $this->db->order($sortfield, $sortorder);
5286 $sql .= $this->db->plimit($limit, $offset);
5288 $result = $this->db->query($sql);
5290 $numc = $this->db->num_rows($result);
5293 while ($i < $numc) {
5294 $obj = $this->db->fetch_object($result);
5296 if ($shortlist == 1) {
5297 $ga[$obj->fid] = $obj->ref;
5298 } elseif ($shortlist == 2) {
5299 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
5301 $ga[$i][
'id'] = $obj->fid;
5302 $ga[$i][
'ref'] = $obj->ref;
5303 $ga[$i][
'name'] = $obj->name;
5332 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5333 $sql .=
" ff.rowid as rowidnext";
5335 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5336 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5337 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
5338 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
5339 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5340 $sql .=
" AND f.paye = 0";
5341 $sql .=
" AND pf.fk_paiement IS NULL";
5342 $sql .=
" AND ff.fk_statut IS NULL";
5344 $sql .=
" AND f.fk_soc = ".((int) $socid);
5347 $sql .=
" ORDER BY f.ref";
5349 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
5350 $resql = $this->db->query($sql);
5352 while ($obj = $this->db->fetch_object($resql)) {
5353 $return[$obj->rowid] = array(
5354 'id' => $obj->rowid,
5356 'status' => $obj->status,
5357 'paid' => $obj->paid,
5364 $this->error = $this->db->error();
5387 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement, f.multicurrency_code";
5388 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5389 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5390 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
5391 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5392 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5396 $sql .=
" AND ff.type IS NULL";
5397 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
5401 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
5402 $sql .=
'(SELECT MAX(fs.rowid)';
5403 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
5404 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
5405 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
5406 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5408 $sql .=
" AND fs.fk_soc = ".((int) $socid);
5410 $sql .=
" GROUP BY fs.situation_cycle_ref)";
5413 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
5417 $sql .=
" AND f.fk_soc = ".((int) $socid);
5420 if (
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5421 $sql .=
" ORDER BY CASE WHEN f.rowid = ".((int)
GETPOST(
'fac_avoir')).
" THEN 0 ELSE 1 END, f.ref";
5423 $sql .= $this->db->plimit(
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5425 $sql .=
" ORDER BY f.ref";
5428 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
5429 $resql = $this->db->query($sql);
5431 while ($obj = $this->db->fetch_object($resql)) {
5433 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5436 if ($obj->fk_statut == self::STATUS_CLOSED) {
5441 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5442 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot,
'multicurrency_code' => $obj->multicurrency_code);
5448 $this->error = $this->db->error();
5464 global
$conf, $langs;
5466 $sanitizedclause =
" WHERE";
5468 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5469 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5470 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5471 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5472 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5473 $sanitizedclause =
" AND";
5475 $sql .= $sanitizedclause.
" f.paye=0";
5476 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5477 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5479 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5482 $resql = $this->db->query($sql);
5484 $langs->load(
"bills");
5487 $response->warning_delay =
getWarningDelay(
'invoice',
'client') / 60 / 60 / 24;
5488 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5489 $response->labelShort = $langs->trans(
"Unpaid");
5490 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5493 $generic_facture =
new Facture($this->db);
5495 while ($obj = $this->db->fetch_object($resql)) {
5496 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5497 $generic_facture->statut = $obj->status;
5498 $generic_facture->status = $obj->status;
5500 $response->nbtodo++;
5501 $response->total += $obj->total_ht;
5503 if ($generic_facture->hasDelay()) {
5504 $response->nbtodolate++;
5505 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5509 $this->db->free($resql);
5513 $this->error = $this->db->error();
5552 global
$conf, $langs, $user;
5556 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5561 $sql =
"SELECT rowid";
5562 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5563 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5564 $sql .= $this->db->plimit(100);
5566 $resql = $this->db->query($sql);
5568 $num_prods = $this->db->num_rows($resql);
5570 while ($i < $num_prods) {
5572 $row = $this->db->fetch_row($resql);
5573 $prodids[$i] = $row[0];
5577 if (empty($num_prods)) {
5579 $prodids[$num_prods] = 1;
5584 $this->entity =
$conf->entity;
5585 $this->
ref =
'SPECIMEN';
5586 $this->specimen = 1;
5588 $this->
date = $nownotime;
5589 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5590 $this->cond_reglement_id = 1;
5591 $this->cond_reglement_code =
'RECEP';
5593 $this->mode_reglement_id = 0;
5594 $this->mode_reglement_code =
'';
5596 $this->note_public =
'This is a comment (public)';
5597 $this->note_private =
'This is a comment (private)';
5599 $this->user_creation_id = $user->id;
5601 $this->multicurrency_tx = 1;
5602 $this->multicurrency_code =
$conf->currency;
5604 $this->fk_incoterms = 0;
5605 $this->location_incoterms =
'';
5607 $this->pos_print_counter = 0;
5608 $this->email_sent_counter = 0;
5612 if (empty($option) || $option !=
'nolines') {
5616 while ($xnbp < $nbp) {
5618 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5620 $line->subprice = 100;
5621 $line->tva_tx = 19.6;
5622 $line->localtax1_tx = 0;
5623 $line->localtax2_tx = 0;
5624 $line->remise_percent = 0;
5625 if ($xnbp == 1 && $option !=
'takepos' && $option !=
'nonegativeup') {
5626 $prodid = mt_rand(1, $num_prods);
5627 if (isset($prodids[$prodid])) {
5628 $line->fk_product = $prodids[$prodid];
5631 $line->total_ht = -100;
5632 $line->total_ttc = -119.6;
5633 $line->total_tva = -19.6;
5634 $line->multicurrency_total_ht = -200;
5635 $line->multicurrency_total_ttc = -239.2;
5636 $line->multicurrency_total_tva = -39.2;
5637 } elseif ($xnbp == 2 && $option !=
'takepos' && $option !=
'nonegativeup') {
5638 $line->subprice = -100;
5639 $line->total_ht = -100;
5640 $line->total_ttc = -119.6;
5641 $line->total_tva = -19.6;
5642 $line->remise_percent = 0;
5643 $line->multicurrency_total_ht = -200;
5644 $line->multicurrency_total_ttc = -239.2;
5645 $line->multicurrency_total_tva = -39.2;
5646 } elseif ($xnbp == 3) {
5647 $prodid = mt_rand(1, $num_prods);
5648 if (isset($prodids[$prodid])) {
5649 $line->fk_product = $prodids[$prodid];
5651 $line->total_ht = 50;
5652 $line->total_ttc = 59.8;
5653 $line->total_tva = 9.8;
5654 $line->multicurrency_total_ht = 100;
5655 $line->multicurrency_total_ttc = 119.6;
5656 $line->multicurrency_total_tva = 19.6;
5657 $line->remise_percent = 50;
5659 $prodid = mt_rand(1, $num_prods);
5660 if (isset($prodids[$prodid])) {
5661 $line->fk_product = $prodids[$prodid];
5663 $line->total_ht = 100;
5664 $line->total_ttc = 119.6;
5665 $line->total_tva = 19.6;
5666 $line->multicurrency_total_ht = 200;
5667 $line->multicurrency_total_ttc = 239.2;
5668 $line->multicurrency_total_tva = 39.2;
5669 $line->remise_percent = 0;
5672 $this->lines[$xnbp] = $line;
5675 $this->total_ht += $line->total_ht;
5676 $this->total_tva += $line->total_tva;
5677 $this->total_ttc += $line->total_ttc;
5679 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5680 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5681 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5685 $this->revenuestamp = 0;
5688 if ($option !=
'takepos') {
5690 $line->desc = $langs->trans(
"Description").
" (offered line)";
5692 $line->subprice = 100;
5693 $line->tva_tx = 19.6;
5694 $line->localtax1_tx = 0;
5695 $line->localtax2_tx = 0;
5696 $line->remise_percent = 100;
5697 $line->total_ht = 0;
5698 $line->total_ttc = 0;
5699 $line->total_tva = 0;
5700 $line->multicurrency_total_ht = 0;
5701 $line->multicurrency_total_ttc = 0;
5702 $line->multicurrency_total_tva = 0;
5703 $prodid = mt_rand(1, $num_prods);
5704 if (isset($prodids[$prodid])) {
5705 $line->fk_product = $prodids[$prodid];
5708 $this->lines[$xnbp] = $line;
5725 $this->nb = array();
5727 $sanitizedclause =
"WHERE";
5729 $sql =
"SELECT count(f.rowid) as nb";
5730 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5731 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5732 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5733 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5734 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5735 $sanitizedclause =
"AND";
5737 $sql .=
" ".$sanitizedclause.
" f.entity IN (".
getEntity(
'invoice').
")";
5739 $resql = $this->db->query($sql);
5741 while ($obj = $this->db->fetch_object($resql)) {
5742 $this->nb[
"invoices"] = $obj->nb;
5744 $this->db->free($resql);
5748 $this->error = $this->db->error();
5774 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5776 $outputlangs->loadLangs(array(
"bills",
"products"));
5780 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5782 if (!empty($this->model_pdf)) {
5783 $modele = $this->model_pdf;
5791 $modelpath =
"core/modules/facture/doc/";
5793 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5803 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5804 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5805 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5807 $resql = $this->db->query($sql);
5809 if ($this->db->num_rows($resql) > 0) {
5811 $obj = $this->db->fetch_object($resql);
5813 $ref = (int) $obj->maxsituationref;
5819 $this->db->free($resql);
5822 $this->error = $this->db->lasterror();
5823 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5837 return ($this->situation_counter == 1);
5851 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5852 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5853 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5854 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5855 $resql = $this->db->query($sql);
5857 if ($resql && $this->db->num_rows($resql) > 0) {
5858 while ($row = $this->db->fetch_object($resql)) {
5860 $situation =
new Facture($this->db);
5861 $situation->fetch($id);
5862 $res[] = $situation;
5865 $this->error = $this->db->error();
5866 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5886 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5889 $resql = $this->db->query($sql);
5891 $this->errors[] = $this->db->error();
5895 if (!$notrigger && empty($error)) {
5897 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5905 $this->db->commit();
5908 foreach ($this->errors as $errmsg) {
5909 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5910 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5912 $this->db->rollback();
5928 if (!empty($this->situation_cycle_ref)) {
5930 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5931 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5932 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5933 $resql = $this->db->query($sql);
5935 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5936 $last = $res[
'max(situation_counter)'];
5937 return ($last == $this->situation_counter);
5939 $this->error = $this->db->lasterror();
5940 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5998 $hasDelay = $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'));
5999 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
6001 $totalpaid = (float) $totalpaid;
6003 if ($totalpaid >= 0 && $retainedWarrantyAmount >= 0) {
6004 if (($totalpaid < $this->total_ttc - $retainedWarrantyAmount) && $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'))) {
6006 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now -
getWarningDelay(
'invoice',
'client'))) {
6024 return $this->situation_cycle_ref;
6037 $displayWarranty =
false;
6038 if (!empty($this->retained_warranty)) {
6039 $displayWarranty =
true;
6043 $displayWarranty =
false;
6044 if (!empty($this->situation_final)) {
6045 $displayWarranty =
true;
6048 $displayWarranty =
true;
6050 foreach ($this->lines as $i => $line) {
6051 if ($line->product_type < 2 && $line->situation_percent < 100) {
6052 $displayWarranty =
false;
6060 return $displayWarranty;
6071 if (empty($this->retained_warranty)) {
6075 $retainedWarrantyAmount = 0;
6079 $displayWarranty =
true;
6081 if (!empty($this->lines)) {
6082 foreach ($this->lines as $i => $line) {
6083 if ($line->product_type < 2 && $line->situation_percent < 100) {
6084 $displayWarranty =
false;
6090 if ($displayWarranty && !empty($this->situation_final)) {
6092 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6096 foreach ($TPreviousIncoice as &$fac) {
6097 $total2BillWT += $fac->total_ttc;
6099 $total2BillWT += $this->total_ttc;
6102 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6108 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6111 if (is_numeric($rounding) && $rounding < 0) {
6115 if (is_numeric($rounding) && $rounding > 0) {
6116 return round($retainedWarrantyAmount, $rounding);
6119 return (
float)
price2num($retainedWarrantyAmount, $rounding);
6130 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
6132 if ($this->
status >= 0) {
6133 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6134 $sql .=
" SET retained_warranty = ".((float) $value);
6135 $sql .=
' WHERE rowid='.((int) $this->
id);
6137 if ($this->db->query($sql)) {
6138 $this->retained_warranty = (float) $value;
6141 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
6142 $this->error = $this->db->error();
6146 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
6147 $this->error =
'Status of the object is incompatible '.$this->status;
6162 if (!$timestamp && $dateYmd) {
6163 $timestamp = $this->db->jdate($dateYmd);
6167 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
6168 if ($this->
status >= 0) {
6169 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6170 $sql .=
" SET retained_warranty_date_limit = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
6171 $sql .=
' WHERE rowid = '.((int) $this->
id);
6173 if ($this->db->query($sql)) {
6174 $this->retained_warranty_date_limit = $timestamp;
6177 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
6178 $this->error = $this->db->error();
6182 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6183 $this->error =
'Status of the object is incompatible '.$this->status;
6202 global
$conf, $langs, $user;
6208 $errorsMsg = array();
6210 $langs->load(
"bills");
6213 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Invoice"));
6216 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
6217 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6227 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
6228 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
6229 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
6230 $formmail =
new FormMail($this->db);
6235 $tmpinvoice =
new Facture($this->db);
6240 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
6241 if (!empty($paymentmode) && $paymentmode !=
'all') {
6242 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
6244 $sql .=
" WHERE f.paye = 0";
6245 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
6246 if ($datetouse ==
'invoicedate') {
6247 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
6249 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
6251 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
6252 if (!empty($paymentmode) && $paymentmode !=
'all') {
6253 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
6256 if ($datetouse ==
'invoicedate') {
6257 $sql .= $this->db->order(
"datef",
"ASC");
6259 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
6263 $resql = $this->db->query($sql);
6266 if ($datetouse ==
'invoicedate') {
6267 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
6269 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
6271 if (!empty($paymentmode) && $paymentmode !=
'all') {
6272 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
6274 $this->output .=
'<br>';
6277 while ($obj = $this->db->fetch_object($resql)) {
6282 $res = $tmpinvoice->fetch($obj->id);
6284 $tmpinvoice->fetch_thirdparty();
6287 if ($tmpinvoice->thirdparty->default_lang) {
6288 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6289 $outputlangs->loadLangs(array(
"main",
"bills"));
6291 $outputlangs = $langs;
6295 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
6296 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6297 $langs->load(
"errors");
6298 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
6306 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $tmpinvoice);
6311 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6314 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6320 if ($forcerecipient) {
6321 $to = array($forcerecipient);
6323 $res = $tmpinvoice->fetch_thirdparty();
6324 $recipient = $tmpinvoice->thirdparty;
6326 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
6327 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6328 foreach ($tmparraycontact as $data_email) {
6329 if (!empty($data_email[
'email'])) {
6330 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
6334 if (empty($to) && !empty($recipient->email)) {
6335 $to[] = $recipient->email;
6338 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
6342 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6349 if (!empty($arraymessage->email_from)) {
6350 $email_from = (
string) $arraymessage->email_from;
6352 if (empty($email_from)) {
6353 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6357 if (!$loopError && !empty($to)) {
6358 $to = implode(
',', $to);
6359 if (!empty($arraymessage->email_to)) {
6360 $to = $to.
','.$arraymessage->email_to;
6366 $trackid =
'inv'.$tmpinvoice->id;
6367 $sendcontext =
'standard';
6370 if (!empty($arraymessage->email_tocc)) {
6371 $email_tocc = (
string) $arraymessage->email_tocc;
6375 if (!empty($arraymessage->email_tobcc)) {
6376 $email_tobcc = (
string) $arraymessage->email_tobcc;
6383 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6384 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
6385 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6386 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
6390 $cMailFile =
new CMailFile($sendTopic, $to, $email_from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
6392 $resultsendmail = $cMailFile->sendfile();
6397 if ($resultsendmail) {
6401 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6406 $actioncomm->type_code =
'AC_OTH_AUTO';
6407 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6408 $actioncomm->contact_id = 0;
6410 $actioncomm->code =
'AC_EMAIL';
6411 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
6412 $actioncomm->note_private = $sendContent;
6413 $actioncomm->fk_project = $tmpinvoice->fk_project;
6414 $actioncomm->datep =
dol_now();
6415 $actioncomm->datef = $actioncomm->datep;
6416 $actioncomm->percentage = -1;
6417 $actioncomm->authorid = $user->id;
6418 $actioncomm->userownerid = $user->id;
6420 $actioncomm->email_msgid = $cMailFile->msgid;
6421 $actioncomm->email_subject = $sendTopic;
6422 $actioncomm->email_from = $email_from;
6423 $actioncomm->email_sender =
'';
6424 $actioncomm->email_to = $to;
6428 $actioncomm->errors_to = $errors_to;
6430 $actioncomm->elementtype =
'invoice';
6431 $actioncomm->elementid = $tmpinvoice->id;
6435 $actioncomm->create($user);
6437 $errormesg = $cMailFile->error.
' : '.$to;
6441 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6446 $actioncomm->type_code =
'AC_OTH_AUTO';
6447 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6448 $actioncomm->contact_id = 0;
6450 $actioncomm->code =
'AC_EMAIL';
6451 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
6452 $actioncomm->note_private = $errormesg;
6453 $actioncomm->fk_project = $tmpinvoice->fk_project;
6454 $actioncomm->datep =
dol_now();
6455 $actioncomm->datef = $actioncomm->datep;
6456 $actioncomm->percentage = -1;
6457 $actioncomm->authorid = $user->id;
6458 $actioncomm->userownerid = $user->id;
6460 $actioncomm->email_msgid = $cMailFile->msgid;
6461 $actioncomm->email_subject = $sendTopic;
6462 $actioncomm->email_from = $email_from;
6463 $actioncomm->email_sender =
'';
6464 $actioncomm->email_to = $to;
6468 $actioncomm->errors_to = $errors_to;
6470 $actioncomm->elementtype =
'invoice';
6471 $actioncomm->elementid = $tmpinvoice->id;
6475 $actioncomm->create($user);
6478 $this->db->commit();
6482 $errorsMsg[] = $errormesg;
6485 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6489 $error += $loopError;
6496 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6498 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6502 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6504 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6519 $sql =
"SELECT datef";
6520 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6521 $sql .=
" WHERE type = " . (int) $this->
type ;
6522 $sql .=
" AND date_valid IS NOT NULL";
6523 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6524 $sql .=
" ORDER BY datef DESC LIMIT 1";
6526 $result = $this->db->query($sql);
6529 if ($this->db->num_rows($result)) {
6530 $obj = $this->db->fetch_object($result);
6531 $last_date = $this->db->jdate($obj->datef);
6532 $invoice_date = $this->date;
6534 $is_last_of_same_type = $invoice_date >= $last_date;
6535 if ($allow_validated_drafts) {
6539 return array($is_last_of_same_type, $last_date);
6562 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6564 $picto = $this->picto;
6565 if ($this->
type == self::TYPE_REPLACEMENT) {
6568 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6571 if ($this->
type == self::TYPE_DEPOSIT) {
6575 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6576 $return .=
'<div class="info-box info-box-sm">';
6577 $return .=
'<span class="info-box-icon bg-infobox-action">';
6579 $return .=
'</span>';
6580 $return .=
'<div class="info-box-content">';
6581 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6582 if ($selected >= 0) {
6583 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6585 if (!empty($arraydata[
'thirdparty'])) {
6586 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6588 if (property_exists($this,
'date')) {
6589 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->
date,
'day').
'</span>';
6591 if (property_exists($this,
'total_ht')) {
6592 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6593 $return .=
' '.$langs->trans(
"HT");
6594 $return .=
'</span>';
6596 if (method_exists($this,
'getLibStatut')) {
6597 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6598 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6600 $return .=
'</div>';
6601 $return .=
'</div>';
6602 $return .=
'</div>';
if(! $sortfield) if(! $sortorder) $object
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
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.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
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
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...
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.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
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.
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.
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 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_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
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.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
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.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
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.
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.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
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
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.