46require_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
47require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/factureligne.class.php';
48require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
49require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
50require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
51require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
53if (isModEnabled(
'accounting')) {
54 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
56if (isModEnabled(
'accounting')) {
57 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
68 public $element =
'facture';
73 public $table_element =
'facture';
78 public $table_element_line =
'facturedet';
83 public $fk_element =
'fk_facture';
88 public $picto =
'bill';
94 public $restrictiononfksoc = 1;
105 public $fk_user_author;
111 public $fk_user_valid;
117 public $fk_user_modif;
127 public $delivery_date;
139 public $ref_customer;
152 public $total_localtax1;
156 public $total_localtax2;
164 public $revenuestamp;
181 public $module_source;
189 public $fk_fac_rec_source;
193 public $fk_facture_source;
194 public $linked_objects = array();
204 public $lines = array();
213 public $extraparams = array();
223 public $date_pointoftax;
229 public $situation_cycle_ref;
234 public $situation_counter;
239 public $situation_final;
244 public $tab_previous_situation_invoice = array();
249 public $tab_next_situation_invoice = array();
259 public $retained_warranty;
264 public $retained_warranty_date_limit;
269 public $retained_warranty_fk_cond_reglement;
274 public $availability_id;
279 public $date_closing;
290 public $remise_percent;
295 public $online_payment_url;
327 public $fields = array(
328 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 1),
329 'ref' => array(
'type' =>
'varchar(30)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'position' => 5),
330 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 20,
'index' => 1),
331 'ref_client' => array(
'type' =>
'varchar(255)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 10),
332 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'Ref ext',
'enabled' => 1,
'visible' => 0,
'position' => 12),
333 'type' => array(
'type' =>
'smallint(6)',
'label' =>
'Type',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
334 'subtype' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoiceSubtype',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
336 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 50),
337 'datef' => array(
'type' =>
'date',
'label' =>
'DateInvoice',
'enabled' => 1,
'visible' => 1,
'position' => 20),
338 'date_valid' => array(
'type' =>
'date',
'label' =>
'DateValidation',
'enabled' => 1,
'visible' => -1,
'position' => 22),
339 'date_lim_reglement' => array(
'type' =>
'date',
'label' =>
'DateDue',
'enabled' => 1,
'visible' => 1,
'position' => 25),
340 'date_closing' => array(
'type' =>
'datetime',
'label' =>
'DateClosing',
'enabled' => 1,
'visible' => -1,
'position' => 30),
341 'paye' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoicePaidCompletely',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 80),
346 'close_code' => array(
'type' =>
'varchar(16)',
'label' =>
'EarlyClosingReason',
'enabled' => 1,
'visible' => -1,
'position' => 92),
347 'close_note' => array(
'type' =>
'varchar(128)',
'label' =>
'EarlyClosingComment',
'enabled' => 1,
'visible' => -1,
'position' => 93),
348 'total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountHT',
'enabled' => 1,
'visible' => 1,
'position' => 95,
'isameasure' => 1),
349 'total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountVAT',
'enabled' => 1,
'visible' => -1,
'position' => 100,
'isameasure' => 1),
350 'localtax1' => array(
'type' =>
'double(24,8)',
'label' =>
'LT1',
'enabled' => 1,
'visible' => -1,
'position' => 110,
'isameasure' => 1),
351 'localtax2' => array(
'type' =>
'double(24,8)',
'label' =>
'LT2',
'enabled' => 1,
'visible' => -1,
'position' => 120,
'isameasure' => 1),
352 'revenuestamp' => array(
'type' =>
'double(24,8)',
'label' =>
'RevenueStamp',
'enabled' => 1,
'visible' => -1,
'position' => 115,
'isameasure' => 1),
353 'total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountTTC',
'enabled' => 1,
'visible' => 1,
'position' => 130,
'isameasure' => 1),
354 'fk_facture_source' => array(
'type' =>
'integer',
'label' =>
'SourceInvoice',
'enabled' => 1,
'visible' => -1,
'position' => 170),
355 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' => 1,
'visible' => -1,
'position' => 175),
356 'fk_account' => array(
'type' =>
'integer',
'label' =>
'Fk account',
'enabled' => 1,
'visible' => -1,
'position' => 180),
357 'fk_currency' => array(
'type' =>
'varchar(3)',
'label' =>
'CurrencyCode',
'enabled' => 1,
'visible' => -1,
'position' => 185),
358 'fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentTerm',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 190),
359 'fk_mode_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentMode',
'enabled' => 1,
'visible' => -1,
'position' => 195),
360 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 205),
361 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 210),
362 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 215),
363 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 225),
364 'situation_cycle_ref' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation cycle ref',
'enabled' =>
'$conf->global->INVOICE_USE_SITUATION',
'visible' => -1,
'position' => 230),
365 'situation_counter' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation counter',
'enabled' =>
'$conf->global->INVOICE_USE_SITUATION',
'visible' => -1,
'position' => 235),
366 'situation_final' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation final',
'enabled' =>
'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1',
'visible' => -1,
'position' => 240),
367 'retained_warranty' => array(
'type' =>
'double',
'label' =>
'Retained warranty',
'enabled' =>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible' => -1,
'position' => 245),
368 'retained_warranty_date_limit' => array(
'type' =>
'date',
'label' =>
'Retained warranty date limit',
'enabled' =>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible' => -1,
'position' => 250),
369 'retained_warranty_fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'Retained warranty fk cond reglement',
'enabled' =>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible' => -1,
'position' => 255),
370 'fk_incoterms' => array(
'type' =>
'integer',
'label' =>
'IncotermCode',
'enabled' =>
'$conf->incoterm->enabled',
'visible' => -1,
'position' => 260),
371 'location_incoterms' => array(
'type' =>
'varchar(255)',
'label' =>
'IncotermLabel',
'enabled' =>
'$conf->incoterm->enabled',
'visible' => -1,
'position' => 265),
372 'date_pointoftax' => array(
'type' =>
'date',
'label' =>
'DatePointOfTax',
'enabled' =>
'$conf->global->INVOICE_POINTOFTAX_DATE',
'visible' => -1,
'position' => 270),
373 'fk_multicurrency' => array(
'type' =>
'integer',
'label' =>
'MulticurrencyID',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 275),
374 'multicurrency_code' => array(
'type' =>
'varchar(255)',
'label' =>
'Currency',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 280),
375 'multicurrency_tx' => array(
'type' =>
'double(24,8)',
'label' =>
'CurrencyRate',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 285,
'isameasure' => 1),
376 'multicurrency_total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountHT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 290,
'isameasure' => 1),
377 'multicurrency_total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountVAT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 291,
'isameasure' => 1),
378 'multicurrency_total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountTTC',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 292,
'isameasure' => 1),
379 'fk_fac_rec_source' => array(
'type' =>
'integer',
'label' =>
'RecurringInvoiceSource',
'enabled' => 1,
'visible' => -1,
'position' => 305),
380 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'LastMainDoc',
'enabled' => 1,
'visible' => -1,
'position' => 310),
381 'module_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSModule',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 315),
382 'pos_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSTerminal',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 320),
383 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 500),
384 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModificationShort',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 502),
385 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'position' => 506),
386 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModification',
'enabled' => 1,
'visible' => -1,
'notnull' => -1,
'position' => 508),
387 'fk_user_valid' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserValidation',
'enabled' => 1,
'visible' => -1,
'position' => 510),
388 'fk_user_closing' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserClosing',
'enabled' => 1,
'visible' => -1,
'position' => 512),
389 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 900),
390 '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')),
452 const CLOSECODE_DISCOUNTVAT =
'discount_vat';
453 const CLOSECODE_BADDEBT =
'badcustomer';
454 const CLOSECODE_BANKCHARGE =
'bankcharge';
455 const CLOSECODE_OTHER =
'other';
457 const CLOSECODE_ABANDONED =
'abandon';
458 const CLOSECODE_REPLACED =
'replaced';
470 $this->ismultientitymanaged = 1;
471 $this->isextrafieldmanaged = 1;
484 public function create(
User $user, $notrigger = 0, $forceduedate = 0)
486 global $langs, $conf, $mysoc, $hookmanager;
488 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
490 if (empty($this->
type)) {
494 $this->ref_client = trim($this->ref_client);
496 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
497 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
498 $this->note_public = trim($this->note_public);
499 if (!$this->cond_reglement_id) {
500 $this->cond_reglement_id = 0;
502 if (!$this->mode_reglement_id) {
503 $this->mode_reglement_id = 0;
508 if (!empty($this->multicurrency_code)) {
510 if (empty($this->multicurrency_tx)) {
518 $this->fk_multicurrency = 0;
520 if (empty($this->fk_multicurrency)) {
521 $this->multicurrency_code = $conf->currency;
522 $this->fk_multicurrency = 0;
523 $this->multicurrency_tx = 1;
526 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
529 if (empty($this->date)) {
530 $this->error =
"Try to create an invoice with an empty parameter (date)";
531 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
535 $result = $soc->fetch($this->socid);
537 $this->error =
"Failed to fetch company: ".$soc->error;
538 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
543 $this->date_creation = $now;
547 $originaldatewhen =
null;
548 $nextdatewhen =
null;
549 $previousdaynextdatewhen =
null;
554 if ($this->fac_rec > 0) {
555 $this->fk_fac_rec_source = $this->fac_rec;
557 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
559 $result = $_facrec->fetch($this->fac_rec);
560 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
564 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
568 $originaldatewhen = $_facrec->date_when;
569 $nextdatewhen =
null;
570 $previousdaynextdatewhen =
null;
571 if ($originaldatewhen) {
572 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
576 if (!empty($_facrec->frequency)) {
577 $this->socid = $_facrec->socid;
579 $this->entity = $_facrec->entity;
584 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
585 $this->note_public = GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
586 $this->note_private = GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
587 $this->model_pdf = GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
588 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
589 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
590 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
593 $this->total_ht = $_facrec->total_ht;
594 $this->total_ttc = $_facrec->total_ttc;
599 $this->fk_incoterms = $_facrec->fk_incoterms;
600 $this->location_incoterms = $_facrec->location_incoterms;
606 $this->ref_client = trim($this->ref_client);
607 $this->ref_customer = trim($this->ref_customer);
608 $this->note_public = trim($this->note_public);
609 $this->note_private = trim($this->note_private);
610 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
612 $this->array_options = $_facrec->array_options;
614 if (!$this->mode_reglement_id) {
615 $this->mode_reglement_id = 0;
620 $this->linked_objects = $_facrec->linkedObjectsIds;
625 if ($_facrec->frequency > 0) {
626 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
627 if (empty($_facrec->date_when)) {
628 $_facrec->date_when = $now;
630 $next_date = $_facrec->getNextDate();
631 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
633 $result = $_facrec->setNextDate($next_date, 1);
637 $outputlangs = $langs;
640 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
641 $newlang = $this->thirdparty->default_lang;
644 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
645 $newlang = $this->default_lang;
647 if (!empty($newlang)) {
649 $outputlangs->setDefaultLang($newlang);
655 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
658 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
661 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
664 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
665 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
666 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
667 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
668 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
679 if (empty($forceduedate)) {
685 $this->date_lim_reglement = $duedate;
687 $this->date_lim_reglement = $forceduedate;
691 $socid = $this->socid;
693 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
702 $sql .=
", date_pointoftax";
703 $sql .=
", note_private";
704 $sql .=
", note_public";
705 $sql .=
", ref_client";
706 $sql .=
", fk_account";
707 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
708 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
709 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
710 $sql .=
", fk_incoterms, location_incoterms";
711 $sql .=
", fk_multicurrency";
712 $sql .=
", multicurrency_code";
713 $sql .=
", multicurrency_tx";
714 $sql .=
", retained_warranty";
715 $sql .=
", retained_warranty_date_limit";
716 $sql .=
", retained_warranty_fk_cond_reglement";
720 $sql .=
", ".setEntity($this);
721 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
722 $sql .=
", '".$this->db->escape($this->
type).
"'";
723 $sql .=
", ".($this->subtype ?
"'".$this->db->escape($this->subtype).
"'" :
"null");
724 $sql .=
", ".((int) $socid);
725 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
726 $sql .=
", '".$this->db->idate($this->date).
"'";
727 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
728 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
729 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
730 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
731 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
732 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
733 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape($this->pos_source).
"'" :
"null");
734 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape($this->fk_fac_rec_source).
"'" :
"null");
735 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape($this->fk_facture_source).
"'" :
"null");
736 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
737 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
738 $sql .=
", ".((int) $this->cond_reglement_id);
739 $sql .=
", ".((int) $this->mode_reglement_id);
740 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
741 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
742 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape($this->situation_cycle_ref).
"'" :
"null");
743 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape($this->situation_counter).
"'" :
"null");
744 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
745 $sql .=
", ".(int) $this->fk_incoterms;
746 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
747 $sql .=
", ".(int) $this->fk_multicurrency;
748 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
749 $sql .=
", ".(float) $this->multicurrency_tx;
750 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape($this->retained_warranty));
751 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
752 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
755 $resql = $this->db->query($sql);
757 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
760 $this->
ref =
'(PROV'.$this->id.
')';
761 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
763 $resql = $this->db->query($sql);
768 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
769 $this->linked_objects = $this->linkedObjectsIds;
773 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
774 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
775 if (is_array($tmp_origin_id)) {
776 foreach ($tmp_origin_id as $origin_id) {
779 $this->error = $this->db->lasterror();
784 $origin_id = $tmp_origin_id;
787 $this->error = $this->db->lasterror();
795 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) {
796 $originforcontact = $this->origin;
797 $originidforcontact = $this->origin_id;
798 if ($originforcontact ==
'shipping') {
799 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
801 $exp->fetch($this->origin_id);
802 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
803 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
804 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
805 $originforcontact =
'commande';
806 if (is_object($value)) {
807 $originidforcontact = $value->id;
809 $originidforcontact = $value;
816 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
817 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
819 $resqlcontact = $this->db->query($sqlcontact);
821 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
823 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
833 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
836 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
837 foreach ($this->lines as $i => $val) {
838 $newinvoiceline = $this->lines[$i];
839 '@phan-var-force FactureLigne $newinvoiceline';
841 $newinvoiceline->context = $this->context;
843 $newinvoiceline->fk_facture = $this->id;
845 $newinvoiceline->origin = $this->lines[$i]->element;
846 $newinvoiceline->origin_id = $this->lines[$i]->id;
849 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
850 $newinvoiceline->date_start = $originaldatewhen;
852 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
853 $newinvoiceline->date_end = $previousdaynextdatewhen;
858 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
863 $vatrate = $newinvoiceline->tva_tx;
864 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
865 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
868 $newinvoiceline->fk_parent_line = $fk_parent_line;
872 $discount->fetch($newinvoiceline->fk_remise_except);
874 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
875 $newinvoiceline->fk_remise_except = $discountId;
879 $newinvoiceline->desc,
880 $newinvoiceline->subprice,
881 $newinvoiceline->qty,
883 $newinvoiceline->localtax1_tx,
884 $newinvoiceline->localtax2_tx,
885 $newinvoiceline->fk_product,
886 $newinvoiceline->remise_percent,
887 $newinvoiceline->date_start,
888 $newinvoiceline->date_end,
889 $newinvoiceline->fk_code_ventilation,
890 $newinvoiceline->info_bits,
891 $newinvoiceline->fk_remise_except,
894 $newinvoiceline->product_type,
895 $newinvoiceline->rang,
896 $newinvoiceline->special_code,
897 $newinvoiceline->element,
900 $newinvoiceline->fk_fournprice,
901 $newinvoiceline->pa_ht,
902 $newinvoiceline->label,
903 $newinvoiceline->array_options,
904 $newinvoiceline->situation_percent,
905 $newinvoiceline->fk_prev_id,
906 $newinvoiceline->fk_unit,
907 $newinvoiceline->multicurrency_subprice,
908 $newinvoiceline->ref_ext,
913 if ($result > 0 && $newinvoiceline->product_type == 9) {
914 $fk_parent_line = $result;
918 $this->error = $newinvoiceline->error;
919 $this->errors = $newinvoiceline->errors;
924 } elseif (!$error && empty($this->fac_rec)) {
927 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
929 foreach ($this->lines as $i => $val) {
930 $line = $this->lines[$i];
931 '@phan-var-force FactureLigne $line';
935 if (!is_object($line)) {
936 $line = (object) $line;
941 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
946 $vatrate = $line->tva_tx;
947 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
948 $vatrate .=
' ('.$line->vat_src_code.
')';
952 $originid = $line->origin_id;
953 $origintype = $line->origin;
955 $originid = $line->id;
956 $origintype = $this->element;
960 if (empty($line->ref_ext)) {
972 $line->remise_percent,
975 $line->fk_code_ventilation,
977 $line->fk_remise_except,
986 $line->fk_fournprice,
989 $line->array_options,
990 $line->situation_percent,
993 $line->multicurrency_subprice,
998 $this->error = $this->db->lasterror();
1000 $this->db->rollback();
1005 if ($result > 0 && $line->product_type == 9) {
1006 $fk_parent_line = $result;
1015 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1016 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1017 $fk_parent_line = 0;
1019 foreach ($_facrec->lines as $i => $val) {
1020 if ($_facrec->lines[$i]->fk_product) {
1021 $prod =
new Product($this->db);
1022 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
1026 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1027 $fk_parent_line = 0;
1038 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1039 $tva_npr = $_facrec->lines[$i]->info_bits;
1040 if (empty($tva_tx)) {
1043 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1044 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1046 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1047 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1050 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1051 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1053 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1058 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1059 $buyprice = $producttmp->cost_price;
1061 $buyprice = $producttmp->pmp;
1063 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1064 if ($producttmp->product_fourn_price_id > 0) {
1065 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1071 $result_insert = $this->
addline(
1072 $_facrec->lines[$i]->desc,
1073 $_facrec->lines[$i]->subprice,
1074 $_facrec->lines[$i]->qty,
1078 $_facrec->lines[$i]->fk_product,
1079 $_facrec->lines[$i]->remise_percent,
1080 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1081 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1087 $_facrec->lines[$i]->product_type,
1088 $_facrec->lines[$i]->rang,
1089 $_facrec->lines[$i]->special_code,
1093 $fk_product_fournisseur_price,
1095 $_facrec->lines[$i]->label,
1096 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1099 $_facrec->lines[$i]->fk_unit,
1100 $_facrec->lines[$i]->multicurrency_subprice,
1101 $_facrec->lines[$i]->ref_ext,
1106 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1107 $fk_parent_line = $result_insert;
1110 if ($result_insert < 0) {
1112 $this->error = $this->db->error();
1131 if (!$error && !$notrigger) {
1140 $this->db->commit();
1143 $this->db->rollback();
1147 $this->error = $langs->trans(
'FailedToUpdatePrice');
1148 $this->db->rollback();
1152 dol_syslog(get_class($this).
"::create error ".$this->error, LOG_ERR);
1153 $this->db->rollback();
1157 $this->error = $this->db->error();
1158 $this->db->rollback();
1174 $facture =
new Facture($this->db);
1180 if (!empty($this->array_options)) {
1181 $facture->array_options = $this->array_options;
1184 foreach ($this->lines as &$line) {
1185 $line->fetch_optionals();
1188 $facture->fk_facture_source = $this->fk_facture_source;
1189 $facture->type = $this->type;
1190 $facture->subtype = $this->subtype;
1191 $facture->socid = $this->socid;
1192 $facture->date = $this->date;
1193 $facture->date_pointoftax = $this->date_pointoftax;
1194 $facture->note_public = $this->note_public;
1195 $facture->note_private = $this->note_private;
1196 $facture->ref_client = $this->ref_client;
1197 $facture->ref_customer = $this->ref_customer;
1198 $facture->model_pdf = $this->model_pdf;
1199 $facture->fk_project = $this->fk_project;
1200 $facture->cond_reglement_id = $this->cond_reglement_id;
1201 $facture->mode_reglement_id = $this->mode_reglement_id;
1205 $facture->origin = $this->origin;
1206 $facture->origin_id = $this->origin_id;
1207 $facture->fk_account = $this->fk_account;
1209 $facture->lines = $this->lines;
1210 $facture->situation_counter = $this->situation_counter;
1211 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1212 $facture->situation_final = $this->situation_final;
1214 $facture->retained_warranty = $this->retained_warranty;
1215 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1216 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1218 $facture->fk_user_author = $user->id;
1219 $facture->user_creation_id = $user->id;
1223 foreach ($facture->lines as $i => $tmpline) {
1224 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1225 if ($invertdetail) {
1226 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1227 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1228 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1229 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1230 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1231 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1232 $facture->lines[$i]->ref_ext =
'';
1236 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1238 $facid = $facture->create($user);
1240 $this->error = $facture->error;
1241 $this->errors = $facture->errors;
1245 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1246 foreach ($Tfk_object as $fk_object) {
1247 $facture->add_object_linked($typeObject, $fk_object);
1251 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1267 global $conf, $hookmanager;
1281 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1282 $objsoc =
new Societe($this->db);
1284 if ($objsoc->fetch($this->socid) > 0) {
1286 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1287 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1289 $object->fk_delivery_address = 0;
1301 $object->user_creation_id = $user->id;
1302 $object->user_validation_id =
null;
1303 $object->fk_user_author = $user->id;
1304 $object->fk_user_valid =
null;
1305 $object->fk_facture_source = 0;
1307 $object->date_modification =
'';
1308 $object->date_validation =
'';
1318 foreach (
$object->lines as $i => $line) {
1319 '@phan-var-force FactureLigne $line';
1320 if (($line->info_bits & 0x02) == 0x02) {
1327 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1339 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1340 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1344 $object->lines[$i]->date_start = $newFirst;
1345 $object->lines[$i]->date_end = $newLast;
1349 $object->lines[$i]->ref_ext =
'';
1353 $object->context[
'createfromclone'] =
'createfromclone';
1354 $result =
$object->create($user);
1357 $this->error =
$object->error;
1358 $this->errors =
$object->errors;
1361 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1363 $this->error =
$object->error;
1364 $this->errors =
$object->errors;
1365 } elseif (
$object->socid == $objFrom->socid) {
1367 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1369 $this->error =
$object->error;
1370 $this->errors =
$object->errors;
1377 if (is_object($hookmanager)) {
1378 $parameters = array(
'objFrom' => $objFrom);
1380 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1388 unset(
$object->context[
'createfromclone']);
1392 $this->db->commit();
1395 $this->db->rollback();
1409 global $conf, $hookmanager;
1418 for ($i = 0; $i < $num; $i++) {
1420 $src_line =
$object->lines[$i];
1421 '@phan-var-force FactureLigne $src_line';
1422 $line->libelle = $src_line->libelle;
1423 $line->label = $src_line->label;
1424 $line->desc = $src_line->desc;
1425 $line->subprice = $src_line->subprice;
1426 $line->total_ht = $src_line->total_ht;
1427 $line->total_tva = $src_line->total_tva;
1428 $line->total_localtax1 = $src_line->total_localtax1;
1429 $line->total_localtax2 = $src_line->total_localtax2;
1430 $line->total_ttc = $src_line->total_ttc;
1431 $line->vat_src_code = $src_line->vat_src_code;
1432 $line->tva_tx = $src_line->tva_tx;
1433 $line->localtax1_tx = $src_line->localtax1_tx;
1434 $line->localtax2_tx = $src_line->localtax2_tx;
1435 $line->qty = $src_line->qty;
1436 $line->fk_remise_except = $src_line->fk_remise_except;
1437 $line->remise_percent = $src_line->remise_percent;
1438 $line->fk_product = $src_line->fk_product;
1439 $line->info_bits = $src_line->info_bits;
1440 $line->product_type = $src_line->product_type;
1441 $line->rang = $src_line->rang;
1442 $line->special_code = $src_line->special_code;
1443 $line->fk_parent_line = $src_line->fk_parent_line;
1444 $line->fk_unit = $src_line->fk_unit;
1445 $line->date_start = $src_line->date_start;
1446 $line->date_end = $src_line->date_end;
1449 $line->fk_multicurrency = $src_line->fk_multicurrency;
1450 $line->multicurrency_code = $src_line->multicurrency_code;
1451 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1452 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1453 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1454 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1456 $line->fk_fournprice = $src_line->fk_fournprice;
1457 $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);
1458 $line->pa_ht = $marginInfos[0];
1461 $src_line->fetch_optionals();
1462 foreach ($src_line->array_options as $options_key => $value) {
1463 $line->array_options[$options_key] = $value;
1466 $this->lines[$i] = $line;
1469 $this->socid =
$object->socid;
1470 $this->fk_project =
$object->fk_project;
1471 $this->fk_account =
$object->fk_account;
1472 $this->cond_reglement_id =
$object->cond_reglement_id;
1473 $this->mode_reglement_id =
$object->mode_reglement_id;
1474 $this->availability_id =
$object->availability_id;
1475 $this->demand_reason_id =
$object->demand_reason_id;
1476 $this->delivery_date =
$object->delivery_date;
1477 $this->fk_delivery_address =
$object->fk_delivery_address;
1478 $this->contact_id =
$object->contact_id;
1479 $this->ref_client =
$object->ref_client;
1482 $this->note_private =
$object->note_private;
1483 $this->note_public =
$object->note_public;
1486 $this->module_source =
$object->module_source;
1487 $this->pos_source =
$object->pos_source;
1489 $this->origin =
$object->element;
1490 $this->origin_id =
$object->id;
1492 $this->fk_user_author = $user->id;
1496 foreach (
$object->array_options as $options_key => $value) {
1497 $this->array_options[$options_key] = $value;
1501 $this->linked_objects[$this->origin] = $this->origin_id;
1502 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1503 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1506 $ret = $this->
create($user);
1510 $hookmanager->initHooks(array(
'invoicedao'));
1512 $parameters = array(
'objFrom' =>
$object);
1514 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1540 global $conf, $hookmanager;
1548 $use_all_lines = empty($lines);
1550 for ($i = 0; $i < $num; $i++) {
1551 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1557 $line->libelle =
$object->lines[$i]->libelle;
1558 $line->label =
$object->lines[$i]->label;
1559 $line->desc =
$object->lines[$i]->desc;
1560 $line->subprice =
$object->lines[$i]->subprice;
1561 $line->total_ht =
$object->lines[$i]->total_ht;
1562 $line->total_tva =
$object->lines[$i]->total_tva;
1563 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1564 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1565 $line->total_ttc =
$object->lines[$i]->total_ttc;
1566 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1567 $line->tva_tx =
$object->lines[$i]->tva_tx;
1568 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1569 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1570 $line->qty =
$object->lines[$i]->qty;
1571 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1572 $line->remise_percent =
$object->lines[$i]->remise_percent;
1573 $line->fk_product =
$object->lines[$i]->fk_product;
1574 $line->info_bits =
$object->lines[$i]->info_bits;
1575 $line->product_type =
$object->lines[$i]->product_type;
1576 $line->rang =
$object->lines[$i]->rang;
1577 $line->special_code =
$object->lines[$i]->special_code;
1578 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1579 $line->fk_unit =
$object->lines[$i]->fk_unit;
1580 $line->date_start =
$object->lines[$i]->date_start;
1581 $line->date_end =
$object->lines[$i]->date_end;
1584 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1585 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1586 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1587 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1588 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1589 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1591 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1593 $line->pa_ht = $marginInfos[0];
1596 $object->lines[$i]->fetch_optionals();
1597 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1598 $line->array_options[$options_key] = $value;
1601 $this->lines[$i] = $line;
1604 $this->socid =
$object->socid;
1605 $this->fk_project =
$object->fk_project;
1606 $this->fk_account =
$object->fk_account;
1607 $this->cond_reglement_id =
$object->cond_reglement_id;
1608 $this->mode_reglement_id =
$object->mode_reglement_id;
1609 $this->availability_id =
$object->availability_id;
1610 $this->demand_reason_id =
$object->demand_reason_id;
1611 $this->delivery_date =
$object->delivery_date;
1612 $this->fk_delivery_address =
$object->fk_delivery_address;
1613 $this->contact_id =
$object->contact_id;
1614 $this->ref_client =
$object->ref_client;
1617 $this->note_private =
$object->note_private;
1618 $this->note_public =
$object->note_public;
1621 $this->module_source =
$object->module_source;
1622 $this->pos_source =
$object->pos_source;
1624 $this->origin =
$object->element;
1625 $this->origin_id =
$object->id;
1627 $this->fk_user_author = $user->id;
1631 foreach (
$object->array_options as $options_key => $value) {
1632 $this->array_options[$options_key] = $value;
1636 $this->linked_objects[$this->origin] = $this->origin_id;
1637 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1638 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1641 $ret = $this->
create($user);
1645 $hookmanager->initHooks(array(
'invoicedao'));
1647 $parameters = array(
'objFrom' =>
$object);
1649 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1679 global $conf, $langs, $hookmanager, $action;
1681 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1682 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1687 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1691 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1694 $origin->error =
'ErrorDateIsInFuture';
1698 if ($payment_terms_id <= 0) {
1699 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1703 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1705 if (empty($payment_conditions_deposit_percent)) {
1706 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1710 if (empty($origin->deposit_percent)) {
1711 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1715 $deposit =
new self($origin->db);
1716 $deposit->socid = $origin->socid;
1718 $deposit->fk_project = $origin->fk_project;
1719 $deposit->ref_client = $origin->ref_client;
1720 $deposit->date = $date;
1721 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1722 $deposit->cond_reglement_id = $payment_terms_id;
1723 $deposit->availability_id = $origin->availability_id;
1724 $deposit->demand_reason_id = $origin->demand_reason_id;
1725 $deposit->fk_account = $origin->fk_account;
1726 $deposit->fk_incoterms = $origin->fk_incoterms;
1727 $deposit->location_incoterms = $origin->location_incoterms;
1728 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1729 $deposit->multicurrency_code = $origin->multicurrency_code;
1730 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1731 $deposit->module_source = $origin->module_source;
1732 $deposit->pos_source = $origin->pos_source;
1733 $deposit->model_pdf =
'crabe';
1735 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1744 $deposit->note_private = $origin->note_private;
1745 $deposit->note_public = $origin->note_public;
1748 $deposit->origin = $origin->element;
1749 $deposit->origin_id = $origin->id;
1751 $origin->fetch_optionals();
1753 foreach ($origin->array_options as $extrakey => $value) {
1754 $deposit->array_options[$extrakey] = $value;
1757 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1759 foreach ($overrideFields as $key => $value) {
1760 $deposit->$key = $value;
1763 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1765 $origin->db->begin();
1768 $createReturn = $deposit->create($user, $notrigger);
1770 if ($createReturn <= 0) {
1771 $origin->db->rollback();
1772 $origin->error = $deposit->error;
1773 $origin->errors = $deposit->errors;
1777 $amount_ttc_diff = 0;
1778 $amountdeposit = array();
1779 $descriptions = array();
1782 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1784 $TTotalByTva = array();
1785 foreach ($origin->lines as &$line) {
1786 if (!empty($line->special_code)) {
1789 $key = $line->tva_tx;
1790 if (!array_key_exists($key, $TTotalByTva)) {
1791 $TTotalByTva[$key] = 0;
1792 $descriptions[$key] =
'';
1794 $TTotalByTva[$key] += $line->total_ttc;
1795 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1796 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1797 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1798 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1801 foreach ($TTotalByTva as $tva => &$total) {
1802 $coef = $total / $origin->total_ttc;
1803 $am = $amount * $coef;
1804 $amount_ttc_diff += $am;
1805 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1809 $lines = $origin->lines;
1810 $numlines = count($lines);
1811 for ($i = 0; $i < $numlines; $i++) {
1812 if (empty($lines[$i]->qty)) {
1815 if (!empty($lines[$i]->special_code)) {
1819 $totalamount += $lines[$i]->total_ht;
1820 $tva_tx = $lines[$i]->tva_tx;
1821 $amountdeposit[$tva_tx] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1822 $descriptions[$tva_tx] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1823 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1824 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1825 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1828 if ($totalamount == 0) {
1829 $amountdeposit[0] = 0;
1832 $amount_ttc_diff = $amountdeposit[0];
1835 foreach ($amountdeposit as $tva => $amount) {
1836 if (empty($amount)) {
1840 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1843 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1844 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1847 $addlineResult = $deposit->addline(
1854 (!
getDolGlobalString(
'INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1874 if ($addlineResult < 0) {
1875 $origin->db->rollback();
1876 $origin->error = $deposit->error;
1877 $origin->errors = $deposit->errors;
1882 $diff = $deposit->total_ttc - $amount_ttc_diff;
1885 $deposit->fetch_lines();
1886 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1888 $updatelineResult = $deposit->updateline(
1889 $deposit->lines[0]->id,
1890 $deposit->lines[0]->desc,
1892 $deposit->lines[0]->qty,
1893 $deposit->lines[0]->remise_percent,
1894 $deposit->lines[0]->date_start,
1895 $deposit->lines[0]->date_end,
1896 $deposit->lines[0]->tva_tx,
1900 $deposit->lines[0]->info_bits,
1901 $deposit->lines[0]->product_type,
1905 $deposit->lines[0]->pa_ht,
1906 $deposit->lines[0]->label,
1912 if ($updatelineResult < 0) {
1913 $origin->db->rollback();
1914 $origin->error = $deposit->error;
1915 $origin->errors = $deposit->errors;
1920 $hookmanager->initHooks(array(
'invoicedao'));
1922 $parameters = array(
'objFrom' => $origin);
1923 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1926 $origin->db->rollback();
1927 $origin->error = $hookmanager->error;
1928 $origin->errors = $hookmanager->errors;
1932 if (!empty($autoValidateDeposit)) {
1933 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1935 if ($validateReturn < 0) {
1936 $origin->db->rollback();
1937 $origin->error = $deposit->error;
1938 $origin->errors = $deposit->errors;
1943 unset($deposit->context[
'createdepositfromorigin']);
1945 $origin->db->commit();
1959 global $conf, $langs, $mysoc, $user;
1961 $langs->load(
'bills');
1964 $moretitle = $params[
'moretitle'] ??
'';
1966 $picto = $this->picto;
1967 if ($this->
type == self::TYPE_REPLACEMENT) {
1970 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1973 if ($this->
type == self::TYPE_DEPOSIT) {
1977 if ($user->hasRight(
"facture",
"read")) {
1978 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1980 $datas[
'picto'] .=
' '.$this->getLibType(1);
1983 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
1986 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
1989 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
1992 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
1993 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
1996 $datas[
'picto'] .=
' - '.$moretitle;
1998 if (!empty($this->
ref)) {
1999 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2001 if (!empty($this->ref_customer)) {
2002 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
2004 if (!empty($this->date)) {
2005 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
2007 if (!empty($this->total_ht)) {
2008 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
2010 if (!empty($this->total_tva)) {
2011 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
2013 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2014 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
2016 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2018 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
2020 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2021 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
2023 if (!empty($this->total_ttc)) {
2024 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
2045 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2047 global $langs, $conf, $user;
2049 if (!empty($conf->dol_no_mouse_hover)) {
2055 if ($option ==
'withdraw') {
2056 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2058 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2061 if (!$user->hasRight(
"facture",
"read")) {
2065 if ($option !==
'nolink') {
2067 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2068 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2069 $add_save_lastsearch_values = 1;
2071 if ($add_save_lastsearch_values) {
2072 $url .=
'&save_lastsearch_values=1';
2080 $picto = $this->picto;
2081 if ($this->
type == self::TYPE_REPLACEMENT) {
2084 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2087 if ($this->
type == self::TYPE_DEPOSIT) {
2093 'objecttype' => $this->element,
2094 'moretitle' => $moretitle,
2095 'option' => $option,
2097 $classfortooltip =
'classfortooltip';
2100 $classfortooltip =
'classforajaxtooltip';
2101 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2107 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2108 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2110 $label = $langs->trans(
"Invoice");
2111 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
2113 $linkclose .= ($label ?
' title="'.dol_escape_htmltag($label, 1).
'"' :
' title="tocomplete"');
2114 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2117 $linkstart =
'<a href="'.$url.
'"';
2118 $linkstart .= $linkclose.
'>';
2121 if ($option ==
'nolink') {
2126 $result .= $linkstart;
2128 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2130 if ($withpicto != 2) {
2131 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2133 $result .= $linkend;
2135 if ($addlinktonotes) {
2136 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2139 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2140 $result .=
' <span class="note inline-block">';
2141 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
2146 $result .=
'</span>';
2150 global $action, $hookmanager;
2151 $hookmanager->initHooks(array(
'invoicedao'));
2152 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2153 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2155 $result = $hookmanager->resPrint;
2157 $result .= $hookmanager->resPrint;
2173 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2175 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2179 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2180 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2181 $sql .=
', f.datef as df, f.date_pointoftax';
2182 $sql .=
', f.date_lim_reglement as dlr';
2183 $sql .=
', f.datec as datec';
2184 $sql .=
', f.date_valid as datev';
2185 $sql .=
', f.tms as datem';
2186 $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';
2187 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2188 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2189 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2190 $sql .=
', f.fk_account';
2191 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2192 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2193 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2194 $sql .=
', f.fk_incoterms, f.location_incoterms';
2195 $sql .=
', f.module_source, f.pos_source';
2196 $sql .=
", i.libelle as label_incoterms";
2197 $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";
2198 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
2199 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2200 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
2201 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2204 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2206 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2208 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2211 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2215 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2216 $resql = $this->db->query($sql);
2218 if ($this->db->num_rows($resql)) {
2219 $obj = $this->db->fetch_object($resql);
2221 $this->
id = $obj->rowid;
2222 $this->entity = $obj->entity;
2224 $this->
ref = $obj->ref;
2225 $this->ref_client = $obj->ref_client;
2226 $this->ref_customer = $obj->ref_client;
2227 $this->ref_ext = $obj->ref_ext;
2228 $this->
type = $obj->type;
2229 $this->subtype = $obj->subtype;
2230 $this->date = $this->db->jdate($obj->df);
2231 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2232 $this->date_creation = $this->db->jdate($obj->datec);
2233 $this->date_validation = $this->db->jdate($obj->datev);
2234 $this->date_modification = $this->db->jdate($obj->datem);
2235 $this->datem = $this->db->jdate($obj->datem);
2236 $this->total_ht = $obj->total_ht;
2237 $this->total_tva = $obj->total_tva;
2238 $this->total_localtax1 = $obj->localtax1;
2239 $this->total_localtax2 = $obj->localtax2;
2240 $this->total_ttc = $obj->total_ttc;
2241 $this->revenuestamp = $obj->revenuestamp;
2242 $this->paye = $obj->paye;
2243 $this->close_code = $obj->close_code;
2244 $this->close_note = $obj->close_note;
2246 $this->socid = $obj->fk_soc;
2247 $this->thirdparty =
null;
2249 $this->fk_project = $obj->fk_project;
2250 $this->project =
null;
2252 $this->statut = $obj->status;
2253 $this->
status = $obj->status;
2255 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2256 $this->mode_reglement_id = $obj->fk_mode_reglement;
2257 $this->mode_reglement_code = $obj->mode_reglement_code;
2258 $this->mode_reglement = $obj->mode_reglement_libelle;
2259 $this->cond_reglement_id = $obj->fk_cond_reglement;
2260 $this->cond_reglement_code = $obj->cond_reglement_code;
2261 $this->cond_reglement = $obj->cond_reglement_libelle;
2262 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2263 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2264 $this->fk_facture_source = $obj->fk_facture_source;
2265 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2266 $this->note = $obj->note_private;
2267 $this->note_private = $obj->note_private;
2268 $this->note_public = $obj->note_public;
2269 $this->user_creation_id = $obj->fk_user_author;
2270 $this->user_validation_id = $obj->fk_user_valid;
2271 $this->user_modification_id = $obj->fk_user_modif;
2272 $this->fk_user_author = $obj->fk_user_author;
2273 $this->fk_user_valid = $obj->fk_user_valid;
2274 $this->fk_user_modif = $obj->fk_user_modif;
2275 $this->model_pdf = $obj->model_pdf;
2276 $this->last_main_doc = $obj->last_main_doc;
2277 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2278 $this->situation_counter = $obj->situation_counter;
2279 $this->situation_final = $obj->situation_final;
2280 $this->retained_warranty = $obj->retained_warranty;
2281 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2282 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2284 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2287 $this->fk_incoterms = $obj->fk_incoterms;
2288 $this->location_incoterms = $obj->location_incoterms;
2289 $this->label_incoterms = $obj->label_incoterms;
2291 $this->module_source = $obj->module_source;
2292 $this->pos_source = $obj->pos_source;
2295 $this->fk_multicurrency = $obj->fk_multicurrency;
2296 $this->multicurrency_code = $obj->multicurrency_code;
2297 $this->multicurrency_tx = $obj->multicurrency_tx;
2298 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2299 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2300 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2302 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2311 $this->lines = array();
2315 $this->error = $this->db->error();
2319 $this->db->free($resql);
2323 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2325 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2329 $this->error = $this->db->lasterror();
2344 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2347 $this->lines = array();
2349 $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,';
2350 $sql .=
' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.ref_ext,';
2351 $sql .=
' l.situation_percent, l.fk_prev_id,';
2352 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2353 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2354 $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,';
2355 $sql .=
' l.fk_unit,';
2356 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2357 $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';
2358 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2359 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2360 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2361 $sql .=
' ORDER BY l.rang, l.rowid';
2363 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2364 $result = $this->db->query($sql);
2366 $num = $this->db->num_rows($result);
2369 $objp = $this->db->fetch_object($result);
2372 $line->id = $objp->rowid;
2373 $line->rowid = $objp->rowid;
2374 $line->fk_facture = $objp->fk_facture;
2375 $line->label = $objp->custom_label;
2376 $line->desc = $objp->description;
2377 $line->description = $objp->description;
2378 $line->product_type = $objp->product_type;
2379 $line->ref = $objp->product_ref;
2380 $line->product_ref = $objp->product_ref;
2381 $line->libelle = $objp->product_label;
2382 $line->product_label = $objp->product_label;
2383 $line->product_barcode = $objp->product_barcode;
2384 $line->product_desc = $objp->product_desc;
2385 $line->fk_product_type = $objp->fk_product_type;
2386 $line->qty = $objp->qty;
2387 $line->subprice = $objp->subprice;
2388 $line->ref_ext = $objp->ref_ext;
2390 $line->vat_src_code = $objp->vat_src_code;
2391 $line->tva_tx = $objp->tva_tx;
2392 $line->localtax1_tx = $objp->localtax1_tx;
2393 $line->localtax2_tx = $objp->localtax2_tx;
2394 $line->localtax1_type = $objp->localtax1_type;
2395 $line->localtax2_type = $objp->localtax2_type;
2396 $line->remise_percent = $objp->remise_percent;
2397 $line->fk_remise_except = $objp->fk_remise_except;
2398 $line->fk_product = $objp->fk_product;
2399 $line->date_start = $this->db->jdate($objp->date_start);
2400 $line->date_end = $this->db->jdate($objp->date_end);
2401 $line->info_bits = $objp->info_bits;
2402 $line->total_ht = $objp->total_ht;
2403 $line->total_tva = $objp->total_tva;
2404 $line->total_localtax1 = $objp->total_localtax1;
2405 $line->total_localtax2 = $objp->total_localtax2;
2406 $line->total_ttc = $objp->total_ttc;
2408 $line->fk_fournprice = $objp->fk_fournprice;
2409 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2410 $line->pa_ht = $marginInfos[0];
2411 $line->marge_tx = $marginInfos[1];
2412 $line->marque_tx = $marginInfos[2];
2413 $line->rang = $objp->rang;
2414 $line->special_code = $objp->special_code;
2415 $line->fk_parent_line = $objp->fk_parent_line;
2416 $line->situation_percent = $objp->situation_percent;
2417 $line->fk_prev_id = $objp->fk_prev_id;
2418 $line->fk_unit = $objp->fk_unit;
2420 $line->batch = $objp->batch;
2421 $line->fk_warehouse = $objp->fk_warehouse;
2424 $line->fk_accounting_account = $objp->fk_code_ventilation;
2427 $line->fk_multicurrency = $objp->fk_multicurrency;
2428 $line->multicurrency_code = $objp->multicurrency_code;
2429 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2430 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2431 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2432 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2434 $line->fetch_optionals();
2437 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2438 $tmpproduct =
new Product($this->db);
2439 $tmpproduct->fetch($objp->fk_product);
2440 $tmpproduct->getMultiLangs();
2442 $line->multilangs = $tmpproduct->multilangs;
2445 $this->lines[$i] = $line;
2449 $this->db->free($result);
2452 $this->error = $this->db->error();
2467 $this->tab_previous_situation_invoice = array();
2468 $this->tab_next_situation_invoice = array();
2470 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2471 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2472 $sql .=
' AND entity = '.((int) $this->entity);
2473 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2474 $sql .=
' ORDER BY situation_counter ASC';
2476 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2477 $result = $this->db->query($sql);
2478 if ($result && $this->db->num_rows($result) > 0) {
2479 while ($objp = $this->db->fetch_object($result)) {
2480 $invoice =
new Facture($this->db);
2481 if ($invoice->fetch($objp->rowid) > 0) {
2482 if ($objp->situation_counter < $this->situation_counter
2483 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2485 $this->tab_previous_situation_invoice[] = $invoice;
2487 $this->tab_next_situation_invoice[] = $invoice;
2506 if (empty($this->
type)) {
2509 if (isset($this->subtype)) {
2510 $this->subtype = (int) trim((
string) $this->subtype);
2512 if (isset($this->
ref)) {
2513 $this->
ref = trim($this->
ref);
2515 if (isset($this->ref_ext)) {
2516 $this->ref_ext = trim($this->ref_ext);
2518 if (isset($this->ref_client)) {
2519 $this->ref_client = trim($this->ref_client);
2521 if (isset($this->increment)) {
2522 $this->increment = trim($this->increment);
2524 if (isset($this->close_code)) {
2525 $this->close_code = trim($this->close_code);
2527 if (isset($this->close_note)) {
2528 $this->close_note = trim($this->close_note);
2530 if (isset($this->note) || isset($this->note_private)) {
2531 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2533 if (isset($this->note) || isset($this->note_private)) {
2534 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2536 if (isset($this->note_public)) {
2537 $this->note_public = trim($this->note_public);
2539 if (isset($this->model_pdf)) {
2540 $this->model_pdf = trim($this->model_pdf);
2542 if (isset($this->import_key)) {
2543 $this->import_key = trim($this->import_key);
2545 if (isset($this->retained_warranty)) {
2546 $this->retained_warranty = (float) $this->retained_warranty;
2554 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2555 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2556 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2557 $sql .=
" type=".(isset($this->
type) ? $this->db->escape($this->
type) :
"null").
",";
2558 $sql .=
" subtype=".(isset($this->subtype) ? $this->db->escape($this->subtype) :
"null").
",";
2559 $sql .=
" ref_client=".(isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null").
",";
2560 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2561 $sql .=
" fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) :
"null").
",";
2562 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2563 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2564 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2565 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2566 $sql .=
" paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).
",";
2567 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2568 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2569 $sql .=
" total_tva=".(isset($this->total_tva) ? (float) $this->total_tva :
"null").
",";
2570 $sql .=
" localtax1=".(isset($this->total_localtax1) ? (float) $this->total_localtax1 :
"null").
",";
2571 $sql .=
" localtax2=".(isset($this->total_localtax2) ? (float) $this->total_localtax2 :
"null").
",";
2572 $sql .=
" total_ht=".(isset($this->total_ht) ? (float) $this->total_ht :
"null").
",";
2573 $sql .=
" total_ttc=".(isset($this->total_ttc) ? (float) $this->total_ttc :
"null").
",";
2574 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
int) $this->revenuestamp :
"null").
",";
2575 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2576 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? (int) $this->fk_user_valid :
"null").
",";
2577 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2578 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2579 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2580 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2581 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2582 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2583 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2584 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2585 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2586 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2587 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2588 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2589 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2590 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2591 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2592 $sql .=
" WHERE rowid=".((int) $this->
id);
2596 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2597 $resql = $this->db->query($sql);
2600 $this->errors[] =
"Error ".$this->db->lasterror();
2610 if (!$error && !$notrigger) {
2621 foreach ($this->errors as $errmsg) {
2622 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2623 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2625 $this->db->rollback();
2628 $this->db->commit();
2646 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2647 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2652 $result = $remise->fetch($idremise);
2655 if ($remise->fk_facture) {
2656 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2657 $this->db->rollback();
2662 $facligne->fk_facture = $this->id;
2663 $facligne->fk_remise_except = $remise->id;
2664 $facligne->desc = $remise->description;
2665 $facligne->vat_src_code = $remise->vat_src_code;
2666 $facligne->tva_tx = $remise->tva_tx;
2667 $facligne->subprice = -(float) $remise->amount_ht;
2668 $facligne->fk_product = 0;
2670 $facligne->remise_percent = 0;
2671 $facligne->rang = -1;
2672 $facligne->info_bits = 2;
2675 $facligne->rang = 1;
2676 $linecount = count($this->lines);
2677 for ($ii = 1; $ii <= $linecount; $ii++) {
2683 if ($remise->fk_facture_source > 0) {
2684 $srcinvoice =
new Facture($this->db);
2685 $srcinvoice->fetch($remise->fk_facture_source);
2686 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2688 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2689 $facligne->pa_ht = $arraytmp[
'pa_total'];
2692 $facligne->total_ht = -(float) $remise->amount_ht;
2693 $facligne->total_tva = -(float) $remise->amount_tva;
2694 $facligne->total_ttc = -(float) $remise->amount_ttc;
2696 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2697 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_amount_ht;
2698 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_amount_tva;
2699 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_amount_ttc;
2701 $lineid = $facligne->insert();
2706 $result = $remise->link_to_invoice($lineid, 0);
2708 $this->error = $remise->error;
2709 $this->db->rollback();
2713 $this->db->commit();
2716 $this->error = $facligne->error;
2717 $this->db->rollback();
2721 $this->error = $facligne->error;
2722 $this->db->rollback();
2726 $this->db->rollback();
2748 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2749 if (empty($ref_client)) {
2750 $sql .=
' SET ref_client = NULL';
2752 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2754 $sql .=
" WHERE rowid = ".((int) $this->
id);
2756 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2757 $resql = $this->db->query($sql);
2759 $this->errors[] = $this->db->error();
2764 $this->ref_client = $ref_client;
2767 if (!$notrigger && empty($error)) {
2777 $this->ref_client = $ref_client;
2779 $this->db->commit();
2782 foreach ($this->errors as $errmsg) {
2783 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2784 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2786 $this->db->rollback();
2799 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2801 global $langs, $conf;
2802 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2806 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2819 if (!$error && !$notrigger) {
2833 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2847 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2848 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2849 $sql .=
' AND fk_facture_line IS NULL';
2850 $resql = $this->db->query($sql);
2854 $list_rowid_det = array();
2855 foreach ($this->lines as $key => $invoiceline) {
2856 $list_rowid_det[] = $invoiceline->id;
2860 if (count($list_rowid_det)) {
2861 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2862 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2863 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
2865 if (!$this->db->query($sql)) {
2866 $this->error = $this->db->error().
" sql=".$sql;
2867 $this->errors[] = $this->error;
2868 $this->db->rollback();
2875 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2876 $sql .=
' SET fk_invoice = NULL';
2877 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2879 if (!$this->db->query($sql)) {
2880 $this->error = $this->db->error().
" sql=".$sql;
2881 $this->errors[] = $this->error;
2882 $this->db->rollback();
2886 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
2887 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2888 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2890 if (!$this->db->query($sql)) {
2891 $this->error = $this->db->error().
" sql=".$sql;
2892 $this->errors[] = $this->error;
2893 $this->db->rollback();
2898 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
2899 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2900 $langs->load(
"agenda");
2902 $num = count($this->lines);
2903 for ($i = 0; $i < $num; $i++) {
2904 if ($this->lines[$i]->fk_product > 0) {
2906 $mouvP->origin = &$this;
2907 $mouvP->setOrigin($this->element, $this->
id);
2909 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2910 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2912 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2919 $main = MAIN_DB_PREFIX.
'facturedet';
2920 $ef = $main.
"_extrafields";
2921 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2923 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2926 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2928 $resql = $this->db->query($sql);
2936 if ($conf->facture->dir_output && !empty($this->
ref)) {
2937 $dir = $conf->facture->dir_output.
"/".$ref;
2938 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2939 if (file_exists($file)) {
2943 $langs->load(
"errors");
2944 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2945 $this->errors[] = $this->error;
2946 $this->db->rollback();
2950 if (file_exists($dir)) {
2952 $langs->load(
"errors");
2953 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2954 $this->errors[] = $this->error;
2955 $this->db->rollback();
2961 $this->db->commit();
2964 $this->error = $this->db->lasterror().
" sql=".$sql;
2965 $this->errors[] = $this->error;
2966 $this->db->rollback();
2970 $this->error = $this->db->lasterror().
" sql=".$sql;
2971 $this->errors[] = $this->error;
2972 $this->db->rollback();
2976 $this->db->rollback();
2993 public function set_paid($user, $close_code =
'', $close_note =
'')
2996 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2997 return $this->
setPaid($user, $close_code, $close_note);
3010 public function setPaid($user, $close_code =
'', $close_note =
'')
3014 if ($this->paye != 1) {
3019 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3021 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3022 $sql .=
' fk_statut='.self::STATUS_CLOSED;
3027 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3030 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3032 $sql .=
', fk_user_closing = '.((int) $user->id);
3033 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3034 $sql .=
" WHERE rowid = ".((int) $this->
id);
3036 $resql = $this->db->query($sql);
3046 $this->error = $this->db->lasterror();
3050 $this->db->commit();
3053 $this->db->rollback();
3076 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3094 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3095 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3096 $sql .=
' date_closing=null,';
3097 $sql .=
' fk_user_closing=null';
3098 $sql .=
" WHERE rowid = ".((int) $this->
id);
3100 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3101 $resql = $this->db->query($sql);
3111 $this->error = $this->db->error();
3116 $this->db->commit();
3119 $this->db->rollback();
3141 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3142 return $this->
setCanceled($user, $close_code, $close_note);
3155 public function setCanceled($user, $close_code =
'', $close_note =
'')
3157 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3162 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3163 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3165 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3168 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3170 $sql .=
', fk_user_closing = '.((int) $user->id);
3171 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3172 $sql .=
" WHERE rowid = ".((int) $this->
id);
3174 $resql = $this->db->query($sql);
3178 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3179 $sql .=
' SET fk_facture = NULL';
3180 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3182 $resql = $this->db->query($sql);
3187 $this->db->rollback();
3192 $this->db->commit();
3195 $this->error = $this->db->error().
" sql=".$sql;
3196 $this->db->rollback();
3200 $this->error = $this->db->error().
" sql=".$sql;
3201 $this->db->rollback();
3217 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3219 global $conf, $langs, $mysoc;
3220 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3222 $productStatic =
null;
3223 $warehouseStatic =
null;
3224 $productbatch =
null;
3225 if ($batch_rule > 0) {
3226 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3227 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3228 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3229 $productStatic =
new Product($this->db);
3230 $warehouseStatic =
new Entrepot($this->db);
3237 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3244 if ($this->
status != self::STATUS_DRAFT) {
3245 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3248 if (count($this->lines) <= 0) {
3249 $langs->load(
"errors");
3250 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3254 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3255 $this->error =
'Permission denied';
3256 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3259 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3267 if (!$last_of_type[0]) {
3268 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3274 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3275 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3276 foreach ($array_to_check as $key) {
3277 $keymin = strtolower($key);
3278 if (!property_exists($this->thirdparty, $keymin)) {
3281 $vallabel = $this->thirdparty->$keymin;
3283 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3285 if ($this->thirdparty->isACompany()) {
3287 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3288 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3290 $langs->load(
"errors");
3291 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3292 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3298 if ($key ==
'EMAIL') {
3301 $langs->load(
"errors");
3302 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3303 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3307 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3309 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3310 $langs->load(
"errors");
3311 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3312 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3321 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3322 foreach ($array_to_check as $key => $val) {
3323 $keymin = strtolower($key);
3324 $vallabel = $this->$keymin;
3327 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3329 $langs->load(
"errors");
3331 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3338 if ($this->
type == self::TYPE_REPLACEMENT) {
3340 if ($this->fk_facture_source <= 0) {
3341 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3342 $this->db->rollback();
3347 $facreplaced =
new Facture($this->db);
3348 $result = $facreplaced->fetch($this->fk_facture_source);
3350 $this->error = $langs->trans(
"ErrorBadInvoice");
3351 $this->db->rollback();
3356 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3357 if ($idreplacement && $idreplacement != $this->
id) {
3358 $facreplacement =
new Facture($this->db);
3359 $facreplacement->fetch($idreplacement);
3360 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3361 $this->db->rollback();
3365 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3367 $this->error = $facreplaced->error;
3368 $this->db->rollback();
3374 if ($force_number) {
3375 $num = $force_number;
3376 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3392 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3393 $sql .=
" SET ref = '".$this->db->escape($num).
"', fk_statut = ".self::STATUS_VALIDATED.
", fk_user_valid = ".($user->id > 0 ? $user->id :
"null").
", date_valid = '".$this->db->idate($now).
"'";
3395 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3396 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3398 $sql .=
" WHERE rowid = ".((int) $this->
id);
3400 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3401 $resql = $this->db->query($sql);
3403 $this->error = $this->db->lasterror();
3416 $result = $this->thirdparty->setAsCustomer();
3419 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3420 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3421 $langs->load(
"agenda");
3424 $cpt = count($this->lines);
3425 for ($i = 0; $i < $cpt; $i++) {
3426 if ($this->lines[$i]->fk_product > 0) {
3428 $mouvP->origin = &$this;
3429 $mouvP->setOrigin($this->element, $this->
id);
3432 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3435 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3438 $this->error = $mouvP->error;
3439 $this->errors = array_merge($this->errors, $mouvP->errors);
3445 $is_batch_line =
false;
3446 if ($batch_rule > 0) {
3447 $productStatic->fetch($this->lines[$i]->fk_product);
3448 if ($productStatic->hasbatch() && is_object($productbatch)) {
3449 $is_batch_line =
true;
3450 $product_qty_remain = $this->lines[$i]->qty;
3456 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3457 $sortorder =
'ASC,ASC,ASC,ASC';
3460 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_ALLOW_NEGATIVE_TRANSFER') ?
null : 0), $sortfield, $sortorder);
3461 if (!is_array($resBatchList)) {
3463 $this->error = $this->db->lasterror();
3467 $batchList = $resBatchList;
3468 if (empty($batchList)) {
3470 $langs->load(
'errors');
3471 $warehouseStatic->fetch($idwarehouse);
3472 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3473 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3476 foreach ($batchList as $batch) {
3477 if ($batch->qty <= 0) {
3482 if ($batch->qty >= $product_qty_remain) {
3483 $product_batch_qty = $product_qty_remain;
3486 $product_batch_qty = $batch->qty;
3488 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3491 $this->error = $mouvP->error;
3492 $this->errors = array_merge($this->errors, $mouvP->errors);
3496 $product_qty_remain -= $product_batch_qty;
3498 if ($product_qty_remain <= 0) {
3503 if (!$error && $product_qty_remain > 0) {
3506 $batch = $batchList[0];
3507 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3510 $this->error = $mouvP->error;
3511 $this->errors = array_merge($this->errors, $mouvP->errors);
3515 $langs->load(
'errors');
3516 $warehouseStatic->fetch($idwarehouse);
3517 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3518 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3525 if (!$is_batch_line) {
3526 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3529 $this->error = $mouvP->error;
3530 $this->errors = array_merge($this->errors, $mouvP->errors);
3543 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3544 $invoice_situation =
new Facture($this->db);
3545 $result = $invoice_situation->fetch($this->fk_facture_source);
3546 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3547 $invoice_situation->situation_final = 0;
3549 $result = $invoice_situation->setFinal($user, 1);
3552 $this->error = $invoice_situation->error;
3553 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3559 if (!$error && !$notrigger) {
3569 $this->oldref = $this->ref;
3572 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3574 $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).
"'";
3575 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
3576 $resql = $this->db->query($sql);
3579 $this->error = $this->db->lasterror();
3581 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3582 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
3583 $resql = $this->db->query($sql);
3586 $this->error = $this->db->lasterror();
3592 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3593 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3594 if (!$error && file_exists($dirsource)) {
3595 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3597 if (@rename($dirsource, $dirdest)) {
3600 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3601 foreach ($listoffiles as $fileentry) {
3602 $dirsource = $fileentry[
'name'];
3603 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3604 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3605 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3606 @rename($dirsource, $dirdest);
3624 $this->date_validation = $now;
3629 $nboflines = count($this->lines);
3630 while (($i < $nboflines) && $final) {
3631 $line = $this->lines[$i];
3632 '@phan-var-force FactureLigne $line';
3634 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3635 $current_progress = (float) $line->situation_percent;
3636 $full_progress = $previousprogress + $current_progress;
3637 $final = ($full_progress == 100);
3639 $final = ($line->situation_percent == 100);
3644 if (empty($final)) {
3645 $this->situation_final = 0;
3647 $this->situation_final = 1;
3658 $this->db->commit();
3661 $this->db->rollback();
3674 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3675 $is_last = $next_invoice->is_last_in_cycle();
3677 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
3678 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3682 foreach ($next_invoice->lines as $line) {
3683 '@phan-var-force FactureLigne $line';
3684 $result = $next_invoice->updateline(
3689 $line->remise_percent,
3693 $line->localtax1_tx,
3694 $line->localtax2_tx,
3697 $line->product_type,
3698 $line->fk_parent_line,
3700 $line->fk_fournprice,
3703 $line->special_code,
3704 $line->array_options,
3705 $line->situation_percent,
3710 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3731 global $conf, $langs;
3735 if ($this->
status == self::STATUS_DRAFT) {
3736 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3744 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3745 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3746 $sql .=
" WHERE rowid = ".((int) $this->
id);
3748 $result = $this->db->query($sql);
3751 $this->oldcopy = clone $this;
3755 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL')) {
3756 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3757 $langs->load(
"agenda");
3759 $num = count($this->lines);
3760 for ($i = 0; $i < $num; $i++) {
3761 if ($this->lines[$i]->fk_product > 0) {
3763 $mouvP->origin = &$this;
3764 $mouvP->setOrigin($this->element, $this->
id);
3766 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3767 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3769 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3776 $old_statut = $this->status;
3781 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3784 $this->statut = $old_statut;
3785 $this->
status = $old_statut;
3789 $this->db->rollback();
3794 $this->db->commit();
3797 $this->db->rollback();
3801 $this->error = $this->db->error();
3802 $this->db->rollback();
3857 $remise_percent = 0,
3860 $fk_code_ventilation = 0,
3862 $fk_remise_except = 0,
3863 $price_base_type =
'HT',
3870 $fk_parent_line = 0,
3871 $fk_fournprice =
null,
3874 $array_options = array(),
3875 $situation_percent = 100,
3880 $noupdateafterinsertline = 0
3884 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3888 global $mysoc, $conf, $langs;
3890 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);
3892 if ($this->
status == self::STATUS_DRAFT) {
3893 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3896 if (empty($remise_percent)) {
3897 $remise_percent = 0;
3902 if (empty($info_bits)) {
3908 if (empty($fk_code_ventilation)) {
3909 $fk_code_ventilation = 0;
3911 if (empty($txtva)) {
3914 if (empty($txlocaltax1)) {
3917 if (empty($txlocaltax2)) {
3920 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3921 $fk_parent_line = 0;
3923 if (empty($fk_prev_id)) {
3924 $fk_prev_id =
'null';
3926 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3927 $situation_percent = 100;
3929 if (empty($ref_ext)) {
3933 $remise_percent = (float)
price2num($remise_percent);
3936 $pu_ht_devise =
price2num($pu_ht_devise);
3939 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
3945 if ($price_base_type ==
'HT') {
3956 if ($date_start && $date_end && $date_start > $date_end) {
3957 $langs->load(
"errors");
3958 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3964 $product_type = $type;
3965 if (!empty($fk_product) && $fk_product > 0) {
3966 $product =
new Product($this->db);
3967 $result = $product->fetch($fk_product);
3968 $product_type = $product->type;
3970 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
3971 $langs->load(
"errors");
3972 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3973 $this->db->rollback();
3983 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3984 $vat_src_code = $reg[1];
3985 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3993 $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);
3995 $total_ht = $tabprice[0];
3996 $total_tva = $tabprice[1];
3997 $total_ttc = $tabprice[2];
3998 $total_localtax1 = $tabprice[9];
3999 $total_localtax2 = $tabprice[10];
4000 $pu_ht = $tabprice[3];
4003 $multicurrency_total_ht = $tabprice[16];
4004 $multicurrency_total_tva = $tabprice[17];
4005 $multicurrency_total_ttc = $tabprice[18];
4006 $pu_ht_devise = $tabprice[19];
4010 if ($ranktouse == -1) {
4011 $rangmax = $this->
line_max($fk_parent_line);
4012 $ranktouse = $rangmax + 1;
4018 $this->line->context = $this->context;
4020 $this->line->fk_facture = $this->id;
4021 $this->line->label = $label;
4022 $this->line->desc = $desc;
4023 $this->line->ref_ext = $ref_ext;
4025 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4026 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
4028 $this->line->vat_src_code = $vat_src_code;
4029 $this->line->tva_tx = $txtva;
4030 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4031 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4032 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4033 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4035 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
4036 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
4037 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
4038 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
4039 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
4041 $this->line->fk_product = $fk_product;
4042 $this->line->product_type = $product_type;
4043 $this->line->remise_percent = $remise_percent;
4044 $this->line->date_start = $date_start;
4045 $this->line->date_end = $date_end;
4046 $this->line->fk_code_ventilation = $fk_code_ventilation;
4047 $this->line->rang = $ranktouse;
4048 $this->line->info_bits = $info_bits;
4049 $this->line->fk_remise_except = $fk_remise_except;
4051 $this->line->special_code = $special_code;
4052 $this->line->fk_parent_line = $fk_parent_line;
4053 $this->line->origin = $origin;
4054 $this->line->origin_id = $origin_id;
4055 $this->line->situation_percent = $situation_percent;
4056 $this->line->fk_prev_id = $fk_prev_id;
4057 $this->line->fk_unit = $fk_unit;
4060 $this->line->fk_fournprice = $fk_fournprice;
4061 $this->line->pa_ht = $pa_ht;
4064 $this->line->fk_multicurrency = $this->fk_multicurrency;
4065 $this->line->multicurrency_code = $this->multicurrency_code;
4066 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
4068 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
4069 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
4070 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4072 if (is_array($array_options) && count($array_options) > 0) {
4073 $this->line->array_options = $array_options;
4076 $result = $this->line->insert();
4079 if (!empty($fk_parent_line)) {
4081 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4082 $linecount = count($this->lines);
4083 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4089 if (empty($noupdateafterinsertline)) {
4094 $this->db->commit();
4095 return $this->line->id;
4097 $this->error = $this->db->lasterror();
4098 $this->db->rollback();
4102 $this->error = $this->line->error;
4103 $this->errors = $this->line->errors;
4104 $this->db->rollback();
4108 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4109 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4145 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)
4151 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4154 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4156 global $mysoc, $langs;
4158 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);
4160 if ($this->
status == self::STATUS_DRAFT) {
4163 if (!$this->error) {
4164 $this->error = $langs->trans(
'invoiceLineProgressError');
4170 if ($date_start && $date_end && $date_start > $date_end) {
4171 $langs->load(
"errors");
4172 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4182 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4183 $fk_parent_line = 0;
4185 if (empty($special_code) || $special_code == 3) {
4188 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4189 $situation_percent = 100;
4191 if (empty($ref_ext)) {
4195 $remise_percent = (float)
price2num($remise_percent);
4198 $pu_ht_devise =
price2num($pu_ht_devise);
4200 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4203 $txlocaltax1 = (float)
price2num($txlocaltax1);
4204 $txlocaltax2 = (float)
price2num($txlocaltax2);
4220 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4221 $vat_src_code = $reg[1];
4222 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4225 $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);
4227 $total_ht = $tabprice[0];
4228 $total_tva = $tabprice[1];
4229 $total_ttc = $tabprice[2];
4230 $total_localtax1 = $tabprice[9];
4231 $total_localtax2 = $tabprice[10];
4232 $pu_ht = $tabprice[3];
4233 $pu_tva = $tabprice[4];
4234 $pu_ttc = $tabprice[5];
4237 $multicurrency_total_ht = $tabprice[16];
4238 $multicurrency_total_tva = $tabprice[17];
4239 $multicurrency_total_ttc = $tabprice[18];
4240 $pu_ht_devise = $tabprice[19];
4245 if ($remise_percent > 0) {
4246 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4247 $price = ((float) $pu - $remise);
4253 $line->fetch($rowid);
4254 $line->fetch_optionals();
4256 if (!empty($line->fk_product)) {
4257 $product =
new Product($this->db);
4258 $result = $product->fetch($line->fk_product);
4259 $product_type = $product->type;
4261 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4262 $langs->load(
"errors");
4263 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4264 $this->db->rollback();
4269 $staticline = clone $line;
4271 $line->oldline = $staticline;
4272 $this->line = $line;
4273 $this->line->context = $this->context;
4274 $this->line->rang = $rang;
4277 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4278 $rangmax = $this->
line_max($fk_parent_line);
4279 $this->line->rang = $rangmax + 1;
4282 $this->line->id = $rowid;
4283 $this->line->rowid = $rowid;
4284 $this->line->label = $label;
4285 $this->line->desc = $desc;
4286 $this->line->ref_ext = $ref_ext;
4287 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4289 $this->line->vat_src_code = $vat_src_code;
4290 $this->line->tva_tx = $txtva;
4291 $this->line->localtax1_tx = $txlocaltax1;
4292 $this->line->localtax2_tx = $txlocaltax2;
4293 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4294 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4296 $this->line->remise_percent = $remise_percent;
4297 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
4298 $this->line->date_start = $date_start;
4299 $this->line->date_end = $date_end;
4300 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
4301 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
4302 $this->line->total_localtax1 = $total_localtax1;
4303 $this->line->total_localtax2 = $total_localtax2;
4304 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
4305 $this->line->info_bits = $info_bits;
4306 $this->line->special_code = $special_code;
4307 $this->line->product_type = $type;
4308 $this->line->fk_parent_line = $fk_parent_line;
4309 $this->line->skip_update_total = $skip_update_total;
4310 $this->line->situation_percent = $situation_percent;
4311 $this->line->fk_unit = $fk_unit;
4313 $this->line->fk_fournprice = $fk_fournprice;
4314 $this->line->pa_ht = $pa_ht;
4317 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
4318 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
4319 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
4320 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4322 if (is_array($array_options) && count($array_options) > 0) {
4324 foreach ($array_options as $key => $value) {
4325 $this->line->array_options[$key] = $array_options[$key];
4329 $result = $this->line->update($user, $notrigger);
4332 if (!empty($fk_parent_line)) {
4338 $this->db->commit();
4341 $this->error = $this->line->error;
4342 $this->db->rollback();
4346 $this->error =
"Invoice statut makes operation forbidden";
4360 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4361 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4362 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4364 $result = $this->db->query($sql);
4366 $this->error = $this->db->error();
4370 $obj = $this->db->fetch_object($result);
4372 if ($obj ===
null) {
4375 return ($situation_percent < $obj->situation_percent);
4391 global $mysoc, $user;
4394 if (($line->info_bits & 2) == 2) {
4398 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4401 if ($percent > 100) {
4405 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4406 $current_progress = $percent - $previous_progress;
4407 $line->situation_percent = $current_progress;
4408 $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);
4410 $line->situation_percent = $percent;
4411 $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);
4413 $line->total_ht = $tabprice[0];
4414 $line->total_tva = $tabprice[1];
4415 $line->total_ttc = $tabprice[2];
4416 $line->total_localtax1 = $tabprice[9];
4417 $line->total_localtax2 = $tabprice[10];
4418 $line->multicurrency_total_ht = $tabprice[16];
4419 $line->multicurrency_total_tva = $tabprice[17];
4420 $line->multicurrency_total_ttc = $tabprice[18];
4421 $line->update($user);
4424 if ($update_price) {
4440 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4442 if ($this->
status != self::STATUS_DRAFT) {
4443 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4449 $line->context = $this->context;
4452 $result = $line->fetch($rowid);
4453 if (!($result > 0)) {
4458 if ($id > 0 && $line->fk_facture != $id) {
4459 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4466 $staticline = clone $line;
4467 $line->oldline = $staticline;
4469 if ($line->delete($user) > 0) {
4473 $this->db->commit();
4476 $this->db->rollback();
4477 $this->error = $this->db->lasterror();
4481 $this->db->rollback();
4482 $this->error = $line->error;
4501 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4503 return $this->
setDiscount($user, $remise, $notrigger);
4517 if (empty($remise)) {
4521 if ($user->hasRight(
'facture',
'creer')) {
4522 $remise = (float)
price2num($remise, 2);
4528 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4529 $sql .=
" SET remise_percent = ".((float) $remise);
4530 $sql .=
" WHERE rowid = ".((int) $this->
id);
4531 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
4534 $resql = $this->db->query($sql);
4536 $this->errors[] = $this->db->error();
4540 if (!$notrigger && empty($error)) {
4550 $this->remise_percent = $remise;
4553 $this->db->commit();
4556 foreach ($this->errors as $errmsg) {
4557 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4558 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4560 $this->db->rollback();
4647 global $conf, $langs;
4649 if ($this->module_source ==
'takepos') {
4650 $langs->load(
'cashdesk');
4652 $moduleName =
'takepos';
4653 $moduleSourceName =
'Takepos';
4654 $addonConstName =
'TAKEPOS_REF_ADDON';
4658 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4663 $langs->load(
'bills');
4665 $moduleName =
'facture';
4666 $moduleSourceName =
'Invoice';
4667 $addonConstName =
'FACTURE_ADDON';
4671 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4673 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4675 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4681 if (!empty($addon)) {
4682 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4686 $file = $addon.
'.php';
4687 $classname = $addon;
4691 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4692 foreach ($dirmodels as $reldir) {
4693 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4696 if (is_file($dir.$file) && is_readable($dir.$file)) {
4697 $mybool = ((bool) include_once $dir.$file) || $mybool;
4703 $file = $addon.
'/'.$addon.
'.modules.php';
4704 $classname =
'mod_'.$moduleName.
'_'.$addon;
4705 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4707 foreach ($conf->file->dol_document_root as $dirroot) {
4708 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4711 if (is_file($dir.$file) && is_readable($dir.$file)) {
4712 $mybool = (include_once $dir.$file) || $mybool;
4722 $obj =
new $classname();
4723 '@phan-var-force ModeleNumRefFactures $obj';
4725 $numref = $obj->getNextValue($soc, $this, $mode);
4732 if ($mode !=
'last' && !$numref) {
4733 $this->error = $obj->error;
4739 $langs->load(
'errors');
4740 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4753 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4754 $sql .=
' date_closing as dateclosing,';
4755 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4756 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4757 $sql .=
' WHERE c.rowid = '.((int) $id);
4759 $result = $this->db->query($sql);
4761 if ($this->db->num_rows($result)) {
4762 $obj = $this->db->fetch_object($result);
4764 $this->
id = $obj->rowid;
4765 $this->user_creation_id = $obj->fk_user_author;
4766 $this->user_validation_id = $obj->fk_user_valid;
4767 $this->user_closing_id = $obj->fk_user_closing;
4769 $this->date_creation = $this->db->jdate($obj->datec);
4770 $this->date_modification = $this->db->jdate($obj->datem);
4771 $this->date_validation = $this->db->jdate($obj->datev);
4772 $this->date_closing = $this->db->jdate($obj->dateclosing);
4774 $this->db->free($result);
4795 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4802 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4803 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4804 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4805 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4806 $sql .=
" AND f.fk_soc = s.rowid";
4808 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4810 if (is_object($excluser)) {
4811 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4815 if (!$user->hasRight(
'societe',
'client',
'voir')) {
4816 $search_sale = $user->id;
4819 if ($search_sale && $search_sale !=
'-1') {
4820 if ($search_sale == -2) {
4821 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
4822 } elseif ($search_sale > 0) {
4823 $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).
")";
4828 $sql .=
" AND f.fk_soc = ".((int) $socid);
4830 $sql .= $this->db->order($sortfield, $sortorder);
4831 $sql .= $this->db->plimit($limit, $offset);
4833 $result = $this->db->query($sql);
4835 $numc = $this->db->num_rows($result);
4838 while ($i < $numc) {
4839 $obj = $this->db->fetch_object($result);
4841 if ($shortlist == 1) {
4842 $ga[$obj->fid] = $obj->ref;
4843 } elseif ($shortlist == 2) {
4844 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4846 $ga[$i][
'id'] = $obj->fid;
4847 $ga[$i][
'ref'] = $obj->ref;
4848 $ga[$i][
'name'] = $obj->name;
4877 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4878 $sql .=
" ff.rowid as rowidnext";
4880 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4881 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4882 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4883 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4884 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4885 $sql .=
" AND f.paye = 0";
4886 $sql .=
" AND pf.fk_paiement IS NULL";
4887 $sql .=
" AND ff.fk_statut IS NULL";
4889 $sql .=
" AND f.fk_soc = ".((int) $socid);
4892 $sql .=
" ORDER BY f.ref";
4894 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4895 $resql = $this->db->query($sql);
4897 while ($obj = $this->db->fetch_object($resql)) {
4898 $return[$obj->rowid] = array(
4899 'id' => $obj->rowid,
4901 'status' => $obj->status,
4902 'paid' => $obj->paid,
4909 $this->error = $this->db->error();
4933 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
4934 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4935 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4936 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4937 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4938 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4942 $sql .=
" AND ff.type IS NULL";
4943 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4947 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4948 $sql .=
'(SELECT MAX(fs.rowid)';
4949 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4950 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4951 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4952 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4954 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4956 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4959 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4963 $sql .=
" AND f.fk_soc = ".((int) $socid);
4965 $sql .=
" ORDER BY f.ref";
4967 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4968 $resql = $this->db->query($sql);
4970 while ($obj = $this->db->fetch_object($resql)) {
4972 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4975 if ($obj->fk_statut == self::STATUS_CLOSED) {
4980 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4981 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
4987 $this->error = $this->db->error();
5003 global $conf, $langs;
5007 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5008 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5009 if (!$user->hasRight(
'societe',
'client',
'voir')) {
5010 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5011 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5014 $sql .= $clause.
" f.paye=0";
5015 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5016 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5018 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5021 $resql = $this->db->query($sql);
5023 $langs->load(
"bills");
5027 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
5028 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5029 $response->labelShort = $langs->trans(
"Unpaid");
5030 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5033 $generic_facture =
new Facture($this->db);
5035 while ($obj = $this->db->fetch_object($resql)) {
5036 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5037 $generic_facture->statut = $obj->status;
5038 $generic_facture->status = $obj->status;
5040 $response->nbtodo++;
5041 $response->total += $obj->total_ht;
5043 if ($generic_facture->hasDelay()) {
5044 $response->nbtodolate++;
5045 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_late=late&mainmenu=billing&leftmenu=customers_bills';
5049 $this->db->free($resql);
5053 $this->error = $this->db->error();
5092 global $conf, $langs, $user;
5096 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5101 $sql =
"SELECT rowid";
5102 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5103 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5104 $sql .= $this->db->plimit(100);
5106 $resql = $this->db->query($sql);
5108 $num_prods = $this->db->num_rows($resql);
5110 while ($i < $num_prods) {
5112 $row = $this->db->fetch_row($resql);
5113 $prodids[$i] = $row[0];
5117 if (empty($num_prods)) {
5124 $this->
ref =
'SPECIMEN';
5125 $this->specimen = 1;
5127 $this->date = $nownotime;
5128 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5129 $this->cond_reglement_id = 1;
5130 $this->cond_reglement_code =
'RECEP';
5132 $this->mode_reglement_id = 0;
5133 $this->mode_reglement_code =
'';
5135 $this->note_public =
'This is a comment (public)';
5136 $this->note_private =
'This is a comment (private)';
5137 $this->note =
'This is a comment (private)';
5139 $this->fk_user_author = $user->id;
5141 $this->multicurrency_tx = 1;
5142 $this->multicurrency_code = $conf->currency;
5144 $this->fk_incoterms = 0;
5145 $this->location_incoterms =
'';
5147 if (empty($option) || $option !=
'nolines') {
5151 while ($xnbp < $nbp) {
5153 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5155 $line->subprice = 100;
5156 $line->tva_tx = 19.6;
5157 $line->localtax1_tx = 0;
5158 $line->localtax2_tx = 0;
5159 $line->remise_percent = 0;
5161 $prodid = mt_rand(1, $num_prods);
5162 $line->fk_product = $prodids[$prodid];
5164 $line->total_ht = -100;
5165 $line->total_ttc = -119.6;
5166 $line->total_tva = -19.6;
5167 $line->multicurrency_total_ht = -200;
5168 $line->multicurrency_total_ttc = -239.2;
5169 $line->multicurrency_total_tva = -39.2;
5170 } elseif ($xnbp == 2) {
5171 $line->subprice = -100;
5172 $line->total_ht = -100;
5173 $line->total_ttc = -119.6;
5174 $line->total_tva = -19.6;
5175 $line->remise_percent = 0;
5176 $line->multicurrency_total_ht = -200;
5177 $line->multicurrency_total_ttc = -239.2;
5178 $line->multicurrency_total_tva = -39.2;
5179 } elseif ($xnbp == 3) {
5180 $prodid = mt_rand(1, $num_prods);
5181 $line->fk_product = $prodids[$prodid];
5182 $line->total_ht = 50;
5183 $line->total_ttc = 59.8;
5184 $line->total_tva = 9.8;
5185 $line->multicurrency_total_ht = 100;
5186 $line->multicurrency_total_ttc = 119.6;
5187 $line->multicurrency_total_tva = 19.6;
5188 $line->remise_percent = 50;
5190 $prodid = mt_rand(1, $num_prods);
5191 $line->fk_product = $prodids[$prodid];
5192 $line->total_ht = 100;
5193 $line->total_ttc = 119.6;
5194 $line->total_tva = 19.6;
5195 $line->multicurrency_total_ht = 200;
5196 $line->multicurrency_total_ttc = 239.2;
5197 $line->multicurrency_total_tva = 39.2;
5198 $line->remise_percent = 0;
5201 $this->lines[$xnbp] = $line;
5204 $this->total_ht += $line->total_ht;
5205 $this->total_tva += $line->total_tva;
5206 $this->total_ttc += $line->total_ttc;
5208 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5209 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5210 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5214 $this->revenuestamp = 0;
5218 $line->desc = $langs->trans(
"Description").
" (offered line)";
5220 $line->subprice = 100;
5221 $line->tva_tx = 19.6;
5222 $line->localtax1_tx = 0;
5223 $line->localtax2_tx = 0;
5224 $line->remise_percent = 100;
5225 $line->total_ht = 0;
5226 $line->total_ttc = 0;
5227 $line->total_tva = 0;
5228 $line->multicurrency_total_ht = 0;
5229 $line->multicurrency_total_ttc = 0;
5230 $line->multicurrency_total_tva = 0;
5231 $prodid = mt_rand(1, $num_prods);
5232 $line->fk_product = $prodids[$prodid];
5234 $this->lines[$xnbp] = $line;
5248 global $conf, $user;
5250 $this->nb = array();
5254 $sql =
"SELECT count(f.rowid) as nb";
5255 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5256 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5257 if (!$user->hasRight(
'societe',
'client',
'voir')) {
5258 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5259 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5262 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
5264 $resql = $this->db->query($sql);
5266 while ($obj = $this->db->fetch_object($resql)) {
5267 $this->nb[
"invoices"] = $obj->nb;
5269 $this->db->free($resql);
5273 $this->error = $this->db->error();
5299 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5301 global $conf, $langs;
5303 $outputlangs->loadLangs(array(
"bills",
"products"));
5307 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5309 if (!empty($this->model_pdf)) {
5310 $modele = $this->model_pdf;
5318 $modelpath =
"core/modules/facture/doc/";
5320 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5330 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5331 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5332 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5334 $resql = $this->db->query($sql);
5336 if ($this->db->num_rows($resql) > 0) {
5338 $obj = $this->db->fetch_object($resql);
5340 $ref = $obj->maxsituationref;
5346 $this->db->free($resql);
5349 $this->error = $this->db->lasterror();
5350 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5364 return ($this->situation_counter == 1);
5378 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5379 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5380 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5381 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5382 $resql = $this->db->query($sql);
5384 if ($resql && $this->db->num_rows($resql) > 0) {
5385 while ($row = $this->db->fetch_object($resql)) {
5387 $situation =
new Facture($this->db);
5388 $situation->fetch($id);
5389 $res[] = $situation;
5392 $this->error = $this->db->error();
5393 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5413 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5416 $resql = $this->db->query($sql);
5418 $this->errors[] = $this->db->error();
5422 if (!$notrigger && empty($error)) {
5432 $this->db->commit();
5435 foreach ($this->errors as $errmsg) {
5436 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5437 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5439 $this->db->rollback();
5455 if (!empty($this->situation_cycle_ref)) {
5457 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5458 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5459 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5460 $resql = $this->db->query($sql);
5462 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5463 $last = $res[
'max(situation_counter)'];
5464 return ($last == $this->situation_counter);
5466 $this->error = $this->db->lasterror();
5467 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5525 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5526 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5528 $totalpaid = (float) $totalpaid;
5530 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5531 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5533 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5556 $displayWarranty =
false;
5557 if (!empty($this->retained_warranty)) {
5558 $displayWarranty =
true;
5562 $displayWarranty =
false;
5563 if (!empty($this->situation_final)) {
5564 $displayWarranty =
true;
5567 $displayWarranty =
true;
5569 foreach ($this->lines as $i => $line) {
5570 if ($line->product_type < 2 && $line->situation_percent < 100) {
5571 $displayWarranty =
false;
5579 return $displayWarranty;
5589 if (empty($this->retained_warranty)) {
5593 $retainedWarrantyAmount = 0;
5597 $displayWarranty =
true;
5599 if (!empty($this->lines)) {
5600 foreach ($this->lines as $i => $line) {
5601 if ($line->product_type < 2 && $line->situation_percent < 100) {
5602 $displayWarranty =
false;
5608 if ($displayWarranty && !empty($this->situation_final)) {
5610 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5613 foreach ($TPreviousIncoice as &$fac) {
5614 $total2BillWT += $fac->total_ttc;
5616 $total2BillWT += $this->total_ttc;
5618 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5624 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5627 if ($rounding < 0) {
5631 if ($rounding > 0) {
5632 return round($retainedWarrantyAmount, $rounding);
5635 return $retainedWarrantyAmount;
5646 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5648 if ($this->
status >= 0) {
5649 $fieldname =
'retained_warranty';
5650 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5651 $sql .=
" SET ".$fieldname.
" = ".((float) $value);
5652 $sql .=
' WHERE rowid='.((int) $this->
id);
5654 if ($this->db->query($sql)) {
5655 $this->retained_warranty = (float) $value;
5658 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5659 $this->error = $this->db->error();
5663 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5664 $this->error =
'Status of the object is incompatible '.$this->status;
5679 if (!$timestamp && $dateYmd) {
5680 $timestamp = $this->db->jdate($dateYmd);
5684 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5685 if ($this->
status >= 0) {
5686 $fieldname =
'retained_warranty_date_limit';
5687 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5688 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5689 $sql .=
' WHERE rowid = '.((int) $this->
id);
5691 if ($this->db->query($sql)) {
5692 $this->retained_warranty_date_limit = $timestamp;
5695 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5696 $this->error = $this->db->error();
5700 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5701 $this->error =
'Status of the object is incompatible '.$this->status;
5720 global $conf, $langs, $user;
5726 $errorsMsg = array();
5728 $langs->load(
"bills");
5730 if (!isModEnabled(
'invoice')) {
5731 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5734 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
5735 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
5745 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5746 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5747 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5748 $formmail =
new FormMail($this->db);
5753 $tmpinvoice =
new Facture($this->db);
5758 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5759 if (!empty($paymentmode) && $paymentmode !=
'all') {
5760 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5762 $sql .=
" WHERE f.paye = 0";
5763 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5764 if ($datetouse ==
'invoicedate') {
5765 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
5767 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5769 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
5770 if (!empty($paymentmode) && $paymentmode !=
'all') {
5771 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5774 if ($datetouse ==
'invoicedate') {
5775 $sql .= $this->db->order(
"datef",
"ASC");
5777 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
5780 $resql = $this->db->query($sql);
5783 if ($datetouse ==
'invoicedate') {
5784 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
5786 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5788 if (!empty($paymentmode) && $paymentmode !=
'all') {
5789 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5791 $this->output .=
'<br>';
5794 while ($obj = $this->db->fetch_object($resql)) {
5797 $res = $tmpinvoice->fetch($obj->id);
5799 $tmpinvoice->fetch_thirdparty();
5801 $outputlangs =
new Translate(
'', $conf);
5802 if ($tmpinvoice->thirdparty->default_lang) {
5803 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5804 $outputlangs->loadLangs(array(
"main",
"bills"));
5806 $outputlangs = $langs;
5810 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5811 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5812 $langs->load(
"errors");
5813 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5826 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5829 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5835 if ($forcerecipient) {
5836 $to = array($forcerecipient);
5838 $res = $tmpinvoice->fetch_thirdparty();
5839 $recipient = $tmpinvoice->thirdparty;
5841 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
5842 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5843 foreach ($tmparraycontact as $data_email) {
5844 if (!empty($data_email[
'email'])) {
5845 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
5849 if (empty($to) && !empty($recipient->email)) {
5850 $to[] = $recipient->email;
5853 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
5857 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5864 if (!empty($arraymessage->email_from)) {
5865 $from = $arraymessage->email_from;
5868 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5872 if (!$error && !empty($to)) {
5875 $to = implode(
',', $to);
5876 if (!empty($arraymessage->email_to)) {
5877 $to = $to.
','.$arraymessage->email_to;
5883 $trackid =
'inv'.$tmpinvoice->id;
5884 $sendcontext =
'standard';
5887 if (!empty($arraymessage->email_tocc)) {
5888 $email_tocc = $arraymessage->email_tocc;
5892 if (!empty($arraymessage->email_tobcc)) {
5893 $email_tobcc = $arraymessage->email_tobcc;
5900 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5901 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
5902 $joinFileName[] = basename($tmpinvoice->last_main_doc);
5903 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
5907 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5910 if ($cMailFile->sendfile()) {
5914 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5919 $actioncomm->type_code =
'AC_OTH_AUTO';
5920 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5921 $actioncomm->contact_id = 0;
5923 $actioncomm->code =
'AC_EMAIL';
5924 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
5925 $actioncomm->note_private = $sendContent;
5926 $actioncomm->fk_project = $tmpinvoice->fk_project;
5927 $actioncomm->datep =
dol_now();
5928 $actioncomm->datef = $actioncomm->datep;
5929 $actioncomm->percentage = -1;
5930 $actioncomm->authorid = $user->id;
5931 $actioncomm->userownerid = $user->id;
5933 $actioncomm->email_msgid = $cMailFile->msgid;
5934 $actioncomm->email_subject = $sendTopic;
5935 $actioncomm->email_from = $from;
5936 $actioncomm->email_sender =
'';
5937 $actioncomm->email_to = $to;
5941 $actioncomm->errors_to = $errors_to;
5943 $actioncomm->elementtype =
'invoice';
5944 $actioncomm->fk_element = $tmpinvoice->id;
5948 $actioncomm->create($user);
5950 $errormesg = $cMailFile->error.
' : '.$to;
5954 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5959 $actioncomm->type_code =
'AC_OTH_AUTO';
5960 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5961 $actioncomm->contact_id = 0;
5963 $actioncomm->code =
'AC_EMAIL';
5964 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5965 $actioncomm->note_private = $errormesg;
5966 $actioncomm->fk_project = $tmpinvoice->fk_project;
5967 $actioncomm->datep =
dol_now();
5968 $actioncomm->datef = $actioncomm->datep;
5969 $actioncomm->percentage = -1;
5970 $actioncomm->authorid = $user->id;
5971 $actioncomm->userownerid = $user->id;
5973 $actioncomm->email_msgid = $cMailFile->msgid;
5974 $actioncomm->email_from = $from;
5975 $actioncomm->email_sender =
'';
5976 $actioncomm->email_to = $to;
5980 $actioncomm->errors_to = $errors_to;
5984 $actioncomm->create($user);
5987 $this->db->commit();
5991 $errorsMsg[] = $errormesg;
5994 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6004 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6006 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6010 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6012 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6027 $sql =
"SELECT datef";
6028 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6029 $sql .=
" WHERE type = " . (int) $this->
type ;
6030 $sql .=
" AND date_valid IS NOT NULL";
6031 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6032 $sql .=
" ORDER BY datef DESC LIMIT 1";
6034 $result = $this->db->query($sql);
6037 if ($this->db->num_rows($result)) {
6038 $obj = $this->db->fetch_object($result);
6039 $last_date = $this->db->jdate($obj->datef);
6040 $invoice_date = $this->date;
6042 $is_last_of_same_type = $invoice_date >= $last_date;
6043 if ($allow_validated_drafts) {
6047 return array($is_last_of_same_type, $last_date);
6070 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6072 $picto = $this->picto;
6073 if ($this->
type == self::TYPE_REPLACEMENT) {
6076 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6079 if ($this->
type == self::TYPE_DEPOSIT) {
6083 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6084 $return .=
'<div class="info-box info-box-sm">';
6085 $return .=
'<span class="info-box-icon bg-infobox-action">';
6087 $return .=
'</span>';
6088 $return .=
'<div class="info-box-content">';
6089 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6090 if ($selected >= 0) {
6091 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6093 if (!empty($arraydata[
'thirdparty'])) {
6094 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6096 if (property_exists($this,
'date')) {
6097 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->date,
'day').
'</span>';
6099 if (property_exists($this,
'total_ht')) {
6100 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6101 $return .=
' '.$langs->trans(
"HT");
6102 $return .=
'</span>';
6104 if (method_exists($this,
'getLibStatut')) {
6105 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6106 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6108 $return .=
'</div>';
6109 $return .=
'</div>';
6110 $return .=
'</div>';
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $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...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage invoices.
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Retourne id des contacts clients de livraison.
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...
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.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this->lines.
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()
Retourne id des contacts clients de facturation.
__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.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
updatePriceNextInvoice(&$langs)
Update price of next invoice.
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 Facture 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.
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')
Set absolute discount.
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.
initAsSpecimen($option='')
Initialise an instance with random values.
deleteLine($rowid, $id=0)
Delete line in database.
getRetainedWarrantyAmount($rounding=-1)
create(User $user, $notrigger=0, $forceduedate=0)
Create invoice 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.
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 getIdFromCode($dbs, $code)
Get id of currency from code.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate 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_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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_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.
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...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
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...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type