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 $class_element_line =
'FactureLigne';
88 public $fk_element =
'fk_facture';
93 public $picto =
'bill';
99 public $restrictiononfksoc = 1;
110 public $fk_user_author;
116 public $fk_user_valid;
122 public $fk_user_modif;
132 public $delivery_date;
144 public $ref_customer;
157 public $total_localtax1;
161 public $total_localtax2;
169 public $revenuestamp;
186 public $module_source;
194 public $fk_fac_rec_source;
198 public $fk_facture_source;
200 public $linked_objects = array();
210 public $lines = array();
219 public $extraparams = array();
229 public $date_pointoftax;
235 public $situation_cycle_ref;
240 public $situation_counter;
245 public $situation_final;
250 public $tab_previous_situation_invoice = array();
255 public $tab_next_situation_invoice = array();
260 public $retained_warranty;
265 public $retained_warranty_date_limit;
270 public $retained_warranty_fk_cond_reglement;
275 public $availability_id;
280 public $date_closing;
291 public $remise_percent;
296 public $online_payment_url;
328 public $fields = array(
329 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 1),
330 'ref' => array(
'type' =>
'varchar(30)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'position' => 5),
331 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 20,
'index' => 1),
332 'ref_client' => array(
'type' =>
'varchar(255)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 10),
333 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'RefExt',
'enabled' => 1,
'visible' => 0,
'position' => 12),
334 'type' => array(
'type' =>
'smallint(6)',
'label' =>
'Type',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
335 'subtype' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoiceSubtype',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
337 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 50),
338 'datef' => array(
'type' =>
'date',
'label' =>
'DateInvoice',
'enabled' => 1,
'visible' => 1,
'position' => 20),
339 'date_valid' => array(
'type' =>
'date',
'label' =>
'DateValidation',
'enabled' => 1,
'visible' => -1,
'position' => 22),
340 'date_lim_reglement' => array(
'type' =>
'date',
'label' =>
'DateDue',
'enabled' => 1,
'visible' => 1,
'position' => 25),
341 'date_closing' => array(
'type' =>
'datetime',
'label' =>
'DateClosing',
'enabled' => 1,
'visible' => -1,
'position' => 30),
342 'paye' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoicePaidCompletely',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 80),
347 'close_code' => array(
'type' =>
'varchar(16)',
'label' =>
'EarlyClosingReason',
'enabled' => 1,
'visible' => -1,
'position' => 92),
348 'close_note' => array(
'type' =>
'varchar(128)',
'label' =>
'EarlyClosingComment',
'enabled' => 1,
'visible' => -1,
'position' => 93),
349 'total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountHT',
'enabled' => 1,
'visible' => 1,
'position' => 95,
'isameasure' => 1),
350 'total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountVAT',
'enabled' => 1,
'visible' => -1,
'position' => 100,
'isameasure' => 1),
351 'localtax1' => array(
'type' =>
'double(24,8)',
'label' =>
'LT1',
'enabled' => 1,
'visible' => -1,
'position' => 110,
'isameasure' => 1),
352 'localtax2' => array(
'type' =>
'double(24,8)',
'label' =>
'LT2',
'enabled' => 1,
'visible' => -1,
'position' => 120,
'isameasure' => 1),
353 'revenuestamp' => array(
'type' =>
'double(24,8)',
'label' =>
'RevenueStamp',
'enabled' => 1,
'visible' => -1,
'position' => 115,
'isameasure' => 1),
354 'total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountTTC',
'enabled' => 1,
'visible' => 1,
'position' => 130,
'isameasure' => 1),
355 'fk_facture_source' => array(
'type' =>
'integer',
'label' =>
'SourceInvoice',
'enabled' => 1,
'visible' => -1,
'position' => 170),
356 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' => 1,
'visible' => -1,
'position' => 175),
357 'fk_account' => array(
'type' =>
'integer',
'label' =>
'Fk account',
'enabled' => 1,
'visible' => -1,
'position' => 180),
358 'fk_currency' => array(
'type' =>
'varchar(3)',
'label' =>
'CurrencyCode',
'enabled' => 1,
'visible' => -1,
'position' => 185),
359 'fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentTerm',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 190),
360 'fk_mode_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentMode',
'enabled' => 1,
'visible' => -1,
'position' => 195),
361 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 205),
362 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 210),
363 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 215),
364 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 225),
365 'situation_cycle_ref' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation cycle ref',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 230),
366 'situation_counter' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation counter',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 235),
367 'situation_final' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation final',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 240),
368 'retained_warranty' => array(
'type' =>
'double',
'label' =>
'Retained warranty',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 245),
369 'retained_warranty_date_limit' => array(
'type' =>
'date',
'label' =>
'Retained warranty date limit',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 250),
370 'retained_warranty_fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'Retained warranty fk cond reglement',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 255),
371 'fk_incoterms' => array(
'type' =>
'integer',
'label' =>
'IncotermCode',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 260),
372 'location_incoterms' => array(
'type' =>
'varchar(255)',
'label' =>
'IncotermLabel',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 265),
373 'date_pointoftax' => array(
'type' =>
'date',
'label' =>
'DatePointOfTax',
'enabled' =>
'getDolGlobalString("INVOICE_POINTOFTAX_DATE")',
'visible' => -1,
'position' => 270),
374 'fk_multicurrency' => array(
'type' =>
'integer',
'label' =>
'MulticurrencyID',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 275),
375 'multicurrency_code' => array(
'type' =>
'varchar(255)',
'label' =>
'Currency',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 280),
376 'multicurrency_tx' => array(
'type' =>
'double(24,8)',
'label' =>
'CurrencyRate',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 285,
'isameasure' => 1),
377 'multicurrency_total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountHT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 290,
'isameasure' => 1),
378 'multicurrency_total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountVAT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 291,
'isameasure' => 1),
379 'multicurrency_total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountTTC',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 292,
'isameasure' => 1),
380 'fk_fac_rec_source' => array(
'type' =>
'integer',
'label' =>
'RecurringInvoiceSource',
'enabled' => 1,
'visible' => -1,
'position' => 305),
381 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'LastMainDoc',
'enabled' => 1,
'visible' => -1,
'position' => 310),
382 'module_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSModule',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 315),
383 'pos_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSTerminal',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 320),
384 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 500),
385 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModificationShort',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 502),
386 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'position' => 506),
387 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModification',
'enabled' => 1,
'visible' => -1,
'notnull' => -1,
'position' => 508),
388 'fk_user_valid' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserValidation',
'enabled' => 1,
'visible' => -1,
'position' => 510),
389 'fk_user_closing' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserClosing',
'enabled' => 1,
'visible' => -1,
'position' => 512),
390 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 900),
391 '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')),
453 const CLOSECODE_DISCOUNTVAT =
'discount_vat';
454 const CLOSECODE_BADDEBT =
'badcustomer';
455 const CLOSECODE_BANKCHARGE =
'bankcharge';
456 const CLOSECODE_OTHER =
'other';
458 const CLOSECODE_ABANDONED =
'abandon';
459 const CLOSECODE_REPLACED =
'replaced';
471 $this->ismultientitymanaged = 1;
472 $this->isextrafieldmanaged = 1;
485 public function create(
User $user, $notrigger = 0, $forceduedate = 0)
487 global $langs,
$conf, $mysoc, $hookmanager;
489 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
491 if (empty($this->
type)) {
495 $this->ref_client = trim($this->ref_client);
496 $this->ref_customer = trim($this->ref_customer);
498 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
499 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
500 $this->note_public = (isset($this->note_public) ? trim($this->note_public) :
'');
502 if (!$this->cond_reglement_id) {
503 $this->cond_reglement_id = 0;
505 if (!$this->mode_reglement_id) {
506 $this->mode_reglement_id = 0;
511 if (!empty($this->multicurrency_code)) {
513 if (empty($this->multicurrency_tx)) {
521 $this->fk_multicurrency = 0;
523 if (empty($this->fk_multicurrency)) {
524 $this->multicurrency_code =
$conf->currency;
525 $this->fk_multicurrency = 0;
526 $this->multicurrency_tx = 1;
530 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
533 if (empty($this->date)) {
534 $this->error =
"Try to create an invoice with an empty parameter (date)";
535 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
539 $result = $soc->fetch($this->socid);
541 $this->error =
"Failed to fetch company: ".$soc->error;
542 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
547 $this->date_creation = $now;
551 $originaldatewhen =
null;
552 $nextdatewhen =
null;
553 $previousdaynextdatewhen =
null;
558 if ($this->fac_rec > 0) {
559 $this->fk_fac_rec_source = $this->fac_rec;
561 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
563 $result = $_facrec->fetch($this->fac_rec);
564 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
568 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
572 $originaldatewhen = $_facrec->date_when;
573 $nextdatewhen =
null;
574 $previousdaynextdatewhen =
null;
575 if ($originaldatewhen) {
576 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
580 if (!empty($_facrec->frequency)) {
581 $this->socid = $_facrec->socid;
583 $this->entity = $_facrec->entity;
588 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
589 $this->note_public = GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
590 $this->note_private = GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
591 $this->model_pdf = GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
592 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
593 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
594 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
597 $this->total_ht = $_facrec->total_ht;
598 $this->total_ttc = $_facrec->total_ttc;
603 $this->fk_incoterms = $_facrec->fk_incoterms;
604 $this->location_incoterms = $_facrec->location_incoterms;
610 $this->ref_client = trim($this->ref_client);
611 $this->ref_customer = trim($this->ref_customer);
612 $this->note_public = trim($this->note_public);
613 $this->note_private = trim($this->note_private);
614 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
616 $this->array_options = $_facrec->array_options;
618 if (!$this->mode_reglement_id) {
619 $this->mode_reglement_id = 0;
624 $this->linked_objects = $_facrec->linkedObjectsIds;
629 if ($_facrec->frequency > 0) {
630 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
631 if (empty($_facrec->date_when)) {
632 $_facrec->date_when = $now;
634 $next_date = $_facrec->getNextDate();
635 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
637 $result = $_facrec->setNextDate($next_date, 1);
641 $outputlangs = $langs;
644 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
645 $newlang = $this->thirdparty->default_lang;
648 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
649 $newlang = $this->default_lang;
651 if (!empty($newlang)) {
653 $outputlangs->setDefaultLang($newlang);
659 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
662 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
665 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
668 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
669 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
670 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
671 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
672 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
683 if (empty($forceduedate)) {
689 $this->date_lim_reglement = $duedate;
691 $this->date_lim_reglement = $forceduedate;
695 $socid = $this->socid;
697 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
706 $sql .=
", date_pointoftax";
707 $sql .=
", note_private";
708 $sql .=
", note_public";
709 $sql .=
", ref_client";
710 $sql .=
", fk_account";
711 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
712 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
713 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
714 $sql .=
", fk_incoterms, location_incoterms";
715 $sql .=
", fk_multicurrency";
716 $sql .=
", multicurrency_code";
717 $sql .=
", multicurrency_tx";
718 $sql .=
", retained_warranty";
719 $sql .=
", retained_warranty_date_limit";
720 $sql .=
", retained_warranty_fk_cond_reglement";
724 $sql .=
", ".(int) $this->entity;
725 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
726 $sql .=
", '".$this->db->escape($this->
type).
"'";
727 $sql .=
", ".($this->subtype ?
"'".$this->db->escape($this->subtype).
"'" :
"null");
728 $sql .=
", ".((int) $socid);
729 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
730 $sql .=
", '".$this->db->idate($this->date).
"'";
731 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
732 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
733 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
734 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
735 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
736 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
737 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape($this->pos_source).
"'" :
"null");
738 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape($this->fk_fac_rec_source).
"'" :
"null");
739 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape($this->fk_facture_source).
"'" :
"null");
740 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
741 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
742 $sql .=
", ".((int) $this->cond_reglement_id);
743 $sql .=
", ".((int) $this->mode_reglement_id);
744 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
745 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
746 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape($this->situation_cycle_ref).
"'" :
"null");
747 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape($this->situation_counter).
"'" :
"null");
748 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
749 $sql .=
", ".(int) $this->fk_incoterms;
750 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
751 $sql .=
", ".(int) $this->fk_multicurrency;
752 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
753 $sql .=
", ".(float) $this->multicurrency_tx;
754 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape($this->retained_warranty));
755 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
756 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
759 $resql = $this->db->query($sql);
761 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
764 $this->
ref =
'(PROV'.$this->id.
')';
765 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
767 $resql = $this->db->query($sql);
772 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
773 $this->linked_objects = $this->linkedObjectsIds;
777 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
778 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
779 if (is_array($tmp_origin_id)) {
780 foreach ($tmp_origin_id as $origin_id) {
783 $this->error = $this->db->lasterror();
788 $origin_id = $tmp_origin_id;
791 $this->error = $this->db->lasterror();
799 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) {
800 $originforcontact = $this->origin;
801 $originidforcontact = $this->origin_id;
802 if ($originforcontact ==
'shipping') {
803 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
805 $exp->fetch($this->origin_id);
806 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
807 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
808 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
809 $originforcontact =
'commande';
810 if (is_object($value)) {
811 $originidforcontact = $value->id;
813 $originidforcontact = $value;
820 $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";
821 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
823 $resqlcontact = $this->db->query($sqlcontact);
825 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
827 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
837 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
840 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
841 foreach ($this->lines as $i => $val) {
842 $newinvoiceline = $this->lines[$i];
843 '@phan-var-force FactureLigne $newinvoiceline';
845 $newinvoiceline->context = $this->context;
847 $newinvoiceline->fk_facture = $this->id;
849 $newinvoiceline->origin = $this->lines[$i]->element;
850 $newinvoiceline->origin_id = $this->lines[$i]->id;
853 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
854 $newinvoiceline->date_start = $originaldatewhen;
856 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
857 $newinvoiceline->date_end = $previousdaynextdatewhen;
862 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
867 $vatrate = $newinvoiceline->tva_tx;
868 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
869 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
872 $newinvoiceline->fk_parent_line = $fk_parent_line;
876 $discount->fetch($newinvoiceline->fk_remise_except);
878 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
879 $newinvoiceline->fk_remise_except = $discountId;
883 $newinvoiceline->desc,
884 $newinvoiceline->subprice,
885 $newinvoiceline->qty,
887 $newinvoiceline->localtax1_tx,
888 $newinvoiceline->localtax2_tx,
889 $newinvoiceline->fk_product,
890 $newinvoiceline->remise_percent,
891 $newinvoiceline->date_start,
892 $newinvoiceline->date_end,
893 $newinvoiceline->fk_code_ventilation,
894 $newinvoiceline->info_bits,
895 $newinvoiceline->fk_remise_except,
898 $newinvoiceline->product_type,
899 $newinvoiceline->rang,
900 $newinvoiceline->special_code,
901 $newinvoiceline->element,
904 $newinvoiceline->fk_fournprice,
905 $newinvoiceline->pa_ht,
906 $newinvoiceline->label,
907 $newinvoiceline->array_options,
908 $newinvoiceline->situation_percent,
909 $newinvoiceline->fk_prev_id,
910 $newinvoiceline->fk_unit,
911 $newinvoiceline->multicurrency_subprice,
912 $newinvoiceline->ref_ext,
917 $this->error = $newinvoiceline->error;
918 $this->errors = array_merge($this->errors, $newinvoiceline->errors);
924 if ($result > 0 && $newinvoiceline->product_type == 9) {
925 $fk_parent_line = $result;
929 } elseif (!$error && empty($this->fac_rec)) {
932 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
934 foreach ($this->lines as $i => $val) {
935 $line = $this->lines[$i];
936 '@phan-var-force FactureLigne $line';
940 if (!is_object($line)) {
941 $line = (object) $line;
946 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
951 $vatrate = $line->tva_tx;
952 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
953 $vatrate .=
' ('.$line->vat_src_code.
')';
957 $originid = $line->origin_id;
958 $origintype = $line->origin;
960 $originid = $line->id;
961 $origintype = $this->element;
965 if (empty($line->ref_ext)) {
977 $line->remise_percent,
980 $line->fk_code_ventilation,
982 $line->fk_remise_except,
991 $line->fk_fournprice,
994 $line->array_options,
995 $line->situation_percent,
998 $line->multicurrency_subprice,
1003 $this->error = $this->db->lasterror();
1005 $this->db->rollback();
1010 if ($result > 0 && $line->product_type == 9) {
1011 $fk_parent_line = $result;
1020 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1021 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1022 $fk_parent_line = 0;
1024 foreach ($_facrec->lines as $i => $val) {
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;
1043 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1044 $tva_npr = $_facrec->lines[$i]->info_bits;
1045 if (empty($tva_tx)) {
1048 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1049 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1051 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1052 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1055 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1056 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1058 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1063 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1064 $buyprice = $producttmp->cost_price;
1066 $buyprice = $producttmp->pmp;
1068 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1069 if ($producttmp->product_fourn_price_id > 0) {
1070 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1076 $result_insert = $this->
addline(
1077 $_facrec->lines[$i]->desc,
1078 $_facrec->lines[$i]->subprice,
1079 $_facrec->lines[$i]->qty,
1083 $_facrec->lines[$i]->fk_product,
1084 $_facrec->lines[$i]->remise_percent,
1085 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1086 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1092 $_facrec->lines[$i]->product_type,
1093 $_facrec->lines[$i]->rang,
1094 $_facrec->lines[$i]->special_code,
1098 $fk_product_fournisseur_price,
1100 $_facrec->lines[$i]->label,
1101 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1104 $_facrec->lines[$i]->fk_unit,
1105 $_facrec->lines[$i]->multicurrency_subprice,
1106 $_facrec->lines[$i]->ref_ext,
1111 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1112 $fk_parent_line = $result_insert;
1115 if ($result_insert < 0) {
1117 $this->error = $this->db->error();
1134 if (!$error && !$notrigger) {
1143 $this->db->commit();
1146 $this->db->rollback();
1150 $this->error = $langs->trans(
'FailedToUpdatePrice');
1151 $this->db->rollback();
1155 dol_syslog(get_class($this).
"::create error ".$this->error, LOG_ERR);
1156 $this->db->rollback();
1160 $this->error = $this->db->error();
1161 $this->db->rollback();
1177 $facture =
new Facture($this->db);
1183 if (!empty($this->array_options)) {
1184 $facture->array_options = $this->array_options;
1187 foreach ($this->lines as &$line) {
1188 $line->fetch_optionals();
1191 $facture->fk_facture_source = $this->fk_facture_source;
1192 $facture->type = $this->type;
1193 $facture->subtype = $this->subtype;
1194 $facture->socid = $this->socid;
1195 $facture->date = $this->date;
1196 $facture->date_pointoftax = $this->date_pointoftax;
1197 $facture->note_public = $this->note_public;
1198 $facture->note_private = $this->note_private;
1199 $facture->ref_client = $this->ref_client;
1200 $facture->ref_customer = $this->ref_customer;
1201 $facture->model_pdf = $this->model_pdf;
1202 $facture->fk_project = $this->fk_project;
1203 $facture->cond_reglement_id = $this->cond_reglement_id;
1204 $facture->mode_reglement_id = $this->mode_reglement_id;
1208 $facture->origin = $this->origin;
1209 $facture->origin_id = $this->origin_id;
1210 $facture->fk_account = $this->fk_account;
1212 $facture->lines = $this->lines;
1213 $facture->situation_counter = $this->situation_counter;
1214 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1215 $facture->situation_final = $this->situation_final;
1217 $facture->retained_warranty = $this->retained_warranty;
1218 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1219 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1221 $facture->fk_user_author = $user->id;
1222 $facture->user_creation_id = $user->id;
1226 foreach ($facture->lines as $i => $tmpline) {
1227 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1228 if ($invertdetail) {
1229 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1230 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1231 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1232 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1233 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1234 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1235 $facture->lines[$i]->ref_ext =
'';
1239 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1241 $facid = $facture->create($user);
1243 $this->error = $facture->error;
1244 $this->errors = $facture->errors;
1248 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1249 foreach ($Tfk_object as $fk_object) {
1250 $facture->add_object_linked($typeObject, $fk_object);
1254 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1270 global
$conf, $hookmanager;
1284 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1285 $objsoc =
new Societe($this->db);
1287 if ($objsoc->fetch($this->socid) > 0) {
1289 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1290 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1292 $object->fk_delivery_address = 0;
1304 $object->user_creation_id = $user->id;
1305 $object->user_validation_id =
null;
1306 $object->fk_user_author = $user->id;
1307 $object->fk_user_valid =
null;
1308 $object->fk_facture_source = 0;
1309 $object->fk_fac_rec_source = 0;
1311 $object->date_modification =
'';
1312 $object->date_validation =
'';
1323 foreach (
$object->lines as $i => $line) {
1324 '@phan-var-force FactureLigne $line';
1325 if (($line->info_bits & 0x02) == 0x02) {
1332 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1344 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1345 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1349 $object->lines[$i]->date_start = $newFirst;
1350 $object->lines[$i]->date_end = $newLast;
1354 $object->lines[$i]->ref_ext =
'';
1358 $object->context[
'createfromclone'] =
'createfromclone';
1359 $result =
$object->create($user);
1362 $this->error =
$object->error;
1363 $this->errors =
$object->errors;
1366 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1368 $this->error =
$object->error;
1369 $this->errors =
$object->errors;
1370 } elseif (
$object->socid == $objFrom->socid) {
1372 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1374 $this->error =
$object->error;
1375 $this->errors =
$object->errors;
1382 if (is_object($hookmanager)) {
1383 $parameters = array(
'objFrom' => $objFrom);
1385 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1393 unset(
$object->context[
'createfromclone']);
1397 $this->db->commit();
1400 $this->db->rollback();
1414 global
$conf, $hookmanager;
1423 for ($i = 0; $i < $num; $i++) {
1425 $src_line =
$object->lines[$i];
1426 '@phan-var-force FactureLigne $src_line';
1427 $line->libelle = $src_line->libelle;
1428 $line->label = $src_line->label;
1429 $line->desc = $src_line->desc;
1430 $line->subprice = $src_line->subprice;
1431 $line->total_ht = $src_line->total_ht;
1432 $line->total_tva = $src_line->total_tva;
1433 $line->total_localtax1 = $src_line->total_localtax1;
1434 $line->total_localtax2 = $src_line->total_localtax2;
1435 $line->total_ttc = $src_line->total_ttc;
1436 $line->vat_src_code = $src_line->vat_src_code;
1437 $line->tva_tx = $src_line->tva_tx;
1438 $line->localtax1_tx = $src_line->localtax1_tx;
1439 $line->localtax2_tx = $src_line->localtax2_tx;
1440 $line->qty = $src_line->qty;
1441 $line->fk_remise_except = $src_line->fk_remise_except;
1442 $line->remise_percent = $src_line->remise_percent;
1443 $line->fk_product = $src_line->fk_product;
1444 $line->info_bits = $src_line->info_bits;
1445 $line->product_type = $src_line->product_type;
1446 $line->rang = $src_line->rang;
1447 $line->special_code = $src_line->special_code;
1448 $line->fk_parent_line = $src_line->fk_parent_line;
1449 $line->fk_unit = $src_line->fk_unit;
1450 $line->date_start = $src_line->date_start;
1451 $line->date_end = $src_line->date_end;
1454 $line->fk_multicurrency = $src_line->fk_multicurrency;
1455 $line->multicurrency_code = $src_line->multicurrency_code;
1456 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1457 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1458 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1459 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1461 $line->fk_fournprice = $src_line->fk_fournprice;
1462 $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);
1463 $line->pa_ht = $marginInfos[0];
1466 $src_line->fetch_optionals();
1467 foreach ($src_line->array_options as $options_key => $value) {
1468 $line->array_options[$options_key] = $value;
1471 $this->lines[$i] = $line;
1474 $this->socid =
$object->socid;
1475 $this->fk_project =
$object->fk_project;
1476 $this->fk_account =
$object->fk_account;
1477 $this->cond_reglement_id =
$object->cond_reglement_id;
1478 $this->mode_reglement_id =
$object->mode_reglement_id;
1479 $this->fk_incoterms =
$object->fk_incoterms;
1480 $this->location_incoterms =
$object->location_incoterms;
1481 $this->availability_id =
$object->availability_id;
1482 $this->demand_reason_id =
$object->demand_reason_id;
1483 $this->delivery_date =
$object->delivery_date;
1484 $this->fk_delivery_address =
$object->fk_delivery_address;
1485 $this->contact_id =
$object->contact_id;
1486 $this->ref_client =
$object->ref_client;
1489 $this->note_private =
$object->note_private;
1490 $this->note_public =
$object->note_public;
1493 $this->module_source =
$object->module_source;
1494 $this->pos_source =
$object->pos_source;
1496 $this->origin =
$object->element;
1497 $this->origin_type =
$object->element;
1498 $this->origin_id =
$object->id;
1500 $this->fk_user_author = $user->id;
1504 foreach (
$object->array_options as $options_key => $value) {
1505 $this->array_options[$options_key] = $value;
1509 $this->linked_objects[$this->origin] = $this->origin_id;
1510 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1511 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1514 $ret = $this->
create($user);
1518 $hookmanager->initHooks(array(
'invoicedao'));
1520 $parameters = array(
'objFrom' =>
$object);
1522 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1548 global
$conf, $hookmanager;
1556 $use_all_lines = empty($lines);
1558 for ($i = 0; $i < $num; $i++) {
1559 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1565 $line->libelle =
$object->lines[$i]->libelle;
1566 $line->label =
$object->lines[$i]->label;
1567 $line->desc =
$object->lines[$i]->desc;
1568 $line->subprice =
$object->lines[$i]->subprice;
1569 $line->total_ht =
$object->lines[$i]->total_ht;
1570 $line->total_tva =
$object->lines[$i]->total_tva;
1571 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1572 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1573 $line->total_ttc =
$object->lines[$i]->total_ttc;
1574 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1575 $line->tva_tx =
$object->lines[$i]->tva_tx;
1576 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1577 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1578 $line->qty =
$object->lines[$i]->qty;
1579 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1580 $line->remise_percent =
$object->lines[$i]->remise_percent;
1581 $line->fk_product =
$object->lines[$i]->fk_product;
1582 $line->info_bits =
$object->lines[$i]->info_bits;
1583 $line->product_type =
$object->lines[$i]->product_type;
1584 $line->rang =
$object->lines[$i]->rang;
1585 $line->special_code =
$object->lines[$i]->special_code;
1586 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1587 $line->fk_unit =
$object->lines[$i]->fk_unit;
1588 $line->date_start =
$object->lines[$i]->date_start;
1589 $line->date_end =
$object->lines[$i]->date_end;
1592 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1593 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1594 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1595 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1596 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1597 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1599 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1601 $line->pa_ht = $marginInfos[0];
1604 $object->lines[$i]->fetch_optionals();
1605 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1606 $line->array_options[$options_key] = $value;
1609 $this->lines[$i] = $line;
1612 $this->socid =
$object->socid;
1613 $this->fk_project =
$object->fk_project;
1614 $this->fk_account =
$object->fk_account;
1615 $this->cond_reglement_id =
$object->cond_reglement_id;
1616 $this->mode_reglement_id =
$object->mode_reglement_id;
1617 $this->availability_id =
$object->availability_id;
1618 $this->demand_reason_id =
$object->demand_reason_id;
1619 $this->delivery_date =
$object->delivery_date;
1620 $this->fk_delivery_address =
$object->fk_delivery_address;
1621 $this->contact_id =
$object->contact_id;
1622 $this->ref_client =
$object->ref_client;
1625 $this->note_private =
$object->note_private;
1626 $this->note_public =
$object->note_public;
1629 $this->module_source =
$object->module_source;
1630 $this->pos_source =
$object->pos_source;
1632 $this->origin =
$object->element;
1633 $this->origin_id =
$object->id;
1635 $this->fk_user_author = $user->id;
1639 foreach (
$object->array_options as $options_key => $value) {
1640 $this->array_options[$options_key] = $value;
1644 $this->linked_objects[$this->origin] = $this->origin_id;
1645 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1646 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1649 $ret = $this->
create($user);
1653 $hookmanager->initHooks(array(
'invoicedao'));
1655 $parameters = array(
'objFrom' =>
$object);
1657 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1687 global
$conf, $langs, $hookmanager, $action;
1689 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1690 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1695 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1699 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1702 $origin->error =
'ErrorDateIsInFuture';
1706 if ($payment_terms_id <= 0) {
1707 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1711 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1713 if (empty($payment_conditions_deposit_percent)) {
1714 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1718 if (empty($origin->deposit_percent)) {
1719 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1723 $deposit =
new self($origin->db);
1724 $deposit->socid = $origin->socid;
1726 $deposit->fk_project = $origin->fk_project;
1727 $deposit->ref_client = $origin->ref_client;
1728 $deposit->date = $date;
1729 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1730 $deposit->cond_reglement_id = $payment_terms_id;
1731 $deposit->availability_id = $origin->availability_id;
1732 $deposit->demand_reason_id = $origin->demand_reason_id;
1733 $deposit->fk_account = $origin->fk_account;
1734 $deposit->fk_incoterms = $origin->fk_incoterms;
1735 $deposit->location_incoterms = $origin->location_incoterms;
1736 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1737 $deposit->multicurrency_code = $origin->multicurrency_code;
1738 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1739 $deposit->module_source = $origin->module_source;
1740 $deposit->pos_source = $origin->pos_source;
1741 $deposit->model_pdf =
'crabe';
1743 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1752 $deposit->note_private = $origin->note_private;
1753 $deposit->note_public = $origin->note_public;
1756 $deposit->origin = $origin->element;
1757 $deposit->origin_id = $origin->id;
1759 $origin->fetch_optionals();
1761 foreach ($origin->array_options as $extrakey => $value) {
1762 $deposit->array_options[$extrakey] = $value;
1765 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1767 foreach ($overrideFields as $key => $value) {
1768 $deposit->$key = $value;
1771 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1773 $origin->db->begin();
1776 $createReturn = $deposit->create($user, $notrigger);
1778 if ($createReturn <= 0) {
1779 $origin->db->rollback();
1780 $origin->error = $deposit->error;
1781 $origin->errors = $deposit->errors;
1785 $amount_ttc_diff = 0;
1786 $amountdeposit = array();
1787 $descriptions = array();
1790 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1792 $TTotalByTva = array();
1793 foreach ($origin->lines as &$line) {
1794 if (!empty($line->special_code)) {
1797 $key = $line->tva_tx;
1798 if (!array_key_exists($key, $TTotalByTva)) {
1799 $TTotalByTva[$key] = 0;
1800 $descriptions[$key] =
'';
1802 $TTotalByTva[$key] += $line->total_ttc;
1803 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1804 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1805 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1806 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1809 foreach ($TTotalByTva as $tva => &$total) {
1810 $coef = $total / $origin->total_ttc;
1811 $am = $amount * $coef;
1812 $amount_ttc_diff += $am;
1813 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1817 $lines = $origin->lines;
1818 $numlines = count($lines);
1819 for ($i = 0; $i < $numlines; $i++) {
1820 if (empty($lines[$i]->qty)) {
1823 if (!empty($lines[$i]->special_code)) {
1827 $totalamount += $lines[$i]->total_ht;
1828 $tva_tx = $lines[$i]->tva_tx;
1829 $amountdeposit[$tva_tx] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1830 $descriptions[$tva_tx] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1831 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1832 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1833 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1836 if ($totalamount == 0) {
1837 $amountdeposit[0] = 0;
1840 $amount_ttc_diff = $amountdeposit[0];
1843 foreach ($amountdeposit as $tva => $amount) {
1844 if (empty($amount)) {
1848 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1851 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1852 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1855 $addlineResult = $deposit->addline(
1882 if ($addlineResult < 0) {
1883 $origin->db->rollback();
1884 $origin->error = $deposit->error;
1885 $origin->errors = $deposit->errors;
1890 $diff = $deposit->total_ttc - $amount_ttc_diff;
1893 $deposit->fetch_lines();
1894 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1896 $updatelineResult = $deposit->updateline(
1897 $deposit->lines[0]->id,
1898 $deposit->lines[0]->desc,
1900 $deposit->lines[0]->qty,
1901 $deposit->lines[0]->remise_percent,
1902 $deposit->lines[0]->date_start,
1903 $deposit->lines[0]->date_end,
1904 $deposit->lines[0]->tva_tx,
1908 $deposit->lines[0]->info_bits,
1909 $deposit->lines[0]->product_type,
1913 $deposit->lines[0]->pa_ht,
1914 $deposit->lines[0]->label,
1920 if ($updatelineResult < 0) {
1921 $origin->db->rollback();
1922 $origin->error = $deposit->error;
1923 $origin->errors = $deposit->errors;
1928 $hookmanager->initHooks(array(
'invoicedao'));
1930 $parameters = array(
'objFrom' => $origin);
1931 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1934 $origin->db->rollback();
1935 $origin->error = $hookmanager->error;
1936 $origin->errors = $hookmanager->errors;
1940 if (!empty($autoValidateDeposit)) {
1941 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1943 if ($validateReturn < 0) {
1944 $origin->db->rollback();
1945 $origin->error = $deposit->error;
1946 $origin->errors = $deposit->errors;
1951 unset($deposit->context[
'createdepositfromorigin']);
1953 $origin->db->commit();
1967 global
$conf, $langs, $mysoc, $user;
1969 $langs->load(
'bills');
1972 $moretitle = $params[
'moretitle'] ??
'';
1974 $picto = $this->picto;
1975 if ($this->
type == self::TYPE_REPLACEMENT) {
1978 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1981 if ($this->
type == self::TYPE_DEPOSIT) {
1985 if ($user->hasRight(
"facture",
"read")) {
1986 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1988 $datas[
'picto'] .=
' '.$this->getLibType(1);
1991 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
1994 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
1997 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
2000 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2001 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2004 $datas[
'picto'] .=
' - '.$moretitle;
2006 if (!empty($this->
ref)) {
2007 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2009 if (!empty($this->ref_customer)) {
2010 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
2012 if (!empty($this->date)) {
2013 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
2015 if (!empty($this->total_ht)) {
2016 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2018 if (!empty($this->total_tva)) {
2019 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2021 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2022 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1,
$conf->currency);
2024 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2026 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency);
2028 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2029 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency);
2031 if (!empty($this->total_ttc)) {
2032 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2053 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2055 global $langs,
$conf, $user;
2057 if (!empty(
$conf->dol_no_mouse_hover)) {
2063 if ($option ==
'withdraw') {
2064 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2066 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2069 if (!$user->hasRight(
"facture",
"read")) {
2073 if ($option !==
'nolink') {
2075 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2076 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2077 $add_save_lastsearch_values = 1;
2079 if ($add_save_lastsearch_values) {
2080 $url .=
'&save_lastsearch_values=1';
2088 $picto = $this->picto;
2089 if ($this->
type == self::TYPE_REPLACEMENT) {
2092 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2095 if ($this->
type == self::TYPE_DEPOSIT) {
2101 'objecttype' => $this->element,
2102 'moretitle' => $moretitle,
2103 'option' => $option,
2105 $classfortooltip =
'classfortooltip';
2108 $classfortooltip =
'classforajaxtooltip';
2109 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2115 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2116 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2118 $label = $langs->trans(
"Invoice");
2119 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2121 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2122 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2125 $linkstart =
'<a href="'.$url.
'"';
2126 $linkstart .= $linkclose.
'>';
2129 if ($option ==
'nolink') {
2134 $result .= $linkstart;
2136 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2138 if ($withpicto != 2) {
2139 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2141 $result .= $linkend;
2143 if ($addlinktonotes) {
2144 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2147 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2148 $result .=
' <span class="note inline-block">';
2149 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
2154 $result .=
'</span>';
2158 global $action, $hookmanager;
2159 $hookmanager->initHooks(array(
'invoicedao'));
2160 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2161 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2163 $result = $hookmanager->resPrint;
2165 $result .= $hookmanager->resPrint;
2181 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2183 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2187 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2188 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2189 $sql .=
', f.datef as df, f.date_pointoftax';
2190 $sql .=
', f.date_lim_reglement as dlr';
2191 $sql .=
', f.datec as datec';
2192 $sql .=
', f.date_valid as datev';
2193 $sql .=
', f.tms as datem';
2194 $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';
2195 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2196 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2197 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2198 $sql .=
', f.fk_account';
2199 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2200 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2201 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2202 $sql .=
', f.fk_incoterms, f.location_incoterms';
2203 $sql .=
', f.module_source, f.pos_source';
2204 $sql .=
", i.libelle as label_incoterms";
2205 $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";
2206 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
2207 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2208 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
2209 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2212 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2214 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2216 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2219 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2223 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2224 $resql = $this->db->query($sql);
2226 if ($this->db->num_rows($resql)) {
2227 $obj = $this->db->fetch_object($resql);
2229 $this->
id = $obj->rowid;
2230 $this->entity = $obj->entity;
2232 $this->
ref = $obj->ref;
2233 $this->ref_client = $obj->ref_client;
2234 $this->ref_customer = $obj->ref_client;
2235 $this->ref_ext = $obj->ref_ext;
2236 $this->
type = $obj->type;
2237 $this->subtype = $obj->subtype;
2238 $this->date = $this->db->jdate($obj->df);
2239 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2240 $this->date_creation = $this->db->jdate($obj->datec);
2241 $this->date_validation = $this->db->jdate($obj->datev);
2242 $this->date_modification = $this->db->jdate($obj->datem);
2243 $this->datem = $this->db->jdate($obj->datem);
2244 $this->total_ht = $obj->total_ht;
2245 $this->total_tva = $obj->total_tva;
2246 $this->total_localtax1 = $obj->localtax1;
2247 $this->total_localtax2 = $obj->localtax2;
2248 $this->total_ttc = $obj->total_ttc;
2249 $this->revenuestamp = $obj->revenuestamp;
2250 $this->paye = $obj->paye;
2251 $this->close_code = $obj->close_code;
2252 $this->close_note = $obj->close_note;
2254 $this->socid = $obj->fk_soc;
2255 $this->thirdparty =
null;
2257 $this->fk_project = $obj->fk_project;
2258 $this->project =
null;
2260 $this->statut = $obj->status;
2261 $this->
status = $obj->status;
2263 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2264 $this->mode_reglement_id = $obj->fk_mode_reglement;
2265 $this->mode_reglement_code = $obj->mode_reglement_code;
2266 $this->mode_reglement = $obj->mode_reglement_libelle;
2267 $this->cond_reglement_id = $obj->fk_cond_reglement;
2268 $this->cond_reglement_code = $obj->cond_reglement_code;
2269 $this->cond_reglement = $obj->cond_reglement_libelle;
2270 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2271 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2272 $this->fk_facture_source = $obj->fk_facture_source;
2273 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2274 $this->note = $obj->note_private;
2275 $this->note_private = $obj->note_private;
2276 $this->note_public = $obj->note_public;
2277 $this->user_creation_id = $obj->fk_user_author;
2278 $this->user_validation_id = $obj->fk_user_valid;
2279 $this->user_modification_id = $obj->fk_user_modif;
2280 $this->fk_user_author = $obj->fk_user_author;
2281 $this->fk_user_valid = $obj->fk_user_valid;
2282 $this->fk_user_modif = $obj->fk_user_modif;
2283 $this->model_pdf = $obj->model_pdf;
2284 $this->last_main_doc = $obj->last_main_doc;
2285 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2286 $this->situation_counter = $obj->situation_counter;
2287 $this->situation_final = $obj->situation_final;
2288 $this->retained_warranty = $obj->retained_warranty;
2289 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2290 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2292 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2295 $this->fk_incoterms = $obj->fk_incoterms;
2296 $this->location_incoterms = $obj->location_incoterms;
2297 $this->label_incoterms = $obj->label_incoterms;
2299 $this->module_source = $obj->module_source;
2300 $this->pos_source = $obj->pos_source;
2303 $this->fk_multicurrency = $obj->fk_multicurrency;
2304 $this->multicurrency_code = $obj->multicurrency_code;
2305 $this->multicurrency_tx = $obj->multicurrency_tx;
2306 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2307 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2308 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2310 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2319 $this->lines = array();
2323 $this->error = $this->db->error();
2327 $this->db->free($resql);
2331 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2333 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2337 $this->error = $this->db->lasterror();
2352 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2355 $this->lines = array();
2357 $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,';
2358 $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,';
2359 $sql .=
' l.situation_percent, l.fk_prev_id,';
2360 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2361 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2362 $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,';
2363 $sql .=
' l.fk_unit,';
2364 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2365 $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';
2366 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2367 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2368 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2369 $sql .=
' ORDER BY l.rang, l.rowid';
2371 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2372 $result = $this->db->query($sql);
2374 $num = $this->db->num_rows($result);
2377 $objp = $this->db->fetch_object($result);
2380 $line->id = $objp->rowid;
2381 $line->rowid = $objp->rowid;
2382 $line->fk_facture = $objp->fk_facture;
2383 $line->label = $objp->custom_label;
2384 $line->desc = $objp->description;
2385 $line->description = $objp->description;
2386 $line->product_type = $objp->product_type;
2387 $line->ref = $objp->product_ref;
2388 $line->product_ref = $objp->product_ref;
2389 $line->libelle = $objp->product_label;
2390 $line->product_label = $objp->product_label;
2391 $line->product_barcode = $objp->product_barcode;
2392 $line->product_desc = $objp->product_desc;
2393 $line->fk_product_type = $objp->fk_product_type;
2394 $line->qty = $objp->qty;
2395 $line->subprice = $objp->subprice;
2396 $line->ref_ext = $objp->ref_ext;
2398 $line->vat_src_code = $objp->vat_src_code;
2399 $line->tva_tx = $objp->tva_tx;
2400 $line->localtax1_tx = $objp->localtax1_tx;
2401 $line->localtax2_tx = $objp->localtax2_tx;
2402 $line->localtax1_type = $objp->localtax1_type;
2403 $line->localtax2_type = $objp->localtax2_type;
2404 $line->remise_percent = $objp->remise_percent;
2405 $line->fk_remise_except = $objp->fk_remise_except;
2406 $line->fk_product = $objp->fk_product;
2407 $line->date_start = $this->db->jdate($objp->date_start);
2408 $line->date_end = $this->db->jdate($objp->date_end);
2409 $line->info_bits = $objp->info_bits;
2410 $line->total_ht = $objp->total_ht;
2411 $line->total_tva = $objp->total_tva;
2412 $line->total_localtax1 = $objp->total_localtax1;
2413 $line->total_localtax2 = $objp->total_localtax2;
2414 $line->total_ttc = $objp->total_ttc;
2416 $line->fk_fournprice = $objp->fk_fournprice;
2417 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2418 $line->pa_ht = $marginInfos[0];
2419 $line->marge_tx = (string) $marginInfos[1];
2420 $line->marque_tx = (string) $marginInfos[2];
2421 $line->rang = $objp->rang;
2422 $line->special_code = $objp->special_code;
2423 $line->fk_parent_line = $objp->fk_parent_line;
2424 $line->situation_percent = $objp->situation_percent;
2425 $line->fk_prev_id = $objp->fk_prev_id;
2426 $line->fk_unit = $objp->fk_unit;
2428 $line->batch = $objp->batch;
2429 $line->fk_warehouse = $objp->fk_warehouse;
2432 $line->fk_accounting_account = $objp->fk_code_ventilation;
2435 $line->fk_multicurrency = $objp->fk_multicurrency;
2436 $line->multicurrency_code = $objp->multicurrency_code;
2437 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2438 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2439 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2440 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2442 $line->fetch_optionals();
2445 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2446 $tmpproduct =
new Product($this->db);
2447 $tmpproduct->fetch($objp->fk_product);
2448 $tmpproduct->getMultiLangs();
2450 $line->multilangs = $tmpproduct->multilangs;
2453 $this->lines[$i] = $line;
2457 $this->db->free($result);
2460 $this->error = $this->db->error();
2475 $this->tab_previous_situation_invoice = array();
2476 $this->tab_next_situation_invoice = array();
2478 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2479 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2480 $sql .=
' AND entity = '.((int) $this->entity);
2481 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2482 $sql .=
' ORDER BY situation_counter ASC';
2484 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2485 $result = $this->db->query($sql);
2486 if ($result && $this->db->num_rows($result) > 0) {
2487 while ($objp = $this->db->fetch_object($result)) {
2488 $invoice =
new Facture($this->db);
2489 if ($invoice->fetch($objp->rowid) > 0) {
2490 if ($objp->situation_counter < $this->situation_counter
2491 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2493 $this->tab_previous_situation_invoice[] = $invoice;
2495 $this->tab_next_situation_invoice[] = $invoice;
2514 if (empty($this->
type)) {
2517 if (isset($this->subtype)) {
2518 $this->subtype = (int) trim((
string) $this->subtype);
2520 if (isset($this->
ref)) {
2521 $this->
ref = trim($this->
ref);
2523 if (isset($this->ref_ext)) {
2524 $this->ref_ext = trim($this->ref_ext);
2527 if (!empty($this->ref_client)) {
2528 $this->ref_client = trim($this->ref_client);
2530 if (!empty($this->ref_customer)) {
2531 $this->ref_customer = trim($this->ref_customer);
2533 if (isset($this->increment)) {
2534 $this->increment = trim($this->increment);
2536 if (isset($this->close_code)) {
2537 $this->close_code = trim($this->close_code);
2539 if (isset($this->close_note)) {
2540 $this->close_note = trim($this->close_note);
2542 if (isset($this->note) || isset($this->note_private)) {
2543 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2545 if (isset($this->note) || isset($this->note_private)) {
2546 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2548 if (isset($this->note_public)) {
2549 $this->note_public = trim($this->note_public);
2551 if (isset($this->model_pdf)) {
2552 $this->model_pdf = trim($this->model_pdf);
2554 if (isset($this->import_key)) {
2555 $this->import_key = trim($this->import_key);
2557 if (isset($this->retained_warranty)) {
2558 $this->retained_warranty = (float) $this->retained_warranty;
2560 if (!isset($this->user_creation_id) && isset($this->fk_user_author) ) {
2561 $this->user_creation_id = $this->fk_user_author;
2563 if (!isset($this->user_validation_id) && isset($this->fk_user_valid) ) {
2564 $this->user_validation_id = $this->fk_user_valid;
2568 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2569 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2570 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2571 $sql .=
" type=".(isset($this->
type) ? $this->db->escape($this->
type) :
"null").
",";
2572 $sql .=
" subtype=".(isset($this->subtype) ? $this->db->escape($this->subtype) :
"null").
",";
2573 $sql .=
" ref_client=".(!empty($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2574 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2575 $sql .=
" fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) :
"null").
",";
2576 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2577 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2578 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2579 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2580 $sql .=
" paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).
",";
2581 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2582 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2583 $sql .=
" total_tva=".(isset($this->total_tva) ? (float) $this->total_tva :
"null").
",";
2584 $sql .=
" localtax1=".(isset($this->total_localtax1) ? (float) $this->total_localtax1 :
"null").
",";
2585 $sql .=
" localtax2=".(isset($this->total_localtax2) ? (float) $this->total_localtax2 :
"null").
",";
2586 $sql .=
" total_ht=".(isset($this->total_ht) ? (float) $this->total_ht :
"null").
",";
2587 $sql .=
" total_ttc=".(isset($this->total_ttc) ? (float) $this->total_ttc :
"null").
",";
2588 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2589 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2590 $sql .=
" fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) :
"null").
",";
2591 $sql .=
" fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id :
"null").
",";
2592 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2593 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2594 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2595 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2596 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2597 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2598 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2599 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2600 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2601 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2602 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2603 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2604 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2605 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2606 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2607 $sql .=
" WHERE rowid=".((int) $this->
id);
2611 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2612 $resql = $this->db->query($sql);
2615 $this->errors[] =
"Error ".$this->db->lasterror();
2625 if (!$error && !$notrigger) {
2636 foreach ($this->errors as $errmsg) {
2637 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2638 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2640 $this->db->rollback();
2643 $this->db->commit();
2661 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2662 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2667 $result = $remise->fetch($idremise);
2670 if ($remise->fk_facture) {
2671 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2672 $this->db->rollback();
2677 $facligne->fk_facture = $this->id;
2678 $facligne->fk_remise_except = $remise->id;
2679 $facligne->desc = $remise->description;
2680 $facligne->vat_src_code = $remise->vat_src_code;
2681 $facligne->tva_tx = $remise->tva_tx;
2682 $facligne->subprice = -(float) $remise->amount_ht;
2683 $facligne->fk_product = 0;
2685 $facligne->remise_percent = 0;
2686 $facligne->rang = -1;
2687 $facligne->info_bits = 2;
2690 $facligne->rang = 1;
2691 $linecount = count($this->lines);
2692 for ($ii = 1; $ii <= $linecount; $ii++) {
2698 if ($remise->fk_facture_source > 0) {
2699 $srcinvoice =
new Facture($this->db);
2700 $srcinvoice->fetch($remise->fk_facture_source);
2701 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2703 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2704 $facligne->pa_ht = $arraytmp[
'pa_total'];
2707 $facligne->total_ht = -(float) $remise->amount_ht;
2708 $facligne->total_tva = -(float) $remise->amount_tva;
2709 $facligne->total_ttc = -(float) $remise->amount_ttc;
2711 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2712 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_amount_ht;
2713 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_amount_tva;
2714 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_amount_ttc;
2716 $lineid = $facligne->insert();
2721 $result = $remise->link_to_invoice($lineid, 0);
2723 $this->error = $remise->error;
2724 $this->db->rollback();
2728 $this->db->commit();
2731 $this->error = $facligne->error;
2732 $this->db->rollback();
2736 $this->error = $facligne->error;
2737 $this->db->rollback();
2741 $this->db->rollback();
2763 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2764 if (empty($ref_client)) {
2765 $sql .=
' SET ref_client = NULL';
2767 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2769 $sql .=
" WHERE rowid = ".((int) $this->
id);
2771 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2772 $resql = $this->db->query($sql);
2774 $this->errors[] = $this->db->error();
2779 $this->ref_client = $ref_client;
2780 $this->ref_customer = $ref_client;
2783 if (!$notrigger && empty($error)) {
2793 $this->ref_client = $ref_client;
2794 $this->ref_customer = $ref_client;
2796 $this->db->commit();
2799 foreach ($this->errors as $errmsg) {
2800 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2801 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2803 $this->db->rollback();
2816 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2818 global $langs,
$conf;
2819 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2823 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2836 if (!$error && !$notrigger) {
2850 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2864 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2865 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2866 $sql .=
' AND fk_facture_line IS NULL';
2867 $resql = $this->db->query($sql);
2871 $list_rowid_det = array();
2872 foreach ($this->lines as $key => $invoiceline) {
2873 $list_rowid_det[] = $invoiceline->id;
2877 if (count($list_rowid_det)) {
2878 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2879 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2880 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
2882 if (!$this->db->query($sql)) {
2883 $this->error = $this->db->error().
" sql=".$sql;
2884 $this->errors[] = $this->error;
2885 $this->db->rollback();
2892 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2893 $sql .=
' SET fk_invoice = NULL';
2894 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2896 if (!$this->db->query($sql)) {
2897 $this->error = $this->db->error().
" sql=".$sql;
2898 $this->errors[] = $this->error;
2899 $this->db->rollback();
2903 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
2904 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2905 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2907 if (!$this->db->query($sql)) {
2908 $this->error = $this->db->error().
" sql=".$sql;
2909 $this->errors[] = $this->error;
2910 $this->db->rollback();
2915 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
2916 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2917 $langs->load(
"agenda");
2919 $num = count($this->lines);
2920 for ($i = 0; $i < $num; $i++) {
2921 if ($this->lines[$i]->fk_product > 0) {
2923 $mouvP->origin = &$this;
2924 $mouvP->setOrigin($this->element, $this->
id);
2926 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2927 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2929 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2936 $main = MAIN_DB_PREFIX.
'facturedet';
2937 $ef = $main.
"_extrafields";
2938 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2940 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2943 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2945 $resql = $this->db->query($sql);
2953 if ($conf->facture->dir_output && !empty($this->
ref)) {
2954 $dir =
$conf->facture->dir_output.
"/".$ref;
2955 $file =
$conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2956 if (file_exists($file)) {
2960 $langs->load(
"errors");
2961 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2962 $this->errors[] = $this->error;
2963 $this->db->rollback();
2967 if (file_exists($dir)) {
2969 $langs->load(
"errors");
2970 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2971 $this->errors[] = $this->error;
2972 $this->db->rollback();
2978 $this->db->commit();
2981 $this->error = $this->db->lasterror().
" sql=".$sql;
2982 $this->errors[] = $this->error;
2983 $this->db->rollback();
2987 $this->error = $this->db->lasterror().
" sql=".$sql;
2988 $this->errors[] = $this->error;
2989 $this->db->rollback();
2993 $this->db->rollback();
3010 public function set_paid($user, $close_code =
'', $close_note =
'')
3013 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3014 return $this->
setPaid($user, $close_code, $close_note);
3027 public function setPaid($user, $close_code =
'', $close_note =
'')
3031 if ($this->paye != 1) {
3036 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3038 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3039 $sql .=
' fk_statut='.self::STATUS_CLOSED;
3044 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3047 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3049 $sql .=
', fk_user_closing = '.((int) $user->id);
3050 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3051 $sql .=
" WHERE rowid = ".((int) $this->
id);
3053 $resql = $this->db->query($sql);
3063 $this->error = $this->db->lasterror();
3067 $this->db->commit();
3070 $this->db->rollback();
3093 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3111 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3112 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3113 $sql .=
' date_closing=null,';
3114 $sql .=
' fk_user_closing=null';
3115 $sql .=
" WHERE rowid = ".((int) $this->
id);
3117 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3118 $resql = $this->db->query($sql);
3128 $this->error = $this->db->error();
3133 $this->db->commit();
3136 $this->db->rollback();
3158 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3159 return $this->
setCanceled($user, $close_code, $close_note);
3172 public function setCanceled($user, $close_code =
'', $close_note =
'')
3174 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3179 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3180 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3182 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3185 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3187 $sql .=
', fk_user_closing = '.((int) $user->id);
3188 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3189 $sql .=
" WHERE rowid = ".((int) $this->
id);
3191 $resql = $this->db->query($sql);
3195 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3196 $sql .=
' SET fk_facture = NULL';
3197 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3199 $resql = $this->db->query($sql);
3204 $this->db->rollback();
3209 $this->db->commit();
3212 $this->error = $this->db->error().
" sql=".$sql;
3213 $this->db->rollback();
3217 $this->error = $this->db->error().
" sql=".$sql;
3218 $this->db->rollback();
3234 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3236 global
$conf, $langs, $mysoc;
3237 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3239 $productStatic =
null;
3240 $warehouseStatic =
null;
3241 $productbatch =
null;
3242 if ($batch_rule > 0) {
3243 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3244 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3245 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3246 $productStatic =
new Product($this->db);
3247 $warehouseStatic =
new Entrepot($this->db);
3254 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3261 if ($this->
status != self::STATUS_DRAFT) {
3262 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3265 if (count($this->lines) <= 0) {
3266 $langs->load(
"errors");
3267 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3271 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3272 $this->error =
'Permission denied';
3273 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3276 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3284 if (!$last_of_type[0]) {
3285 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3291 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3292 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'TVA_INTRA',
'ACCOUNTANCY_CODE_CUSTOMER');
3293 foreach ($array_to_check as $key) {
3294 $keymin = strtolower($key);
3295 if (!property_exists($this->thirdparty, $keymin)) {
3298 $vallabel = $this->thirdparty->$keymin;
3300 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3302 if ($this->thirdparty->isACompany()) {
3304 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3305 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3307 $langs->load(
"errors");
3308 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3309 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3315 if ($key ==
'EMAIL') {
3318 $langs->load(
"errors");
3319 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3320 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3324 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3326 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3327 $langs->load(
"errors");
3328 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3329 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3333 if ($key ==
'TVA_INTRA') {
3336 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3337 $langs->load(
"errors");
3338 $this->error = $langs->trans(
'ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3339 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3342 } elseif (
getDolGlobalString(
'SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3343 $langs->load(
"errors");
3344 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3345 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3354 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3355 foreach ($array_to_check as $key => $val) {
3356 $keymin = strtolower($key);
3357 $vallabel = $this->$keymin;
3360 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3362 $langs->load(
"errors");
3364 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3371 if ($this->
type == self::TYPE_REPLACEMENT) {
3373 if ($this->fk_facture_source <= 0) {
3374 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3375 $this->db->rollback();
3380 $facreplaced =
new Facture($this->db);
3381 $result = $facreplaced->fetch($this->fk_facture_source);
3383 $this->error = $langs->trans(
"ErrorBadInvoice");
3384 $this->db->rollback();
3389 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3390 if ($idreplacement && $idreplacement != $this->
id) {
3391 $facreplacement =
new Facture($this->db);
3392 $facreplacement->fetch($idreplacement);
3393 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3394 $this->db->rollback();
3398 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3400 $this->error = $facreplaced->error;
3401 $this->db->rollback();
3407 if ($force_number) {
3408 $num = $force_number;
3409 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3422 $this->oldref = $this->ref;
3430 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3431 $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).
"'";
3433 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3434 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3436 $sql .=
" WHERE rowid = ".((int) $this->
id);
3438 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3439 $resql = $this->db->query($sql);
3441 $this->error = $this->db->lasterror();
3448 $result = $this->thirdparty->setAsCustomer();
3451 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3452 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3453 $langs->load(
"agenda");
3456 $cpt = count($this->lines);
3457 for ($i = 0; $i < $cpt; $i++) {
3458 if ($this->lines[$i]->fk_product > 0) {
3460 $mouvP->origin = &$this;
3461 $mouvP->setOrigin($this->element, $this->
id);
3464 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3467 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3470 $this->error = $mouvP->error;
3471 $this->errors = array_merge($this->errors, $mouvP->errors);
3477 $is_batch_line =
false;
3478 if ($batch_rule > 0) {
3479 $productStatic->fetch($this->lines[$i]->fk_product);
3480 if ($productStatic->hasbatch() && is_object($productbatch)) {
3481 $is_batch_line =
true;
3482 $product_qty_remain = $this->lines[$i]->qty;
3488 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3489 $sortorder =
'ASC,ASC,ASC,ASC';
3492 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_ALLOW_NEGATIVE_TRANSFER') ?
null : 0), $sortfield, $sortorder);
3493 if (!is_array($resBatchList)) {
3495 $this->error = $this->db->lasterror();
3499 $batchList = $resBatchList;
3500 if (empty($batchList)) {
3502 $langs->load(
'errors');
3503 $warehouseStatic->fetch($idwarehouse);
3504 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3505 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3508 foreach ($batchList as $batch) {
3509 if ($batch->qty <= 0) {
3514 if ($batch->qty >= $product_qty_remain) {
3515 $product_batch_qty = $product_qty_remain;
3518 $product_batch_qty = $batch->qty;
3520 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3523 $this->error = $mouvP->error;
3524 $this->errors = array_merge($this->errors, $mouvP->errors);
3528 $product_qty_remain -= $product_batch_qty;
3530 if ($product_qty_remain <= 0) {
3535 if (!$error && $product_qty_remain > 0) {
3538 $batch = $batchList[0];
3539 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3542 $this->error = $mouvP->error;
3543 $this->errors = array_merge($this->errors, $mouvP->errors);
3547 $langs->load(
'errors');
3548 $warehouseStatic->fetch($idwarehouse);
3549 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3550 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3557 if (!$is_batch_line) {
3558 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3561 $this->error = $mouvP->error;
3562 $this->errors = array_merge($this->errors, $mouvP->errors);
3574 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3575 $invoice_situation =
new Facture($this->db);
3576 $result = $invoice_situation->fetch($this->fk_facture_source);
3577 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3578 $invoice_situation->situation_final = 0;
3580 $result = $invoice_situation->setFinal($user, 1);
3583 $this->error = $invoice_situation->error;
3584 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3590 if (!$error && !$notrigger) {
3601 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3603 $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).
"'";
3604 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
3605 $resql = $this->db->query($sql);
3608 $this->error = $this->db->lasterror();
3610 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3611 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
3612 $resql = $this->db->query($sql);
3615 $this->error = $this->db->lasterror();
3631 $this->date_validation = $now;
3636 $nboflines = count($this->lines);
3637 while (($i < $nboflines) && $final) {
3638 $line = $this->lines[$i];
3639 '@phan-var-force FactureLigne $line';
3641 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3642 $current_progress = (float) $line->situation_percent;
3643 $full_progress = $previousprogress + $current_progress;
3644 $final = ($full_progress == 100);
3646 $final = ($line->situation_percent == 100);
3651 if (empty($final)) {
3652 $this->situation_final = 0;
3654 $this->situation_final = 1;
3663 if (!$error && preg_match(
'/^[\(]?PROV/i', $this->oldref)) {
3667 $dirsource =
$conf->facture->dir_output.
'/'.$oldref;
3668 $dirdest =
$conf->facture->dir_output.
'/'.$newref;
3669 if (!$error && file_exists($dirsource)) {
3670 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3672 if (@rename($dirsource, $dirdest)) {
3675 $listoffiles =
dol_dir_list(
$conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3676 foreach ($listoffiles as $fileentry) {
3677 $dirsource = $fileentry[
'name'];
3678 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3679 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3680 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3681 @rename($dirsource, $dirdest);
3688 $this->db->commit();
3691 $this->db->rollback();
3704 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3705 $is_last = $next_invoice->is_last_in_cycle();
3707 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
3708 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3712 foreach ($next_invoice->lines as $line) {
3713 '@phan-var-force FactureLigne $line';
3714 $result = $next_invoice->updateline(
3719 $line->remise_percent,
3723 $line->localtax1_tx,
3724 $line->localtax2_tx,
3727 $line->product_type,
3728 $line->fk_parent_line,
3730 $line->fk_fournprice,
3733 $line->special_code,
3734 $line->array_options,
3735 $line->situation_percent,
3740 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3761 global
$conf, $langs;
3765 if ($this->
status == self::STATUS_DRAFT) {
3766 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3774 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3775 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3776 $sql .=
" WHERE rowid = ".((int) $this->
id);
3778 $result = $this->db->query($sql);
3781 $this->oldcopy = clone $this;
3785 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL')) {
3786 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3787 $langs->load(
"agenda");
3789 $num = count($this->lines);
3790 for ($i = 0; $i < $num; $i++) {
3791 if ($this->lines[$i]->fk_product > 0) {
3793 $mouvP->origin = &$this;
3794 $mouvP->setOrigin($this->element, $this->
id);
3796 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3797 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3799 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3806 $old_statut = $this->status;
3811 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3814 $this->statut = $old_statut;
3815 $this->
status = $old_statut;
3819 $this->db->rollback();
3824 $this->db->commit();
3827 $this->db->rollback();
3831 $this->error = $this->db->error();
3832 $this->db->rollback();
3887 $remise_percent = 0,
3890 $fk_code_ventilation = 0,
3892 $fk_remise_except = 0,
3893 $price_base_type =
'HT',
3900 $fk_parent_line = 0,
3901 $fk_fournprice =
null,
3904 $array_options = array(),
3905 $situation_percent = 100,
3910 $noupdateafterinsertline = 0
3914 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3918 global $mysoc,
$conf, $langs;
3920 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);
3922 if ($this->
status == self::STATUS_DRAFT) {
3923 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3926 if (empty($remise_percent)) {
3927 $remise_percent = 0;
3932 if (empty($info_bits)) {
3938 if (empty($fk_code_ventilation)) {
3939 $fk_code_ventilation = 0;
3941 if (empty($txtva)) {
3944 if (empty($txlocaltax1)) {
3947 if (empty($txlocaltax2)) {
3950 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3951 $fk_parent_line = 0;
3953 if (empty($fk_prev_id)) {
3954 $fk_prev_id =
'null';
3956 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
3959 $situation_percent = 0;
3961 $situation_percent = 100;
3964 if (empty($ref_ext)) {
3968 $remise_percent = (float)
price2num($remise_percent);
3972 $pu_ht_devise = (float)
price2num($pu_ht_devise);
3976 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
3979 $txlocaltax1 = (float)
price2num($txlocaltax1);
3980 $txlocaltax2 = (float)
price2num($txlocaltax2);
3982 if ($price_base_type ==
'HT') {
3993 if ($date_start && $date_end && $date_start > $date_end) {
3994 $langs->load(
"errors");
3995 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4001 $product_type = $type;
4002 if (!empty($fk_product) && $fk_product > 0) {
4003 $product =
new Product($this->db);
4004 $result = $product->fetch($fk_product);
4005 $product_type = $product->type;
4007 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4008 $langs->load(
"errors");
4009 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4010 $this->db->rollback();
4020 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4021 $vat_src_code = $reg[1];
4022 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4030 $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);
4032 $total_ht = $tabprice[0];
4033 $total_tva = $tabprice[1];
4034 $total_ttc = $tabprice[2];
4035 $total_localtax1 = $tabprice[9];
4036 $total_localtax2 = $tabprice[10];
4037 $pu_ht = $tabprice[3];
4040 $multicurrency_total_ht = $tabprice[16];
4041 $multicurrency_total_tva = $tabprice[17];
4042 $multicurrency_total_ttc = $tabprice[18];
4043 $pu_ht_devise = $tabprice[19];
4047 if ($ranktouse == -1) {
4048 $rangmax = $this->
line_max($fk_parent_line);
4049 $ranktouse = $rangmax + 1;
4055 $this->line->context = $this->context;
4057 $this->line->fk_facture = $this->id;
4058 $this->line->label = $label;
4059 $this->line->desc = $desc;
4060 $this->line->ref_ext = $ref_ext;
4062 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : (float) $qty);
4063 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs((
float) $pu_ht) : (float) $pu_ht);
4065 $this->line->vat_src_code = $vat_src_code;
4066 $this->line->tva_tx = $txtva;
4067 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4068 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4069 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4070 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4072 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4073 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4074 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4075 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_localtax1) : (float) $total_localtax1);
4076 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_localtax2) : (float) $total_localtax2);
4078 $this->line->fk_product = $fk_product;
4079 $this->line->product_type = $product_type;
4080 $this->line->remise_percent = $remise_percent;
4081 $this->line->date_start = $date_start;
4082 $this->line->date_end = $date_end;
4083 $this->line->fk_code_ventilation = $fk_code_ventilation;
4084 $this->line->rang = $ranktouse;
4085 $this->line->info_bits = $info_bits;
4086 $this->line->fk_remise_except = $fk_remise_except;
4088 $this->line->special_code = $special_code;
4089 $this->line->fk_parent_line = $fk_parent_line;
4090 $this->line->origin = $origin;
4091 $this->line->origin_id = $origin_id;
4092 $this->line->situation_percent = $situation_percent;
4093 $this->line->fk_prev_id = $fk_prev_id;
4094 $this->line->fk_unit = $fk_unit;
4097 $this->line->fk_fournprice = $fk_fournprice;
4098 $this->line->pa_ht = $pa_ht;
4101 $this->line->fk_multicurrency = $this->fk_multicurrency;
4102 $this->line->multicurrency_code = $this->multicurrency_code;
4103 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4105 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4106 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4107 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4109 if (is_array($array_options) && count($array_options) > 0) {
4110 $this->line->array_options = $array_options;
4113 $result = $this->line->insert();
4116 if (empty($noupdateafterinsertline)) {
4120 if (!isset($this->context[
'createfromclone'])) {
4121 if (!empty($fk_parent_line)) {
4124 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4126 $linecount = count($this->lines);
4127 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4132 $this->lines[] = $this->line;
4136 $this->db->commit();
4137 return $this->line->id;
4139 $this->error = $this->db->lasterror();
4140 $this->db->rollback();
4144 $this->error = $this->line->error;
4145 $this->errors = $this->line->errors;
4146 $this->db->rollback();
4150 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4151 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4187 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)
4193 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4196 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4198 global $mysoc, $langs;
4200 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);
4202 if ($this->
status == self::STATUS_DRAFT) {
4205 if (!$this->error) {
4206 $this->error = $langs->trans(
'invoiceLineProgressError');
4212 if ($date_start && $date_end && $date_start > $date_end) {
4213 $langs->load(
"errors");
4214 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4224 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4225 $fk_parent_line = 0;
4227 if (empty($special_code) || $special_code == 3) {
4230 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
4233 $situation_percent = 0;
4235 $situation_percent = 100;
4238 if (empty($ref_ext)) {
4242 $remise_percent = (float)
price2num($remise_percent);
4246 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4249 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4252 $txlocaltax1 = (float)
price2num($txlocaltax1);
4253 $txlocaltax2 = (float)
price2num($txlocaltax2);
4269 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4270 $vat_src_code = $reg[1];
4271 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4274 $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);
4276 $total_ht = $tabprice[0];
4277 $total_tva = $tabprice[1];
4278 $total_ttc = $tabprice[2];
4279 $total_localtax1 = $tabprice[9];
4280 $total_localtax2 = $tabprice[10];
4281 $pu_ht = $tabprice[3];
4282 $pu_tva = $tabprice[4];
4283 $pu_ttc = $tabprice[5];
4286 $multicurrency_total_ht = $tabprice[16];
4287 $multicurrency_total_tva = $tabprice[17];
4288 $multicurrency_total_ttc = $tabprice[18];
4289 $pu_ht_devise = $tabprice[19];
4294 if ($remise_percent > 0) {
4295 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4296 $price = ((float) $pu - $remise);
4302 $line->fetch($rowid);
4303 $line->fetch_optionals();
4305 if (!empty($line->fk_product)) {
4306 $product =
new Product($this->db);
4307 $result = $product->fetch($line->fk_product);
4308 $product_type = $product->type;
4310 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4311 $langs->load(
"errors");
4312 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4313 $this->db->rollback();
4318 $staticline = clone $line;
4320 $line->oldline = $staticline;
4321 $this->line = $line;
4322 $this->line->context = $this->context;
4323 $this->line->rang = $rang;
4326 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4327 $rangmax = $this->
line_max($fk_parent_line);
4328 $this->line->rang = $rangmax + 1;
4330 $apply_abs_price_on_credit_note=
false;
4332 $apply_abs_price_on_credit_note =
true;
4336 $this->line->id = $rowid;
4337 $this->line->rowid = $rowid;
4338 $this->line->label = $label;
4339 $this->line->desc = $desc;
4340 $this->line->ref_ext = $ref_ext;
4341 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4343 $this->line->vat_src_code = $vat_src_code;
4344 $this->line->tva_tx = $txtva;
4345 $this->line->localtax1_tx = $txlocaltax1;
4346 $this->line->localtax2_tx = $txlocaltax2;
4347 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4348 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4350 $this->line->remise_percent = $remise_percent;
4351 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4352 $this->line->date_start = $date_start;
4353 $this->line->date_end = $date_end;
4354 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4355 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4356 $this->line->total_localtax1 = (float) $total_localtax1;
4357 $this->line->total_localtax2 = (float) $total_localtax2;
4358 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4359 $this->line->info_bits = $info_bits;
4360 $this->line->special_code = $special_code;
4361 $this->line->product_type = $type;
4362 $this->line->fk_parent_line = $fk_parent_line;
4363 $this->line->skip_update_total = $skip_update_total;
4364 $this->line->situation_percent = $situation_percent;
4365 $this->line->fk_unit = $fk_unit;
4367 $this->line->fk_fournprice = $fk_fournprice;
4368 $this->line->pa_ht = $pa_ht;
4371 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4372 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4373 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4374 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4376 if (is_array($array_options) && count($array_options) > 0) {
4378 foreach ($array_options as $key => $value) {
4379 $this->line->array_options[$key] = $array_options[$key];
4383 $result = $this->line->update($user, $notrigger);
4386 if (!empty($fk_parent_line)) {
4392 $this->db->commit();
4395 $this->error = $this->line->error;
4396 $this->db->rollback();
4400 $this->error =
"Invoice statut makes operation forbidden";
4414 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4415 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4416 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4418 $result = $this->db->query($sql);
4420 $this->error = $this->db->error();
4424 $obj = $this->db->fetch_object($result);
4426 if ($obj ===
null) {
4429 return ($situation_percent < $obj->situation_percent);
4445 global $mysoc, $user;
4448 if (($line->info_bits & 2) == 2) {
4452 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4455 if ($percent > 100) {
4459 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4460 $current_progress = $percent - $previous_progress;
4461 $line->situation_percent = $current_progress;
4462 $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);
4464 $line->situation_percent = $percent;
4465 $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);
4467 $line->total_ht = (float) $tabprice[0];
4468 $line->total_tva = (float) $tabprice[1];
4469 $line->total_ttc = (float) $tabprice[2];
4470 $line->total_localtax1 = (float) $tabprice[9];
4471 $line->total_localtax2 = (float) $tabprice[10];
4472 $line->multicurrency_total_ht = (float) $tabprice[16];
4473 $line->multicurrency_total_tva = (float) $tabprice[17];
4474 $line->multicurrency_total_ttc = (float) $tabprice[18];
4475 $line->update($user);
4478 if ($update_price) {
4494 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4496 if ($this->
status != self::STATUS_DRAFT) {
4497 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4503 $line->context = $this->context;
4506 $result = $line->fetch($rowid);
4507 if (!($result > 0)) {
4512 if ($id > 0 && $line->fk_facture != $id) {
4513 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4520 $staticline = clone $line;
4521 $line->oldline = $staticline;
4523 if ($line->delete($user) > 0) {
4527 $this->db->commit();
4530 $this->db->rollback();
4531 $this->error = $this->db->lasterror();
4535 $this->db->rollback();
4536 $this->error = $line->error;
4555 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4557 return $this->
setDiscount($user, $remise, $notrigger);
4571 if (empty($remise)) {
4575 if ($user->hasRight(
'facture',
'creer')) {
4576 $remise = (float)
price2num($remise, 2);
4582 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4583 $sql .=
" SET remise_percent = ".((float) $remise);
4584 $sql .=
" WHERE rowid = ".((int) $this->
id);
4585 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
4588 $resql = $this->db->query($sql);
4590 $this->errors[] = $this->db->error();
4594 if (!$notrigger && empty($error)) {
4604 $this->remise_percent = $remise;
4607 $this->db->commit();
4610 foreach ($this->errors as $errmsg) {
4611 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4612 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4614 $this->db->rollback();
4701 global
$conf, $langs;
4703 if ($this->module_source ==
'takepos') {
4704 $langs->load(
'cashdesk');
4706 $moduleName =
'takepos';
4707 $moduleSourceName =
'Takepos';
4708 $addonConstName =
'TAKEPOS_REF_ADDON';
4712 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4717 $langs->load(
'bills');
4719 $moduleName =
'facture';
4720 $moduleSourceName =
'Invoice';
4721 $addonConstName =
'FACTURE_ADDON';
4725 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4727 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4729 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4735 if (!empty($addon)) {
4736 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4740 $file = $addon.
'.php';
4741 $classname = $addon;
4745 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
4746 foreach ($dirmodels as $reldir) {
4747 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4750 if (is_file($dir.$file) && is_readable($dir.$file)) {
4751 $mybool = ((bool) include_once $dir.$file) || $mybool;
4757 $file = $addon.
'/'.$addon.
'.modules.php';
4758 $classname =
'mod_'.$moduleName.
'_'.$addon;
4759 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4761 foreach (
$conf->file->dol_document_root as $dirroot) {
4762 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4765 if (is_file($dir.$file) && is_readable($dir.$file)) {
4766 $mybool = (include_once $dir.$file) || $mybool;
4776 $obj =
new $classname();
4777 '@phan-var-force ModeleNumRefFactures $obj';
4779 $numref = $obj->getNextValue($soc, $this, $mode);
4786 if ($mode !=
'last' && !$numref) {
4787 $this->error = $obj->error;
4793 $langs->load(
'errors');
4794 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4807 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4808 $sql .=
' date_closing as dateclosing,';
4809 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4810 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4811 $sql .=
' WHERE c.rowid = '.((int) $id);
4813 $result = $this->db->query($sql);
4815 if ($this->db->num_rows($result)) {
4816 $obj = $this->db->fetch_object($result);
4818 $this->
id = $obj->rowid;
4819 $this->user_creation_id = $obj->fk_user_author;
4820 $this->user_validation_id = $obj->fk_user_valid;
4821 $this->user_closing_id = $obj->fk_user_closing;
4823 $this->date_creation = $this->db->jdate($obj->datec);
4824 $this->date_modification = $this->db->jdate($obj->datem);
4825 $this->date_validation = $this->db->jdate($obj->datev);
4826 $this->date_closing = $this->db->jdate($obj->dateclosing);
4828 $this->db->free($result);
4849 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4856 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4857 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4858 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4859 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4860 $sql .=
" AND f.fk_soc = s.rowid";
4862 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4864 if (is_object($excluser)) {
4865 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4869 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
4870 $search_sale = $user->id;
4873 if ($search_sale && $search_sale !=
'-1') {
4874 if ($search_sale == -2) {
4875 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
4876 } elseif ($search_sale > 0) {
4877 $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).
")";
4882 $sql .=
" AND f.fk_soc = ".((int) $socid);
4884 $sql .= $this->db->order($sortfield, $sortorder);
4885 $sql .= $this->db->plimit($limit, $offset);
4887 $result = $this->db->query($sql);
4889 $numc = $this->db->num_rows($result);
4892 while ($i < $numc) {
4893 $obj = $this->db->fetch_object($result);
4895 if ($shortlist == 1) {
4896 $ga[$obj->fid] = $obj->ref;
4897 } elseif ($shortlist == 2) {
4898 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4900 $ga[$i][
'id'] = $obj->fid;
4901 $ga[$i][
'ref'] = $obj->ref;
4902 $ga[$i][
'name'] = $obj->name;
4931 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4932 $sql .=
" ff.rowid as rowidnext";
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";
4937 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4938 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4939 $sql .=
" AND f.paye = 0";
4940 $sql .=
" AND pf.fk_paiement IS NULL";
4941 $sql .=
" AND ff.fk_statut IS NULL";
4943 $sql .=
" AND f.fk_soc = ".((int) $socid);
4946 $sql .=
" ORDER BY f.ref";
4948 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4949 $resql = $this->db->query($sql);
4951 while ($obj = $this->db->fetch_object($resql)) {
4952 $return[$obj->rowid] = array(
4953 'id' => $obj->rowid,
4955 'status' => $obj->status,
4956 'paid' => $obj->paid,
4963 $this->error = $this->db->error();
4987 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
4988 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4989 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4990 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4991 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4992 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4996 $sql .=
" AND ff.type IS NULL";
4997 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
5001 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
5002 $sql .=
'(SELECT MAX(fs.rowid)';
5003 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
5004 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
5005 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
5006 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5008 $sql .=
" AND fs.fk_soc = ".((int) $socid);
5010 $sql .=
" GROUP BY fs.situation_cycle_ref)";
5013 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
5017 $sql .=
" AND f.fk_soc = ".((int) $socid);
5019 $sql .=
" ORDER BY f.ref";
5021 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
5022 $resql = $this->db->query($sql);
5024 while ($obj = $this->db->fetch_object($resql)) {
5026 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5029 if ($obj->fk_statut == self::STATUS_CLOSED) {
5034 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5035 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
5041 $this->error = $this->db->error();
5057 global
$conf, $langs;
5061 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5062 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5063 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5064 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5065 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5068 $sql .= $clause.
" f.paye=0";
5069 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5070 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5072 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5075 $resql = $this->db->query($sql);
5077 $langs->load(
"bills");
5081 $response->warning_delay =
$conf->facture->client->warning_delay / 60 / 60 / 24;
5082 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5083 $response->labelShort = $langs->trans(
"Unpaid");
5084 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5087 $generic_facture =
new Facture($this->db);
5089 while ($obj = $this->db->fetch_object($resql)) {
5090 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5091 $generic_facture->statut = $obj->status;
5092 $generic_facture->status = $obj->status;
5094 $response->nbtodo++;
5095 $response->total += $obj->total_ht;
5097 if ($generic_facture->hasDelay()) {
5098 $response->nbtodolate++;
5099 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5103 $this->db->free($resql);
5107 $this->error = $this->db->error();
5146 global
$conf, $langs, $user;
5150 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5155 $sql =
"SELECT rowid";
5156 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5157 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5158 $sql .= $this->db->plimit(100);
5160 $resql = $this->db->query($sql);
5162 $num_prods = $this->db->num_rows($resql);
5164 while ($i < $num_prods) {
5166 $row = $this->db->fetch_row($resql);
5167 $prodids[$i] = $row[0];
5171 if (empty($num_prods)) {
5173 $prodids[$num_prods] = 1;
5178 $this->entity =
$conf->entity;
5179 $this->
ref =
'SPECIMEN';
5180 $this->specimen = 1;
5182 $this->date = $nownotime;
5183 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5184 $this->cond_reglement_id = 1;
5185 $this->cond_reglement_code =
'RECEP';
5187 $this->mode_reglement_id = 0;
5188 $this->mode_reglement_code =
'';
5190 $this->note_public =
'This is a comment (public)';
5191 $this->note_private =
'This is a comment (private)';
5192 $this->note =
'This is a comment (private)';
5194 $this->fk_user_author = $user->id;
5196 $this->multicurrency_tx = 1;
5197 $this->multicurrency_code =
$conf->currency;
5199 $this->fk_incoterms = 0;
5200 $this->location_incoterms =
'';
5202 if (empty($option) || $option !=
'nolines') {
5206 while ($xnbp < $nbp) {
5208 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5210 $line->subprice = 100;
5211 $line->tva_tx = 19.6;
5212 $line->localtax1_tx = 0;
5213 $line->localtax2_tx = 0;
5214 $line->remise_percent = 0;
5216 $prodid = mt_rand(1, $num_prods);
5217 $line->fk_product = $prodids[$prodid];
5219 $line->total_ht = -100;
5220 $line->total_ttc = -119.6;
5221 $line->total_tva = -19.6;
5222 $line->multicurrency_total_ht = -200;
5223 $line->multicurrency_total_ttc = -239.2;
5224 $line->multicurrency_total_tva = -39.2;
5225 } elseif ($xnbp == 2) {
5226 $line->subprice = -100;
5227 $line->total_ht = -100;
5228 $line->total_ttc = -119.6;
5229 $line->total_tva = -19.6;
5230 $line->remise_percent = 0;
5231 $line->multicurrency_total_ht = -200;
5232 $line->multicurrency_total_ttc = -239.2;
5233 $line->multicurrency_total_tva = -39.2;
5234 } elseif ($xnbp == 3) {
5235 $prodid = mt_rand(1, $num_prods);
5236 $line->fk_product = $prodids[$prodid];
5237 $line->total_ht = 50;
5238 $line->total_ttc = 59.8;
5239 $line->total_tva = 9.8;
5240 $line->multicurrency_total_ht = 100;
5241 $line->multicurrency_total_ttc = 119.6;
5242 $line->multicurrency_total_tva = 19.6;
5243 $line->remise_percent = 50;
5245 $prodid = mt_rand(1, $num_prods);
5246 $line->fk_product = $prodids[$prodid];
5247 $line->total_ht = 100;
5248 $line->total_ttc = 119.6;
5249 $line->total_tva = 19.6;
5250 $line->multicurrency_total_ht = 200;
5251 $line->multicurrency_total_ttc = 239.2;
5252 $line->multicurrency_total_tva = 39.2;
5253 $line->remise_percent = 0;
5256 $this->lines[$xnbp] = $line;
5259 $this->total_ht += $line->total_ht;
5260 $this->total_tva += $line->total_tva;
5261 $this->total_ttc += $line->total_ttc;
5263 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5264 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5265 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5269 $this->revenuestamp = 0;
5273 $line->desc = $langs->trans(
"Description").
" (offered line)";
5275 $line->subprice = 100;
5276 $line->tva_tx = 19.6;
5277 $line->localtax1_tx = 0;
5278 $line->localtax2_tx = 0;
5279 $line->remise_percent = 100;
5280 $line->total_ht = 0;
5281 $line->total_ttc = 0;
5282 $line->total_tva = 0;
5283 $line->multicurrency_total_ht = 0;
5284 $line->multicurrency_total_ttc = 0;
5285 $line->multicurrency_total_tva = 0;
5286 $prodid = mt_rand(1, $num_prods);
5287 $line->fk_product = $prodids[$prodid];
5289 $this->lines[$xnbp] = $line;
5303 global
$conf, $user;
5305 $this->nb = array();
5309 $sql =
"SELECT count(f.rowid) as nb";
5310 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5311 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5312 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5313 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5314 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5317 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
5319 $resql = $this->db->query($sql);
5321 while ($obj = $this->db->fetch_object($resql)) {
5322 $this->nb[
"invoices"] = $obj->nb;
5324 $this->db->free($resql);
5328 $this->error = $this->db->error();
5354 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5356 global
$conf, $langs;
5358 $outputlangs->loadLangs(array(
"bills",
"products"));
5362 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5364 if (!empty($this->model_pdf)) {
5365 $modele = $this->model_pdf;
5373 $modelpath =
"core/modules/facture/doc/";
5375 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5385 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5386 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5387 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5389 $resql = $this->db->query($sql);
5391 if ($this->db->num_rows($resql) > 0) {
5393 $obj = $this->db->fetch_object($resql);
5395 $ref = $obj->maxsituationref;
5401 $this->db->free($resql);
5404 $this->error = $this->db->lasterror();
5405 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5419 return ($this->situation_counter == 1);
5433 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5434 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5435 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5436 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity :
$conf->entity);
5437 $resql = $this->db->query($sql);
5439 if ($resql && $this->db->num_rows($resql) > 0) {
5440 while ($row = $this->db->fetch_object($resql)) {
5442 $situation =
new Facture($this->db);
5443 $situation->fetch($id);
5444 $res[] = $situation;
5447 $this->error = $this->db->error();
5448 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5468 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5471 $resql = $this->db->query($sql);
5473 $this->errors[] = $this->db->error();
5477 if (!$notrigger && empty($error)) {
5487 $this->db->commit();
5490 foreach ($this->errors as $errmsg) {
5491 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5492 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5494 $this->db->rollback();
5510 if (!empty($this->situation_cycle_ref)) {
5512 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5513 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5514 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity :
$conf->entity);
5515 $resql = $this->db->query($sql);
5517 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5518 $last = $res[
'max(situation_counter)'];
5519 return ($last == $this->situation_counter);
5521 $this->error = $this->db->lasterror();
5522 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5580 $hasDelay = $this->date_lim_reglement < ($now -
$conf->facture->client->warning_delay);
5581 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5583 $totalpaid = (float) $totalpaid;
5585 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5586 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now -
$conf->facture->client->warning_delay)) {
5588 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now -
$conf->facture->client->warning_delay)) {
5606 return $this->situation_cycle_ref;
5619 $displayWarranty =
false;
5620 if (!empty($this->retained_warranty)) {
5621 $displayWarranty =
true;
5625 $displayWarranty =
false;
5626 if (!empty($this->situation_final)) {
5627 $displayWarranty =
true;
5630 $displayWarranty =
true;
5632 foreach ($this->lines as $i => $line) {
5633 if ($line->product_type < 2 && $line->situation_percent < 100) {
5634 $displayWarranty =
false;
5642 return $displayWarranty;
5651 if (empty($this->retained_warranty)) {
5655 $retainedWarrantyAmount = 0;
5659 $displayWarranty =
true;
5661 if (!empty($this->lines)) {
5662 foreach ($this->lines as $i => $line) {
5663 if ($line->product_type < 2 && $line->situation_percent < 100) {
5664 $displayWarranty =
false;
5670 if ($displayWarranty && !empty($this->situation_final)) {
5672 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5675 foreach ($TPreviousIncoice as &$fac) {
5676 $total2BillWT += $fac->total_ttc;
5678 $total2BillWT += $this->total_ttc;
5680 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5686 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5689 if ($rounding < 0) {
5693 if ($rounding > 0) {
5694 return round($retainedWarrantyAmount, $rounding);
5697 return $retainedWarrantyAmount;
5708 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5710 if ($this->
status >= 0) {
5711 $fieldname =
'retained_warranty';
5712 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5713 $sql .=
" SET ".$fieldname.
" = ".((float) $value);
5714 $sql .=
' WHERE rowid='.((int) $this->
id);
5716 if ($this->db->query($sql)) {
5717 $this->retained_warranty = (float) $value;
5720 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5721 $this->error = $this->db->error();
5725 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5726 $this->error =
'Status of the object is incompatible '.$this->status;
5741 if (!$timestamp && $dateYmd) {
5742 $timestamp = $this->db->jdate($dateYmd);
5746 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5747 if ($this->
status >= 0) {
5748 $fieldname =
'retained_warranty_date_limit';
5749 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5750 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5751 $sql .=
' WHERE rowid = '.((int) $this->
id);
5753 if ($this->db->query($sql)) {
5754 $this->retained_warranty_date_limit = $timestamp;
5757 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5758 $this->error = $this->db->error();
5762 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5763 $this->error =
'Status of the object is incompatible '.$this->status;
5782 global
$conf, $langs, $user;
5788 $errorsMsg = array();
5790 $langs->load(
"bills");
5792 if (!isModEnabled(
'invoice')) {
5793 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5796 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
5797 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
5807 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5808 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5809 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5810 $formmail =
new FormMail($this->db);
5815 $tmpinvoice =
new Facture($this->db);
5820 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5821 if (!empty($paymentmode) && $paymentmode !=
'all') {
5822 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5824 $sql .=
" WHERE f.paye = 0";
5825 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5826 if ($datetouse ==
'invoicedate') {
5827 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
5829 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5831 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
5832 if (!empty($paymentmode) && $paymentmode !=
'all') {
5833 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5836 if ($datetouse ==
'invoicedate') {
5837 $sql .= $this->db->order(
"datef",
"ASC");
5839 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
5842 $resql = $this->db->query($sql);
5845 if ($datetouse ==
'invoicedate') {
5846 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
5848 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5850 if (!empty($paymentmode) && $paymentmode !=
'all') {
5851 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5853 $this->output .=
'<br>';
5856 while ($obj = $this->db->fetch_object($resql)) {
5861 $res = $tmpinvoice->fetch($obj->id);
5863 $tmpinvoice->fetch_thirdparty();
5866 if ($tmpinvoice->thirdparty->default_lang) {
5867 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5868 $outputlangs->loadLangs(array(
"main",
"bills"));
5870 $outputlangs = $langs;
5874 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5875 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5876 $langs->load(
"errors");
5877 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5890 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5893 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5899 if ($forcerecipient) {
5900 $to = array($forcerecipient);
5902 $res = $tmpinvoice->fetch_thirdparty();
5903 $recipient = $tmpinvoice->thirdparty;
5905 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
5906 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5907 foreach ($tmparraycontact as $data_email) {
5908 if (!empty($data_email[
'email'])) {
5909 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
5913 if (empty($to) && !empty($recipient->email)) {
5914 $to[] = $recipient->email;
5917 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
5921 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5928 if (!empty($arraymessage->email_from)) {
5929 $from = $arraymessage->email_from;
5932 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5936 if (!$loopError && !empty($to)) {
5939 $to = implode(
',', $to);
5940 if (!empty($arraymessage->email_to)) {
5941 $to = $to.
','.$arraymessage->email_to;
5947 $trackid =
'inv'.$tmpinvoice->id;
5948 $sendcontext =
'standard';
5951 if (!empty($arraymessage->email_tocc)) {
5952 $email_tocc = $arraymessage->email_tocc;
5956 if (!empty($arraymessage->email_tobcc)) {
5957 $email_tobcc = $arraymessage->email_tobcc;
5964 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5965 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
5966 $joinFileName[] = basename($tmpinvoice->last_main_doc);
5967 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
5971 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5974 if ($cMailFile->sendfile()) {
5978 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5983 $actioncomm->type_code =
'AC_OTH_AUTO';
5984 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5985 $actioncomm->contact_id = 0;
5987 $actioncomm->code =
'AC_EMAIL';
5988 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
5989 $actioncomm->note_private = $sendContent;
5990 $actioncomm->fk_project = $tmpinvoice->fk_project;
5991 $actioncomm->datep =
dol_now();
5992 $actioncomm->datef = $actioncomm->datep;
5993 $actioncomm->percentage = -1;
5994 $actioncomm->authorid = $user->id;
5995 $actioncomm->userownerid = $user->id;
5997 $actioncomm->email_msgid = $cMailFile->msgid;
5998 $actioncomm->email_subject = $sendTopic;
5999 $actioncomm->email_from = $from;
6000 $actioncomm->email_sender =
'';
6001 $actioncomm->email_to = $to;
6005 $actioncomm->errors_to = $errors_to;
6007 $actioncomm->elementtype =
'invoice';
6008 $actioncomm->fk_element = $tmpinvoice->id;
6012 $actioncomm->create($user);
6014 $errormesg = $cMailFile->error.
' : '.$to;
6018 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6023 $actioncomm->type_code =
'AC_OTH_AUTO';
6024 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6025 $actioncomm->contact_id = 0;
6027 $actioncomm->code =
'AC_EMAIL';
6028 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
6029 $actioncomm->note_private = $errormesg;
6030 $actioncomm->fk_project = $tmpinvoice->fk_project;
6031 $actioncomm->datep =
dol_now();
6032 $actioncomm->datef = $actioncomm->datep;
6033 $actioncomm->percentage = -1;
6034 $actioncomm->authorid = $user->id;
6035 $actioncomm->userownerid = $user->id;
6037 $actioncomm->email_msgid = $cMailFile->msgid;
6038 $actioncomm->email_from = $from;
6039 $actioncomm->email_sender =
'';
6040 $actioncomm->email_to = $to;
6044 $actioncomm->errors_to = $errors_to;
6048 $actioncomm->create($user);
6051 $this->db->commit();
6055 $errorsMsg[] = $errormesg;
6058 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6062 $error += $loopError;
6069 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6071 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6075 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6077 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6092 $sql =
"SELECT datef";
6093 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6094 $sql .=
" WHERE type = " . (int) $this->
type ;
6095 $sql .=
" AND date_valid IS NOT NULL";
6096 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6097 $sql .=
" ORDER BY datef DESC LIMIT 1";
6099 $result = $this->db->query($sql);
6102 if ($this->db->num_rows($result)) {
6103 $obj = $this->db->fetch_object($result);
6104 $last_date = $this->db->jdate($obj->datef);
6105 $invoice_date = $this->date;
6107 $is_last_of_same_type = $invoice_date >= $last_date;
6108 if ($allow_validated_drafts) {
6112 return array($is_last_of_same_type, $last_date);
6135 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6137 $picto = $this->picto;
6138 if ($this->
type == self::TYPE_REPLACEMENT) {
6141 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6144 if ($this->
type == self::TYPE_DEPOSIT) {
6148 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6149 $return .=
'<div class="info-box info-box-sm">';
6150 $return .=
'<span class="info-box-icon bg-infobox-action">';
6152 $return .=
'</span>';
6153 $return .=
'<div class="info-box-content">';
6154 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6155 if ($selected >= 0) {
6156 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6158 if (!empty($arraydata[
'thirdparty'])) {
6159 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6161 if (property_exists($this,
'date')) {
6162 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->date,
'day').
'</span>';
6164 if (property_exists($this,
'total_ht')) {
6165 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6166 $return .=
' '.$langs->trans(
"HT");
6167 $return .=
'</span>';
6169 if (method_exists($this,
'getLibStatut')) {
6170 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6171 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6173 $return .=
'</div>';
6174 $return .=
'</div>';
6175 $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.
isSituationInvoice()
Check if an invoice is a situation invoice.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getTooltipContentArray($params)
getTooltipContentArray
getNextNumRef($soc, $mode='next')
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_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
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 '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
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_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.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
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