49require_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
50require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/factureligne.class.php';
51require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
52require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
53require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
54require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
55require_once DOL_DOCUMENT_ROOT.
'/subtotals/class/commonsubtotal.class.php';
58 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
61 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
74 public $element =
'facture';
79 public $TRIGGER_PREFIX =
'BILL';
84 public $table_element =
'facture';
89 public $table_element_line =
'facturedet';
94 public $class_element_line =
'FactureLigne';
99 public $fk_element =
'fk_facture';
104 public $picto =
'bill';
110 public $restrictiononfksoc = 1;
126 public $fk_user_author;
132 public $fk_user_valid;
138 public $fk_user_modif;
148 public $delivery_date;
160 public $ref_customer;
176 public $module_source;
184 public $pos_print_counter = 0;
189 public $email_sent_counter = 0;
194 public $fk_fac_rec_source;
199 public $fk_facture_source;
209 public $lines = array();
218 public $extraparams = array();
228 public $date_pointoftax;
234 public $situation_cycle_ref;
239 public $situation_counter;
244 public $situation_final;
249 public $tab_previous_situation_invoice = array();
254 public $tab_next_situation_invoice = array();
259 public $retained_warranty;
264 public $retained_warranty_date_limit;
269 public $retained_warranty_fk_cond_reglement;
274 public $availability_id;
279 public $date_closing;
290 public $remise_percent;
295 public $online_payment_url;
332 public $fields = array(
333 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 1),
334 'ref' => array(
'type' =>
'varchar(30)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'position' => 5),
335 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 20,
'index' => 1),
336 'ref_client' => array(
'type' =>
'varchar(255)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 10),
337 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'RefExt',
'enabled' => 1,
'visible' => 0,
'position' => 12),
338 'type' => array(
'type' =>
'smallint(6)',
'label' =>
'Type',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
339 'subtype' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoiceSubtype',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
341 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 50),
342 'datef' => array(
'type' =>
'date',
'label' =>
'DateInvoice',
'enabled' => 1,
'visible' => 1,
'position' => 20),
343 'date_valid' => array(
'type' =>
'date',
'label' =>
'DateValidation',
'enabled' => 1,
'visible' => -1,
'position' => 22),
344 'date_lim_reglement' => array(
'type' =>
'date',
'label' =>
'DateDue',
'enabled' => 1,
'visible' => 1,
'position' => 25),
345 'date_closing' => array(
'type' =>
'datetime',
'label' =>
'DateClosing',
'enabled' => 1,
'visible' => -1,
'position' => 30),
346 '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 'fk_input_reason' => array(
'type' =>
'integer',
'label' =>
'Source',
'enabled' => 1,
'visible' => -1,
'position' => 220),
365 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 225),
366 'situation_cycle_ref' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation cycle ref',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 230),
367 'situation_counter' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation counter',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 235),
368 'situation_final' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation final',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 240),
369 'retained_warranty' => array(
'type' =>
'double',
'label' =>
'Retained warranty',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 245),
370 'retained_warranty_date_limit' => array(
'type' =>
'date',
'label' =>
'Retained warranty date limit',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 250),
371 'retained_warranty_fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'Retained warranty fk cond reglement',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 255),
372 'fk_incoterms' => array(
'type' =>
'integer',
'label' =>
'IncotermCode',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 260),
373 'location_incoterms' => array(
'type' =>
'varchar(255)',
'label' =>
'IncotermLabel',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 265),
374 'date_pointoftax' => array(
'type' =>
'date',
'label' =>
'DatePointOfTax',
'enabled' =>
'getDolGlobalString("INVOICE_POINTOFTAX_DATE")',
'visible' => -1,
'position' => 270),
375 'fk_multicurrency' => array(
'type' =>
'integer',
'label' =>
'MulticurrencyID',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 275),
376 'multicurrency_code' => array(
'type' =>
'varchar(255)',
'label' =>
'Currency',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 280),
377 'multicurrency_tx' => array(
'type' =>
'double(24,8)',
'label' =>
'CurrencyRate',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 285,
'isameasure' => 1),
378 'multicurrency_total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountHT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 290,
'isameasure' => 1),
379 'multicurrency_total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountVAT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 291,
'isameasure' => 1),
380 'multicurrency_total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountTTC',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 292,
'isameasure' => 1),
381 'fk_fac_rec_source' => array(
'type' =>
'integer',
'label' =>
'RecurringInvoiceSource',
'enabled' => 1,
'visible' => -1,
'position' => 305),
382 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'LastMainDoc',
'enabled' => 1,
'visible' => -1,
'position' => 310),
383 'module_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSModule',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 315),
384 'pos_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSTerminal',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 320),
385 'pos_print_counter' => array(
'type' =>
'integer',
'label' =>
'PrintCount',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => 0,
'position' => 325),
386 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 500),
387 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModificationShort',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 502),
388 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'position' => 506),
389 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModification',
'enabled' => 1,
'visible' => -1,
'notnull' => -1,
'position' => 508),
390 'fk_user_valid' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserValidation',
'enabled' => 1,
'visible' => -1,
'position' => 510),
391 'fk_user_closing' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserClosing',
'enabled' => 1,
'visible' => -1,
'position' => 512),
392 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 900),
393 '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')),
472 $this->ismultientitymanaged = 1;
473 $this->isextrafieldmanaged = 1;
475 $this->fields[
'ref_ext'][
'visible'] =
getDolGlobalInt(
'MAIN_LIST_SHOW_REF_EXT');
489 public function create(
User $user, $notrigger = 0, $forceduedate = 0, $updatecurrencyrate = 0)
493 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
495 if (empty($this->
type)) {
499 $this->ref_client = trim((
string) $this->ref_client);
500 $this->ref_customer = trim((
string) $this->ref_customer);
502 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
503 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
504 $this->note_public = (isset($this->note_public) ? trim($this->note_public) :
'');
506 if (!$this->cond_reglement_id) {
507 $this->cond_reglement_id = 0;
509 if (!$this->mode_reglement_id) {
510 $this->mode_reglement_id = 0;
515 if (!empty($this->multicurrency_code)) {
517 if (empty($this->multicurrency_tx)) {
525 $this->fk_multicurrency = 0;
527 if (empty($this->fk_multicurrency)) {
528 $this->multicurrency_code =
$conf->currency;
529 $this->fk_multicurrency = 0;
530 $this->multicurrency_tx = 1;
534 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
537 if (empty($this->
date)) {
538 $this->error =
"Try to create an invoice with an empty parameter (date)";
539 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
543 $result = $soc->fetch($this->socid);
545 $this->error =
"Failed to fetch company: ".$soc->error;
546 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
551 $this->date_creation = $now;
555 $originaldatewhen =
null;
556 $nextdatewhen =
null;
557 $previousdaynextdatewhen =
null;
562 if ($this->fac_rec > 0) {
563 $this->fk_fac_rec_source = $this->fac_rec;
565 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
567 $result = $_facrec->fetch($this->fac_rec);
568 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
572 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
576 $originaldatewhen = $_facrec->date_when;
577 $nextdatewhen =
null;
578 $previousdaynextdatewhen =
null;
580 if ($originaldatewhen) {
581 if ($_facrec->rule_for_lines_dates ==
'postpaid') {
583 $originaldatewhen =
dol_time_plus_duree($originaldatewhen, -$_facrec->frequency, $_facrec->unit_frequency);
585 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, (
int) $_facrec->frequency, $_facrec->unit_frequency);
591 if (!empty($_facrec->frequency)) {
592 $this->socid = $_facrec->socid;
596 $this->entity = $_facrec->entity;
601 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
602 $this->note_public =
GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
603 $this->note_private =
GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
604 $this->model_pdf =
GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
605 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
606 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
607 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
610 $this->total_ht = $_facrec->total_ht;
611 $this->total_ttc = $_facrec->total_ttc;
614 $this->fk_incoterms = $_facrec->fk_incoterms;
615 $this->location_incoterms = $_facrec->location_incoterms;
621 $this->ref_client = trim($this->ref_client);
622 $this->ref_customer = trim($this->ref_customer);
623 $this->note_public = trim($this->note_public);
624 $this->note_private = trim($this->note_private);
625 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
628 foreach ($_facrec->array_options as $key => $val) {
629 if (!isset($this->array_options[$key]) || $this->array_options[$key] ===
'') {
630 $this->array_options[$key] = $val;
634 if (!$this->mode_reglement_id) {
635 $this->mode_reglement_id = 0;
640 $this->linked_objects = $_facrec->linkedObjectsIds;
645 if ($_facrec->frequency > 0) {
646 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
647 if (empty($_facrec->date_when)) {
648 $_facrec->date_when = $now;
650 $next_date = $_facrec->getNextDate();
652 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
655 $result = $_facrec->setNextDate($next_date, 1);
659 $outputlangs = $langs;
662 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
663 $newlang = $this->thirdparty->default_lang;
666 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
667 $newlang = $this->default_lang;
669 if (!empty($newlang)) {
671 $outputlangs->setDefaultLang($newlang);
675 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $this);
686 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
687 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
688 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
689 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
690 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
701 if (empty($forceduedate)) {
707 $this->date_lim_reglement = $duedate;
709 $this->date_lim_reglement = $forceduedate;
713 $socid = $this->socid;
715 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
724 $sql .=
", date_pointoftax";
725 $sql .=
", note_private";
726 $sql .=
", note_public";
727 $sql .=
", ref_client";
728 $sql .=
", fk_account";
729 $sql .=
", module_source, pos_source, pos_print_counter, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
730 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
731 $sql .=
", fk_input_reason";
732 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
733 $sql .=
", fk_incoterms, location_incoterms";
734 $sql .=
", fk_multicurrency";
735 $sql .=
", multicurrency_code";
736 $sql .=
", multicurrency_tx";
737 $sql .=
", retained_warranty";
738 $sql .=
", retained_warranty_date_limit";
739 $sql .=
", retained_warranty_fk_cond_reglement";
744 $sql .=
", ".(int) $this->entity;
745 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
746 $sql .=
", ".((int) $this->
type);
747 $sql .=
", ".(isset($this->subtype) ? (int) $this->subtype :
"null");
748 $sql .=
", ".((int) $socid);
749 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
752 $sql .=
", '".$this->db->idate($this->
date).
"'";
753 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
754 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
755 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
756 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
757 $sql .=
", ".($this->fk_account > 0 ? ((int) $this->fk_account) :
'NULL');
758 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
759 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape((
string) $this->pos_source).
"'" :
"null");
760 $sql .=
", ".(int) $this->pos_print_counter;
761 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape((
string) $this->fk_fac_rec_source).
"'" :
"null");
762 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape((
string) $this->fk_facture_source).
"'" :
"null");
763 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
764 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
765 $sql .=
", ".((int) $this->cond_reglement_id);
766 $sql .=
", ".((int) $this->mode_reglement_id);
767 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
768 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
769 $sql .=
", ".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id :
"null");
770 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape((
string) $this->situation_cycle_ref).
"'" :
"null");
771 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape((
string) $this->situation_counter).
"'" :
"null");
772 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
773 $sql .=
", ".(int) $this->fk_incoterms;
774 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
775 $sql .=
", ".(int) $this->fk_multicurrency;
776 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
777 $sql .=
", ".(float) $this->multicurrency_tx;
778 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape((
string) $this->retained_warranty));
779 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
780 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
781 $sql .=
", ".(!empty($this->ip) ?
"'".$this->db->escape($this->ip).
"'" :
"null");
784 $resql = $this->db->query($sql);
786 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
789 $this->
ref =
'(PROV'.$this->id.
')';
790 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
792 $resql = $this->db->query($sql);
797 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
798 $this->linked_objects = $this->linkedObjectsIds;
802 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
803 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
804 if (is_array($tmp_origin_id)) {
805 foreach ($tmp_origin_id as $origin_id) {
808 $this->error = $this->db->lasterror();
813 $origin_id = $tmp_origin_id;
816 $this->error = $this->db->lasterror();
824 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && (!empty($this->origin_type) || !empty($this->origin)) && !empty($this->origin_id)) {
825 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
826 $originidforcontact = $this->origin_id;
827 if ($originforcontact ==
'shipping') {
828 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
830 $exp->fetch($this->origin_id);
831 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
832 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
833 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
834 $originforcontact =
'commande';
835 if (is_object($value)) {
836 $originidforcontact = $value->id;
838 $originidforcontact = $value;
845 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople";
846 $sqlcontact .=
" FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
847 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
849 $resqlcontact = $this->db->query($sqlcontact);
851 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
852 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
860 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
863 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
864 foreach ($this->lines as $i => $val) {
865 $newinvoiceline = $this->lines[$i];
866 '@phan-var-force FactureLigne $newinvoiceline';
868 $newinvoiceline->context = $this->context;
870 $newinvoiceline->fk_facture = $this->id;
872 $newinvoiceline->origin = $this->lines[$i]->element;
873 $newinvoiceline->origin_type = $this->lines[$i]->element;
874 $newinvoiceline->origin_id = $this->lines[$i]->id;
877 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
878 $newinvoiceline->date_start = $originaldatewhen;
880 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
881 $newinvoiceline->date_end = $previousdaynextdatewhen;
886 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
891 $vatrate = $newinvoiceline->tva_tx;
892 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
893 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
896 $newinvoiceline->fk_parent_line = $fk_parent_line;
900 $discount->fetch($newinvoiceline->fk_remise_except);
902 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
903 $newinvoiceline->fk_remise_except = $discountId;
907 $newinvoiceline->desc,
908 $newinvoiceline->subprice,
909 $newinvoiceline->qty,
911 $newinvoiceline->localtax1_tx,
912 $newinvoiceline->localtax2_tx,
913 $newinvoiceline->fk_product,
914 $newinvoiceline->remise_percent,
915 $newinvoiceline->date_start,
916 $newinvoiceline->date_end,
917 $newinvoiceline->fk_code_ventilation,
918 $newinvoiceline->info_bits,
919 $newinvoiceline->fk_remise_except,
922 $newinvoiceline->product_type,
923 $newinvoiceline->rang,
924 $newinvoiceline->special_code,
925 $newinvoiceline->element,
928 $newinvoiceline->fk_fournprice,
929 $newinvoiceline->pa_ht,
930 $newinvoiceline->label,
931 $newinvoiceline->array_options,
932 $newinvoiceline->situation_percent,
933 $newinvoiceline->fk_prev_id,
934 $newinvoiceline->fk_unit,
935 $newinvoiceline->multicurrency_subprice,
936 $newinvoiceline->ref_ext,
947 if ($result > 0 && $newinvoiceline->product_type == 9) {
948 $fk_parent_line = $result;
952 } elseif (!$error && empty($this->fac_rec)) {
955 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
957 foreach ($this->lines as $i => $val) {
958 $line = $this->lines[$i];
959 '@phan-var-force FactureLigne $line';
963 if (!is_object($line)) {
964 $line = (object) $line;
969 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
974 $vatrate = $line->tva_tx;
975 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
976 $vatrate .=
' ('.$line->vat_src_code.
')';
980 $originid = $line->origin_id;
981 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
983 $originid = $line->id;
984 $origintype = $this->element;
988 if (empty($line->ref_ext)) {
1000 $line->remise_percent,
1003 $line->fk_code_ventilation,
1005 $line->fk_remise_except,
1008 $line->product_type,
1010 $line->special_code,
1014 $line->fk_fournprice,
1017 $line->array_options,
1018 $line->situation_percent,
1021 $line->multicurrency_subprice,
1026 $this->error = $this->db->lasterror();
1028 $this->db->rollback();
1033 if ($result > 0 && $line->product_type == 9) {
1034 $fk_parent_line = $result;
1041 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1042 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1043 $fk_parent_line = 0;
1045 foreach ($_facrec->lines as $i => $val) {
1047 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1048 $fk_parent_line = 0;
1051 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1052 $tva_npr = (int) $_facrec->lines[$i]->info_bits;
1053 if (empty($tva_tx)) {
1056 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1057 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1059 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1060 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1063 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1064 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1066 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1071 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1072 $buyprice = $producttmp->cost_price;
1074 $buyprice = $producttmp->pmp;
1076 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1077 if ($producttmp->product_fourn_price_id > 0) {
1078 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1085 if ($updatecurrencyrate == 1) {
1087 } elseif ($updatecurrencyrate == 2) {
1091 $result_insert = $this->
addline(
1092 $_facrec->lines[$i]->desc,
1093 $_facrec->lines[$i]->subprice,
1094 $_facrec->lines[$i]->qty,
1098 $_facrec->lines[$i]->fk_product,
1099 $_facrec->lines[$i]->remise_percent,
1100 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1101 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1107 $_facrec->lines[$i]->product_type,
1108 $_facrec->lines[$i]->rang,
1109 $_facrec->lines[$i]->special_code,
1113 $fk_product_fournisseur_price,
1114 is_null($buyprice) ?
'' : $buyprice,
1115 $_facrec->lines[$i]->label,
1116 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1119 $_facrec->lines[$i]->fk_unit,
1120 $_facrec->lines[$i]->multicurrency_subprice,
1121 $_facrec->lines[$i]->ref_ext,
1125 foreach ($this->lines as $line) {
1126 if ($line->id == $result_insert) {
1127 $line->extraparams = $_facrec->lines[$i]->extraparams;
1128 $line->setExtraParameters();
1133 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1134 $fk_parent_line = $result_insert;
1137 if ($result_insert < 0) {
1139 $this->error = $this->db->error();
1148 $this->error = $langs->trans(
'FailedToUpdatePrice');
1149 $this->db->rollback();
1164 if (!$error && !$notrigger) {
1166 $result = $this->call_trigger(
'BILL_CREATE', $user);
1173 $this->db->commit();
1176 $this->db->rollback();
1180 $this->error = $this->db->error();
1181 $this->db->rollback();
1197 $facture =
new Facture($this->db);
1200 $facture->context[
'createfromclone'] = 1;
1205 if (empty($this->array_options)) {
1209 if (!empty($this->array_options)) {
1210 $facture->array_options = $this->array_options;
1213 foreach ($this->lines as &$line) {
1214 $line->fetch_optionals();
1217 $facture->fk_facture_source = $this->fk_facture_source;
1218 $facture->type = $this->type;
1219 $facture->subtype = $this->subtype;
1220 $facture->socid = $this->socid;
1221 $facture->date = $this->date;
1222 $facture->date_pointoftax = $this->date_pointoftax;
1223 $facture->note_public = $this->note_public;
1224 $facture->note_private = $this->note_private;
1225 $facture->ref_client = $this->ref_client;
1226 $facture->ref_customer = $this->ref_customer;
1227 $facture->model_pdf = $this->model_pdf;
1228 $facture->fk_project = $this->fk_project;
1229 $facture->cond_reglement_id = $this->cond_reglement_id;
1230 $facture->mode_reglement_id = $this->mode_reglement_id;
1232 $facture->origin = $this->origin;
1233 $facture->origin_id = $this->origin_id;
1234 $facture->fk_account = $this->fk_account;
1236 $facture->lines = $this->lines;
1237 $facture->situation_counter = $this->situation_counter;
1238 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1239 $facture->situation_final = $this->situation_final;
1241 $facture->retained_warranty = $this->retained_warranty;
1242 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1243 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1245 $facture->fk_user_author = $user->id;
1246 $facture->user_creation_id = $user->id;
1250 foreach ($facture->lines as $i => $tmpline) {
1251 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1252 if ($invertdetail) {
1253 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1254 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1255 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1256 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1257 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1258 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1259 $facture->lines[$i]->ref_ext =
'';
1263 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1265 $facid = $facture->create($user);
1267 $this->error = $facture->error;
1268 $this->errors = $facture->errors;
1272 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1273 foreach ($Tfk_object as $fk_object) {
1274 $facture->add_object_linked($typeObject, $fk_object);
1278 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1295 global $hookmanager;
1315 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1316 $objsoc =
new Societe($this->db);
1318 if ($objsoc->fetch($this->socid) > 0) {
1320 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1321 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1323 $object->fk_delivery_address = 0;
1329 $object->entity = (!empty($forceentity) ? $forceentity :
$object->entity);
1337 $object->user_creation_id = $user->id;
1338 $object->user_validation_id =
null;
1339 $object->user_modification_id =
null;
1340 $object->fk_user_author = $user->id;
1341 $object->fk_user_valid =
null;
1342 $object->fk_facture_source = 0;
1343 $object->fk_fac_rec_source = 0;
1345 $object->date_modification =
'';
1346 $object->date_validation =
'';
1357 foreach (
$object->lines as $i => $line) {
1358 '@phan-var-force FactureLigne $line';
1359 if (($line->info_bits & 0x02) == 0x02) {
1366 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1378 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1379 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1383 $object->lines[$i]->date_start = $newFirst;
1384 $object->lines[$i]->date_end = $newLast;
1388 $object->lines[$i]->ref_ext =
'';
1391 $object->lines[$i]->fk_code_ventilation = 0;
1395 $object->context[
'createfromclone'] =
'createfromclone';
1396 $result =
$object->create($user);
1403 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1406 } elseif (
$object->socid == $objFrom->socid) {
1408 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1417 if (is_object($hookmanager)) {
1418 $parameters = array(
'objFrom' => $objFrom,
'clonedObj' =>
$object);
1420 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1428 unset(
$object->context[
'createfromclone']);
1432 $this->db->commit();
1435 $this->db->rollback();
1449 global $hookmanager;
1458 $this->context[
'createfromclone'] = 1;
1461 for ($i = 0; $i < $num; $i++) {
1463 $src_line =
$object->lines[$i];
1464 '@phan-var-force FactureLigne $src_line';
1465 $line->libelle = $src_line->libelle;
1466 $line->label = $src_line->label;
1467 $line->desc = $src_line->desc;
1468 $line->subprice = $src_line->subprice;
1469 $line->total_ht = $src_line->total_ht;
1470 $line->total_tva = $src_line->total_tva;
1471 $line->total_localtax1 = $src_line->total_localtax1;
1472 $line->total_localtax2 = $src_line->total_localtax2;
1473 $line->total_ttc = $src_line->total_ttc;
1474 $line->vat_src_code = $src_line->vat_src_code;
1475 $line->tva_tx = $src_line->tva_tx;
1476 $line->localtax1_tx = $src_line->localtax1_tx;
1477 $line->localtax2_tx = $src_line->localtax2_tx;
1478 $line->qty = $src_line->qty;
1479 $line->fk_remise_except = $src_line->fk_remise_except;
1480 $line->remise_percent = $src_line->remise_percent;
1481 $line->fk_product = $src_line->fk_product;
1482 $line->info_bits = $src_line->info_bits;
1483 $line->product_type = $src_line->product_type;
1484 $line->rang = $src_line->rang;
1485 $line->special_code = $src_line->special_code;
1486 $line->fk_parent_line = $src_line->fk_parent_line;
1487 $line->fk_unit = $src_line->fk_unit;
1488 $line->date_start = $src_line->date_start;
1489 $line->date_end = $src_line->date_end;
1492 $line->fk_multicurrency = $src_line->fk_multicurrency;
1493 $line->multicurrency_code = $src_line->multicurrency_code;
1494 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1495 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1496 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1497 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1499 $line->fk_fournprice = $src_line->fk_fournprice;
1500 $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);
1501 $line->pa_ht = $marginInfos[0];
1504 $src_line->fetch_optionals();
1505 foreach ($src_line->array_options as $options_key => $value) {
1506 $line->array_options[$options_key] = $value;
1509 $this->lines[$i] = $line;
1512 $this->socid =
$object->socid;
1513 $this->fk_project =
$object->fk_project;
1514 $this->fk_account =
$object->fk_account;
1515 $this->cond_reglement_id =
$object->cond_reglement_id;
1516 $this->mode_reglement_id =
$object->mode_reglement_id;
1517 $this->fk_incoterms =
$object->fk_incoterms;
1518 $this->location_incoterms =
$object->location_incoterms;
1519 $this->availability_id =
$object->availability_id;
1520 $this->demand_reason_id =
$object->demand_reason_id;
1521 $this->delivery_date =
$object->delivery_date;
1522 $this->fk_delivery_address =
$object->fk_delivery_address;
1523 $this->contact_id =
$object->contact_id;
1524 $this->ref_client =
$object->ref_client;
1525 $this->ref_customer =
$object->ref_client;
1528 $this->note_private =
$object->note_private;
1529 $this->note_public =
$object->note_public;
1532 $this->module_source =
$object->module_source;
1533 $this->pos_source =
$object->pos_source;
1535 $this->origin =
$object->element;
1536 $this->origin_type =
$object->element;
1537 $this->origin_id =
$object->id;
1539 $this->fk_user_author = $user->id;
1540 $this->user_creation_id = $user->id;
1544 foreach (
$object->array_options as $options_key => $value) {
1545 $this->array_options[$options_key] = $value;
1549 $this->linked_objects[$this->origin] = $this->origin_id;
1550 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1551 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1554 $ret = $this->
create($user);
1558 $hookmanager->initHooks(array(
'invoicedao'));
1560 $parameters = array(
'objFrom' =>
$object);
1562 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1571 unset($this->context[
'createfromclone']);
1590 global $hookmanager;
1598 $use_all_lines = empty($lines);
1600 for ($i = 0; $i < $num; $i++) {
1601 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1607 $line->libelle =
$object->lines[$i]->libelle;
1608 $line->label =
$object->lines[$i]->label;
1609 $line->desc =
$object->lines[$i]->desc;
1610 $line->subprice =
$object->lines[$i]->subprice;
1611 $line->total_ht =
$object->lines[$i]->total_ht;
1612 $line->total_tva =
$object->lines[$i]->total_tva;
1613 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1614 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1615 $line->total_ttc =
$object->lines[$i]->total_ttc;
1616 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1617 $line->tva_tx =
$object->lines[$i]->tva_tx;
1618 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1619 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1620 $line->qty =
$object->lines[$i]->qty;
1621 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1622 $line->remise_percent =
$object->lines[$i]->remise_percent;
1623 $line->fk_product =
$object->lines[$i]->fk_product;
1624 $line->info_bits =
$object->lines[$i]->info_bits;
1625 $line->product_type =
$object->lines[$i]->product_type;
1626 $line->rang =
$object->lines[$i]->rang;
1627 $line->special_code =
$object->lines[$i]->special_code;
1628 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1629 $line->fk_unit =
$object->lines[$i]->fk_unit;
1630 $line->date_start =
$object->lines[$i]->date_start;
1631 $line->date_end =
$object->lines[$i]->date_end;
1634 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1635 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1636 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1637 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1638 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1639 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1641 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1643 $line->pa_ht = $marginInfos[0];
1646 $object->lines[$i]->fetch_optionals();
1647 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1648 $line->array_options[$options_key] = $value;
1651 $this->lines[$i] = $line;
1654 $this->socid =
$object->socid;
1655 $this->fk_project =
$object->fk_project;
1656 $this->fk_account =
$object->fk_account;
1657 $this->cond_reglement_id =
$object->cond_reglement_id;
1658 $this->mode_reglement_id =
$object->mode_reglement_id;
1659 $this->availability_id =
$object->availability_id;
1660 $this->demand_reason_id =
$object->demand_reason_id;
1661 $this->delivery_date =
$object->delivery_date;
1662 $this->fk_delivery_address =
$object->fk_delivery_address;
1663 $this->contact_id =
$object->contact_id;
1664 $this->ref_client =
$object->ref_client;
1667 $this->note_private =
$object->note_private;
1668 $this->note_public =
$object->note_public;
1671 $this->module_source =
$object->module_source;
1672 $this->pos_source =
$object->pos_source;
1674 $this->origin =
$object->element;
1675 $this->origin_id =
$object->id;
1677 $this->fk_user_author = $user->id;
1678 $this->user_creation_id = $user->id;
1682 foreach (
$object->array_options as $options_key => $value) {
1683 $this->array_options[$options_key] = $value;
1687 $this->linked_objects[$this->origin] = $this->origin_id;
1688 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1689 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1692 $ret = $this->
create($user);
1696 $hookmanager->initHooks(array(
'invoicedao'));
1698 $parameters = array(
'objFrom' =>
$object);
1700 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1730 global
$conf, $langs, $hookmanager, $action;
1732 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1733 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1738 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1742 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1745 $origin->error =
'ErrorDateIsInFuture';
1749 if ($payment_terms_id <= 0) {
1750 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1754 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1756 if (empty($payment_conditions_deposit_percent)) {
1757 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1761 if (empty($origin->deposit_percent)) {
1762 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1766 $deposit =
new self($origin->db);
1767 $deposit->socid = $origin->socid;
1769 $deposit->fk_project = $origin->fk_project;
1770 $deposit->ref_client = $origin->ref_client;
1771 $deposit->ref_customer = $origin->ref_client;
1772 $deposit->date = $date;
1773 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1774 $deposit->cond_reglement_id = $payment_terms_id;
1775 $deposit->availability_id = $origin->availability_id;
1776 $deposit->demand_reason_id = $origin->demand_reason_id;
1777 $deposit->fk_account = $origin->fk_account;
1778 $deposit->fk_incoterms = $origin->fk_incoterms;
1779 $deposit->location_incoterms = $origin->location_incoterms;
1780 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1781 $deposit->multicurrency_code = $origin->multicurrency_code;
1782 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1783 $deposit->module_source = $origin->module_source;
1784 $deposit->pos_source = $origin->pos_source;
1785 $deposit->model_pdf =
'sponge';
1787 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1796 $deposit->note_private = $origin->note_private;
1797 $deposit->note_public = $origin->note_public;
1800 $deposit->origin = $origin->element;
1801 $deposit->origin_type = $origin->element;
1802 $deposit->origin_id = $origin->id;
1804 $origin->fetch_optionals();
1806 foreach ($origin->array_options as $extrakey => $value) {
1807 $deposit->array_options[$extrakey] = $value;
1810 $deposit->linked_objects[$deposit->origin_type] = $deposit->origin_id;
1812 foreach ($overrideFields as $key => $value) {
1813 $deposit->$key = $value;
1816 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1818 $origin->db->begin();
1821 $createReturn = $deposit->create($user, $notrigger);
1823 if ($createReturn <= 0) {
1824 $origin->db->rollback();
1825 $origin->error = $deposit->error;
1826 $origin->errors = $deposit->errors;
1830 $amount_ttc_diff = 0;
1831 $amountdeposit = array();
1832 $descriptions = array();
1839 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1841 $TTotalByTva = array();
1842 foreach ($origin->lines as &$line) {
1843 if (!empty($line->special_code)) {
1846 $key = $line->tva_tx . ($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
1847 if (!array_key_exists($key, $TTotalByTva)) {
1848 $TTotalByTva[$key] = 0;
1849 $descriptions[$key] =
'';
1851 $TTotalByTva[$key] += $line->total_ttc;
1852 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1853 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1854 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1855 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1858 foreach ($TTotalByTva as $tva => &$total) {
1859 $tva_rate_only = preg_replace(
'/\s*\(.*\)/',
'', (
string) $tva);
1860 $coef = $total / $origin->total_ttc;
1861 $am = $amount * $coef;
1862 $amount_ttc_diff += $am;
1863 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100);
1867 $lines = $origin->lines;
1868 $numlines = count($lines);
1869 for ($i = 0; $i < $numlines; $i++) {
1870 if (empty($lines[$i]->qty)) {
1873 if (!empty($lines[$i]->special_code)) {
1877 $totalamount += $lines[$i]->total_ht;
1878 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ?
' ('.$lines[$i]->vat_src_code.
')' :
'');
1879 if (!isset($amountdeposit[$tva_key])) {
1880 $amountdeposit[$tva_key] = 0;
1881 $descriptions[$tva_key] =
'';
1883 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1884 $descriptions[$tva_key] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1885 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1886 $descriptions[$tva_key] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1887 $descriptions[$tva_key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1890 if ($totalamount == 0) {
1891 $amountdeposit[0] = 0;
1894 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1897 foreach ($amountdeposit as $tva => $amount) {
1898 if (empty($amount)) {
1902 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1905 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1906 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1909 $addlineResult = $deposit->addline(
1936 if ($addlineResult < 0) {
1937 $origin->db->rollback();
1938 $origin->error = $deposit->error;
1939 $origin->errors = $deposit->errors;
1944 $diff = $deposit->total_ttc - $amount_ttc_diff;
1947 $deposit->fetch_lines();
1948 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1952 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ?
' ('.$deposit->lines[0]->vat_src_code.
')' :
'');
1953 $updatelineResult = $deposit->updateline(
1954 $deposit->lines[0]->id,
1955 $deposit->lines[0]->desc,
1957 $deposit->lines[0]->qty,
1958 $deposit->lines[0]->remise_percent,
1959 $deposit->lines[0]->date_start,
1960 $deposit->lines[0]->date_end,
1965 $deposit->lines[0]->info_bits,
1966 $deposit->lines[0]->product_type,
1970 $deposit->lines[0]->pa_ht,
1971 $deposit->lines[0]->label,
1977 if ($updatelineResult < 0) {
1978 $origin->db->rollback();
1979 $origin->error = $deposit->error;
1980 $origin->errors = $deposit->errors;
1985 $hookmanager->initHooks(array(
'invoicedao'));
1987 $parameters = array(
'objFrom' => $origin);
1988 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1991 $origin->db->rollback();
1992 $origin->error = $hookmanager->error;
1993 $origin->errors = $hookmanager->errors;
1997 if (!empty($autoValidateDeposit)) {
1998 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
2000 if ($validateReturn < 0) {
2001 $origin->db->rollback();
2002 $origin->error = $deposit->error;
2003 $origin->errors = $deposit->errors;
2008 unset($deposit->context[
'createdepositfromorigin']);
2010 $origin->db->commit();
2026 $langs->load(
'bills');
2029 $moretitle = $params[
'moretitle'] ??
'';
2031 $picto = $this->picto;
2032 if ($this->
type == self::TYPE_REPLACEMENT) {
2035 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2038 if ($this->
type == self::TYPE_DEPOSIT) {
2042 if ($user->hasRight(
"facture",
"read")) {
2043 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
2045 $datas[
'picto'] .=
' '.$this->getLibType(1);
2048 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
2051 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2054 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
2057 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2058 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2061 $datas[
'picto'] .=
' - '.$moretitle;
2063 if (!empty($this->
ref)) {
2064 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2066 if (!empty($this->ref_customer)) {
2067 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
2069 if (!empty($this->
date)) {
2070 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->
date,
'day');
2072 if (!empty($this->total_ht)) {
2073 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2075 if (!empty($this->total_tva)) {
2076 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2078 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2079 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1,
$conf->currency);
2081 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2083 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1',
$mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency);
2085 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2086 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2',
$mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency);
2088 if (!empty($this->total_ttc)) {
2089 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2110 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2112 global $langs,
$conf, $user;
2114 if (!empty(
$conf->dol_no_mouse_hover)) {
2120 if ($option ==
'withdraw') {
2121 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2123 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2126 if (!$user->hasRight(
"facture",
"read")) {
2130 if ($option !==
'nolink') {
2132 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2133 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2134 $add_save_lastsearch_values = 1;
2136 if ($add_save_lastsearch_values) {
2137 $url .=
'&save_lastsearch_values=1';
2145 $picto = $this->picto;
2146 if ($this->
type == self::TYPE_REPLACEMENT) {
2149 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2152 if ($this->
type == self::TYPE_DEPOSIT) {
2158 'objecttype' => $this->element,
2159 'moretitle' => $moretitle,
2160 'option' => $option,
2162 $classfortooltip =
'classfortooltip';
2165 $classfortooltip =
'classforajaxtooltip';
2166 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2172 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2173 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2175 $label = $langs->trans(
"Invoice");
2176 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2178 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2179 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2182 $linkstart =
'<a href="'.$url.
'"';
2183 $linkstart .= $linkclose.
'>';
2186 if ($option ==
'nolink') {
2191 $result .= $linkstart;
2193 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2195 if ($withpicto != 2) {
2196 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2198 $result .= $linkend;
2200 if ($addlinktonotes) {
2201 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2203 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2204 $result .=
' <span class="note inline-block">';
2205 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dolPrintHTMLForAttribute($notetoshow).
'">';
2208 $result .=
'</span>';
2212 global $action, $hookmanager;
2213 $hookmanager->initHooks(array(
'invoicedao'));
2214 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2215 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2217 $result = $hookmanager->resPrint;
2219 $result .= $hookmanager->resPrint;
2235 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2237 global
$conf, $extrafields;
2239 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2243 $extraFieldsCheck =
false;
2244 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2246 if ($doFetchInOneSqlRequest) {
2248 if (!isset($extrafields) || !is_object($extrafields)) {
2249 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2254 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
2255 $extrafields->fetch_name_optionals_label($this->table_element);
2258 $extraFieldsCheck = (
2259 !empty($extrafields->attributes[$this->table_element][
'label'])
2260 && is_array($extrafields->attributes[$this->table_element][
'label'])
2261 && count($extrafields->attributes[$this->table_element][
'label']) > 0
2267 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2268 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2269 $sql .=
', f.datef as df, f.date_pointoftax';
2270 $sql .=
', f.date_lim_reglement as dlr';
2271 $sql .=
', f.datec as datec';
2272 $sql .=
', f.date_valid as datev';
2273 $sql .=
', f.tms as datem';
2274 $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';
2275 $sql .=
", f.fk_input_reason";
2276 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2277 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2278 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2279 $sql .=
', f.fk_account';
2280 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2281 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2282 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2283 $sql .=
', f.fk_incoterms, f.location_incoterms';
2284 $sql .=
', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2285 $sql .=
", i.libelle as label_incoterms";
2286 $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";
2287 $sql .=
", f.payment_reference, f.dispute_status";
2289 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2290 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2291 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2292 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2295 if ($type !==
'separate') {
2296 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2297 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2299 $sql .=
", ef.".$this->db->sanitize($key);
2305 $sql .=
' FROM '.$this->db->prefix().
'facture as f';
2308 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2310 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element.
'_extrafields as ef ON f.rowid = ef.fk_object';
2313 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2314 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_paiement as p ON f.fk_mode_reglement = p.id';
2315 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2316 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2319 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2321 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2323 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2326 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2330 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2331 $resql = $this->db->query($sql);
2333 if ($this->db->num_rows($resql)) {
2334 $obj = $this->db->fetch_object($resql);
2336 $this->
id = $obj->rowid;
2337 $this->entity = $obj->entity;
2339 $this->
ref = $obj->ref;
2340 $this->ref_client = $obj->ref_client;
2341 $this->ref_customer = $obj->ref_client;
2342 $this->ref_ext = $obj->ref_ext;
2343 $this->
type = $obj->type;
2344 $this->subtype = $obj->subtype;
2345 $this->
date = $this->db->jdate($obj->df);
2346 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2347 $this->date_creation = $this->db->jdate($obj->datec);
2348 $this->date_validation = $this->db->jdate($obj->datev);
2349 $this->date_modification = $this->db->jdate($obj->datem);
2350 $this->datem = $this->db->jdate($obj->datem);
2351 $this->total_ht = $obj->total_ht;
2352 $this->total_tva = $obj->total_tva;
2353 $this->total_localtax1 = $obj->localtax1;
2354 $this->total_localtax2 = $obj->localtax2;
2355 $this->total_ttc = $obj->total_ttc;
2356 $this->revenuestamp = $obj->revenuestamp;
2357 $this->paye = $obj->paye;
2358 $this->close_code = $obj->close_code;
2359 $this->close_note = $obj->close_note;
2361 $this->socid = $obj->fk_soc;
2362 $this->thirdparty =
null;
2364 $this->fk_project = $obj->fk_project;
2365 $this->project =
null;
2367 $this->statut = $obj->status;
2368 $this->
status = $obj->status;
2370 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2371 $this->mode_reglement_id = $obj->fk_mode_reglement;
2372 $this->mode_reglement_code = $obj->mode_reglement_code;
2373 $this->mode_reglement = $obj->mode_reglement_libelle;
2374 $this->cond_reglement_id = $obj->fk_cond_reglement;
2375 $this->cond_reglement_code = $obj->cond_reglement_code;
2376 $this->cond_reglement = $obj->cond_reglement_libelle;
2377 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2378 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2379 $this->fk_facture_source = $obj->fk_facture_source;
2380 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2381 $this->note = $obj->note_private;
2382 $this->note_private = $obj->note_private;
2383 $this->note_public = $obj->note_public;
2384 $this->user_creation_id = $obj->fk_user_author;
2385 $this->user_validation_id = $obj->fk_user_valid;
2386 $this->user_modification_id = $obj->fk_user_modif;
2387 $this->fk_user_author = $obj->fk_user_author;
2388 $this->fk_user_valid = $obj->fk_user_valid;
2389 $this->fk_user_modif = $obj->fk_user_modif;
2390 $this->model_pdf = $obj->model_pdf;
2391 $this->last_main_doc = $obj->last_main_doc;
2392 $this->demand_reason_id = $obj->fk_input_reason;
2393 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2394 $this->situation_counter = $obj->situation_counter;
2395 $this->situation_final = $obj->situation_final;
2396 $this->retained_warranty = $obj->retained_warranty;
2397 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2398 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2400 $this->payment_reference = $obj->payment_reference;
2401 $this->dispute_status = $obj->dispute_status;
2403 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2406 $this->fk_incoterms = $obj->fk_incoterms;
2407 $this->location_incoterms = $obj->location_incoterms;
2408 $this->label_incoterms = $obj->label_incoterms;
2410 $this->module_source = $obj->module_source;
2411 $this->pos_source = $obj->pos_source;
2412 $this->pos_print_counter = (int) $obj->pos_print_counter;
2413 $this->email_sent_counter = $obj->email_sent_counter;
2416 $this->fk_multicurrency = $obj->fk_multicurrency;
2417 $this->multicurrency_code = $obj->multicurrency_code;
2418 $this->multicurrency_tx = $obj->multicurrency_tx;
2419 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2420 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2421 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2424 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2425 $this->array_options = array();
2427 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2428 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2429 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2432 if ($type !==
'separate') {
2433 $rawval = $obj->$key;
2436 if (in_array($type, array(
'date',
'datetime'))) {
2437 $this->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2438 } elseif ($type ==
'password') {
2439 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2440 $this->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2442 $this->array_options[
'options_' . $key] = $rawval;
2445 $this->array_options[
'options_' . $key] = $rawval;
2451 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2452 if (!empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
2453 if (empty(
$conf->disable_compute)) {
2454 global $objectoffield;
2455 $objectoffield = $this;
2456 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
2462 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2466 if (!$doFetchInOneSqlRequest) {
2473 $this->lines = array();
2477 $this->error = $this->db->error();
2481 $this->db->free($resql);
2485 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2487 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2491 $this->error = $this->db->lasterror();
2505 public function fetch_lines($only_type_product =
'', $loadalsotranslation = 0)
2507 global
$conf, $extrafields;
2510 $this->lines = array();
2512 $extraFieldsCheck =
false;
2513 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2515 if ($doFetchInOneSqlRequest) {
2517 if (!isset($extrafields) || !is_object($extrafields)) {
2518 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2523 if (empty($extrafields->attributes[$this->table_element_line][
'loaded'])) {
2524 $extrafields->fetch_name_optionals_label($this->table_element_line);
2527 $extraFieldsCheck = (
2528 !empty($extrafields->attributes[$this->table_element_line][
'label'])
2529 && is_array($extrafields->attributes[$this->table_element_line][
'label'])
2530 && count($extrafields->attributes[$this->table_element_line][
'label']) > 0
2534 $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,';
2535 $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,';
2536 $sql .=
' l.situation_percent, l.fk_prev_id,';
2537 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2538 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2539 $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,';
2540 $sql .=
' l.fk_unit, l.extraparams,';
2541 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2542 $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';
2544 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2545 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2546 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2547 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2550 if ($type !==
'separate') {
2551 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2552 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2554 $sql .=
", ef.".$this->db->sanitize($key);
2560 $sql .=
' FROM '.$this->db->prefix().
'facturedet as l';
2563 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2565 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element_line.
'_extrafields as ef ON l.rowid = ef.fk_object';
2568 $sql .=
' LEFT JOIN '.$this->db->prefix().
'product as p ON l.fk_product = p.rowid';
2569 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2570 if (is_int($only_type_product)) {
2571 $sql .=
" AND p.fk_product_type = ".((int) $only_type_product);
2573 $sql .=
' ORDER BY l.rang, l.rowid';
2575 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2576 $result = $this->db->query($sql);
2578 $num = $this->db->num_rows($result);
2581 $objp = $this->db->fetch_object($result);
2584 $line->id = $objp->rowid;
2585 $line->rowid = $objp->rowid;
2586 $line->fk_facture = $objp->fk_facture;
2587 $line->label = $objp->custom_label;
2588 $line->desc = $objp->description;
2589 $line->description = $objp->description;
2590 $line->product_type = $objp->product_type;
2591 $line->ref = $objp->product_ref;
2592 $line->product_ref = $objp->product_ref;
2593 $line->libelle = $objp->product_label;
2594 $line->product_label = $objp->product_label;
2595 $line->product_barcode = $objp->product_barcode;
2596 $line->product_desc = $objp->product_desc;
2597 $line->fk_product_type = $objp->fk_product_type;
2598 $line->qty = $objp->qty;
2599 $line->subprice = $objp->subprice;
2600 $line->ref_ext = $objp->ref_ext;
2602 $line->vat_src_code = $objp->vat_src_code;
2603 $line->tva_tx = $objp->tva_tx;
2604 $line->localtax1_tx = $objp->localtax1_tx;
2605 $line->localtax2_tx = $objp->localtax2_tx;
2606 $line->localtax1_type = $objp->localtax1_type;
2607 $line->localtax2_type = $objp->localtax2_type;
2608 $line->remise_percent = $objp->remise_percent;
2609 $line->fk_remise_except = $objp->fk_remise_except;
2610 $line->fk_product = $objp->fk_product;
2611 $line->date_start = $this->db->jdate($objp->date_start);
2612 $line->date_end = $this->db->jdate($objp->date_end);
2613 $line->info_bits = $objp->info_bits;
2614 $line->total_ht = $objp->total_ht;
2615 $line->total_tva = $objp->total_tva;
2616 $line->total_localtax1 = $objp->total_localtax1;
2617 $line->total_localtax2 = $objp->total_localtax2;
2618 $line->total_ttc = $objp->total_ttc;
2620 $line->fk_fournprice = $objp->fk_fournprice;
2621 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2622 $line->pa_ht = $marginInfos[0];
2623 $line->marge_tx = (
string) $marginInfos[1];
2624 $line->marque_tx = (
string) $marginInfos[2];
2625 $line->rang = $objp->rang;
2626 $line->special_code = $objp->special_code;
2627 $line->fk_parent_line = $objp->fk_parent_line;
2628 $line->situation_percent = $objp->situation_percent;
2629 $line->fk_prev_id = $objp->fk_prev_id;
2630 $line->fk_unit = $objp->fk_unit;
2632 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
2634 $line->batch = $objp->batch;
2635 $line->fk_warehouse = $objp->fk_warehouse;
2638 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2641 $line->fk_multicurrency = $objp->fk_multicurrency;
2642 $line->multicurrency_code = $objp->multicurrency_code;
2643 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2644 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2645 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2646 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2648 $line->array_options = array();
2649 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2650 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2651 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2652 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2655 if ($type !==
'separate') {
2656 $rawval = $objp->$key;
2659 if (in_array($type, array(
'date',
'datetime'))) {
2660 $line->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2661 } elseif ($type ==
'password') {
2662 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2663 $line->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2665 $line->array_options[
'options_' . $key] = $rawval;
2668 $line->array_options[
'options_' . $key] = $rawval;
2674 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2675 if (!empty($extrafields->attributes[$this->table_element_line][
'computed'][$key])) {
2676 if (empty(
$conf->disable_compute)) {
2677 global $objectoffield;
2678 $objectoffield = $line;
2679 $line->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element_line][
'computed'][$key], 1, 0,
'2');
2685 if (!$doFetchInOneSqlRequest) {
2687 $line->fetch_optionals();
2691 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2692 $tmpproduct =
new Product($this->db);
2693 $tmpproduct->fetch($objp->fk_product);
2694 $tmpproduct->getMultiLangs();
2696 $line->multilangs = $tmpproduct->multilangs;
2699 $this->lines[$i] = $line;
2703 $this->db->free($result);
2706 $this->error = $this->db->error();
2719 $this->tab_previous_situation_invoice = array();
2720 $this->tab_next_situation_invoice = array();
2722 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2723 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2724 $sql .=
' AND entity = '.((int) $this->entity);
2725 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2726 $sql .=
' ORDER BY situation_counter ASC';
2728 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2729 $result = $this->db->query($sql);
2730 if ($result && $this->db->num_rows($result) > 0) {
2731 while ($objp = $this->db->fetch_object($result)) {
2732 $invoice =
new Facture($this->db);
2733 if ($invoice->fetch($objp->rowid) > 0) {
2734 if ($objp->situation_counter < $this->situation_counter
2735 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2737 $this->tab_previous_situation_invoice[] = $invoice;
2739 $this->tab_next_situation_invoice[] = $invoice;
2760 if (empty($this->
type)) {
2763 if (isset($this->subtype)) {
2764 $this->subtype = (int) $this->subtype;
2766 if (isset($this->
ref)) {
2767 $this->
ref = trim($this->
ref);
2769 if (isset($this->ref_ext)) {
2770 $this->ref_ext = trim($this->ref_ext);
2772 if (!empty($this->ref_customer)) {
2773 $this->ref_customer = trim($this->ref_customer);
2775 if (isset($this->increment)) {
2776 $this->increment = trim($this->increment);
2778 if (isset($this->close_code)) {
2779 $this->close_code = trim($this->close_code);
2781 if (isset($this->close_note)) {
2782 $this->close_note = trim($this->close_note);
2784 if (isset($this->note) || isset($this->note_private)) {
2785 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2787 if (isset($this->note) || isset($this->note_private)) {
2788 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2790 if (isset($this->note_public)) {
2791 $this->note_public = trim($this->note_public);
2793 if (isset($this->model_pdf)) {
2794 $this->model_pdf = trim($this->model_pdf);
2796 if (isset($this->import_key)) {
2797 $this->import_key = trim($this->import_key);
2799 if (isset($this->retained_warranty)) {
2800 $this->retained_warranty = (float) $this->retained_warranty;
2802 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2803 $this->user_creation_id = $this->fk_user_author;
2805 if (!isset($this->user_modification_id) && !empty($user->id)) {
2806 $this->user_modification_id = $user->id;
2808 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2809 $this->user_validation_id = $this->fk_user_valid;
2814 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2815 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2816 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2817 $sql .=
" type=".(isset($this->
type) ? ((int) $this->
type) :
"null").
",";
2818 $sql .=
" subtype=".(isset($this->subtype) ? (int) $this->subtype :
"null").
",";
2819 $sql .=
" ref_client=".(!empty($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2820 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2821 $sql .=
" fk_soc=".(isset($this->socid) ? ((int) $this->socid) :
"null").
",";
2822 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2823 $sql .=
" datef=".(strval($this->
date) !=
'' ?
"'".$this->db->idate($this->
date).
"'" :
'null').
",";
2824 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2825 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2826 $sql .=
" paye=".(isset($this->paye) ? ((int) $this->paye) : 0).
",";
2827 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2828 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2829 $sql .=
" total_tva=".((float) $this->total_tva).
",";
2830 $sql .=
" localtax1=".((float) $this->total_localtax1).
",";
2831 $sql .=
" localtax2=".((float) $this->total_localtax2).
",";
2832 $sql .=
" total_ht=".((float) $this->total_ht).
",";
2833 $sql .=
" total_ttc=".((float) $this->total_ttc).
",";
2834 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2835 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2836 $sql .=
" fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) :
"null").
",";
2837 $sql .=
" fk_user_modif=".(!empty($user->id) ? ((int) $user->id) :
"null").
",";
2838 $sql .=
" fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id :
"null").
",";
2839 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2840 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2841 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2842 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2843 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2844 $sql .=
" note_private = ".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2845 $sql .=
" note_public = ".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2846 $sql .=
" model_pdf = ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2847 $sql .=
" import_key = ".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2848 $sql .=
" module_source = ".(isset($this->module_source) ?
"'".$this->db->escape($this->module_source).
"'" :
"null").
",";
2849 $sql .=
" pos_source = ".(isset($this->pos_source) ?
"'".$this->db->escape($this->pos_source).
"'" :
"null").
",";
2850 $sql .=
" pos_print_counter = ".(int) $this->pos_print_counter.
",";
2851 $sql .=
" situation_cycle_ref = ".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2852 $sql .=
" situation_counter = ".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2853 $sql .=
" situation_final = ".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2854 $sql .=
" retained_warranty = ".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2855 $sql .=
" retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2856 $sql .=
" retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2857 $sql .=
" WHERE rowid = ".((int) $this->
id);
2861 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2862 $resql = $this->db->query($sql);
2865 $this->errors[] =
"Error ".$this->db->lasterror();
2875 if (!$error && !$notrigger) {
2877 $result = $this->call_trigger(
'BILL_MODIFY', $user);
2886 foreach ($this->errors as $errmsg) {
2887 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2888 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2890 $this->db->rollback();
2893 $this->db->commit();
2911 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2912 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2917 $result = $remise->fetch($idremise);
2920 if ($remise->fk_facture) {
2921 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2922 $this->db->rollback();
2927 $facligne->fk_facture = $this->id;
2928 $facligne->fk_remise_except = $remise->id;
2929 $facligne->desc = $remise->description;
2930 $facligne->vat_src_code = $remise->vat_src_code;
2931 $facligne->tva_tx = $remise->tva_tx;
2932 $facligne->localtax1_tx = $remise->localtax1_tx;
2933 $facligne->localtax1_type = (int) $remise->localtax1_type;
2934 $facligne->localtax2_tx = $remise->localtax2_tx;
2935 $facligne->localtax2_type = (int) $remise->localtax2_type;
2936 $facligne->subprice = -(float) $remise->total_ht;
2937 $facligne->fk_product = 0;
2939 $facligne->remise_percent = 0;
2940 $facligne->rang = -1;
2941 $facligne->info_bits = 2;
2944 $facligne->rang = 1;
2945 $linecount = count($this->lines);
2946 for ($ii = 1; $ii <= $linecount; $ii++) {
2952 if ($remise->fk_facture_source > 0) {
2953 $srcinvoice =
new Facture($this->db);
2954 $srcinvoice->fetch($remise->fk_facture_source);
2955 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2957 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2958 $facligne->pa_ht = $arraytmp[
'pa_total'];
2961 $facligne->total_ht = -(float) $remise->total_ht;
2962 $facligne->total_tva = -(float) $remise->total_tva;
2963 $facligne->total_ttc = -(float) $remise->total_ttc;
2964 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
2965 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
2967 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2968 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
2969 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
2970 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
2972 $lineid = $facligne->insert();
2977 $result = $remise->link_to_invoice($lineid, 0);
2979 $this->error = $remise->error;
2980 $this->db->rollback();
2984 $this->db->commit();
2987 $this->error = $facligne->error;
2988 $this->db->rollback();
2992 $this->error = $facligne->error;
2993 $this->db->rollback();
2997 $this->db->rollback();
3019 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3020 if (empty($ref_client)) {
3021 $sql .=
" SET ref_client = NULL";
3023 $sql .=
" SET ref_client = '".$this->db->escape($ref_client).
"'";
3025 $sql .=
" WHERE rowid = ".((int) $this->
id);
3027 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
3028 $resql = $this->db->query($sql);
3030 $this->errors[] = $this->db->error();
3035 $this->ref_client = $ref_client;
3036 $this->ref_customer = $ref_client;
3039 if (!$notrigger && empty($error)) {
3041 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3049 $this->ref_client = $ref_client;
3050 $this->ref_customer = $ref_client;
3052 $this->db->commit();
3055 foreach ($this->errors as $errmsg) {
3056 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
3057 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
3059 $this->db->rollback();
3079 dol_syslog(__METHOD__.
' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3080 if ($this->
status >= self::STATUS_DRAFT) {
3082 $this->demand_reason_id = $inputReasonId;
3086 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3087 $sql .=
" SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId :
'null');
3088 $sql .=
" WHERE rowid = ".((int) $this->
id);
3091 $res = $this->db->query($sql);
3094 $this->error = $this->db->lasterror();
3095 $this->errors[] = $this->error;
3101 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3110 $this->db->commit();
3112 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3113 $this->db->rollback();
3114 dol_syslog(__METHOD__.
' Error : '.$this->errorsToString(), LOG_ERR);
3135 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3137 global $langs,
$conf;
3138 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3142 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
3155 if (!$error && !$notrigger) {
3157 $result = $this->call_trigger(
'BILL_DELETE', $user);
3166 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"categorie_invoice";
3167 $sql .=
" WHERE fk_invoice = ".((int) $this->
id);
3169 $result = $this->db->query($sql);
3172 $this->errors[] = $this->db->lasterror();
3181 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
3195 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
3196 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
3197 $sql .=
' AND fk_facture_line IS NULL';
3198 $resql = $this->db->query($sql);
3202 $list_rowid_det = array();
3203 foreach ($this->lines as $key => $invoiceline) {
3204 $list_rowid_det[] = $invoiceline->id;
3208 if (count($list_rowid_det)) {
3209 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3210 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
3211 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
3213 if (!$this->db->query($sql)) {
3214 $this->error = $this->db->error().
" sql=".$sql;
3215 $this->errors[] = $this->error;
3216 $this->db->rollback();
3223 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
3224 $sql .=
' SET fk_invoice = NULL';
3225 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
3227 if (!$this->db->query($sql)) {
3228 $this->error = $this->db->error().
" sql=".$sql;
3229 $this->errors[] = $this->error;
3230 $this->db->rollback();
3234 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
3235 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
3236 $sql .=
' WHERE invoice_id = '.((int) $rowid);
3238 if (!$this->db->query($sql)) {
3239 $this->error = $this->db->error().
" sql=".$sql;
3240 $this->errors[] = $this->error;
3241 $this->db->rollback();
3247 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3248 $langs->load(
"agenda");
3250 $num = count($this->lines);
3251 for ($i = 0; $i < $num; $i++) {
3252 if ($this->lines[$i]->fk_product > 0) {
3254 $mouvP->origin = &$this;
3255 $mouvP->setOrigin($this->element, $this->
id);
3257 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3258 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3260 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3267 $sql_main_table = MAIN_DB_PREFIX.
'facturedet';
3268 $sql_ef_table = $sql_main_table.
"_extrafields";
3269 $sqlef =
"DELETE FROM ".$sql_ef_table.
" WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table.
" WHERE fk_facture = ".((int) $rowid).
")";
3271 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
3274 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
3276 $resql = $this->db->query($sql);
3284 if ($conf->facture->dir_output && !empty($this->
ref)) {
3285 $dir =
$conf->facture->dir_output.
"/".$ref;
3286 $file =
$conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
3287 if (file_exists($file)) {
3291 $langs->load(
"errors");
3292 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
3293 $this->errors[] = $this->error;
3294 $this->db->rollback();
3298 if (file_exists($dir)) {
3300 $langs->load(
"errors");
3301 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
3302 $this->errors[] = $this->error;
3303 $this->db->rollback();
3309 $this->db->commit();
3312 $this->error = $this->db->lasterror().
" sql=".$sql;
3313 $this->errors[] = $this->error;
3314 $this->db->rollback();
3318 $this->error = $this->db->lasterror().
" sql=".$sql;
3319 $this->errors[] = $this->error;
3320 $this->db->rollback();
3324 $this->db->rollback();
3341 public function set_paid($user, $close_code =
'', $close_note =
'')
3344 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3345 return $this->
setPaid($user, $close_code, $close_note);
3358 public function setPaid($user, $close_code =
'', $close_note =
'')
3362 if ($this->paye != 1 || $this->
status != self::STATUS_CLOSED) {
3367 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3369 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3370 $sql .=
' fk_statut = '.self::STATUS_CLOSED;
3372 $sql .=
', paye = 1';
3375 $sql .=
", close_code = '".$this->db->escape($close_code).
"'";
3378 $sql .=
", close_note = '".$this->db->escape($close_note).
"'";
3380 $sql .=
', fk_user_closing = '.((int) $user->id);
3381 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3382 $sql .=
" WHERE rowid = ".((int) $this->
id);
3384 $resql = $this->db->query($sql);
3387 $result = $this->call_trigger(
'BILL_PAYED', $user);
3394 $this->error = $this->db->lasterror();
3400 $this->db->commit();
3403 $this->db->rollback();
3426 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3444 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3445 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3446 $sql .=
' date_closing=null,';
3447 $sql .=
' fk_user_closing=null';
3448 $sql .=
" WHERE rowid = ".((int) $this->
id);
3450 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3451 $resql = $this->db->query($sql);
3454 $result = $this->call_trigger(
'BILL_UNPAYED', $user);
3461 $this->error = $this->db->error();
3466 $this->db->commit();
3469 $this->db->rollback();
3491 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3492 return $this->
setCanceled($user, $close_code, $close_note);
3505 public function setCanceled($user, $close_code =
'', $close_note =
'')
3507 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3512 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3513 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3515 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3518 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3520 $sql .=
', fk_user_closing = '.((int) $user->id);
3521 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3522 $sql .=
" WHERE rowid = ".((int) $this->
id);
3524 $resql = $this->db->query($sql);
3528 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3529 $sql .=
' SET fk_facture = NULL';
3530 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3532 $resql = $this->db->query($sql);
3535 $result = $this->call_trigger(
'BILL_CANCEL', $user);
3537 $this->db->rollback();
3542 $this->db->commit();
3545 $this->error = $this->db->error().
" sql=".$sql;
3546 $this->db->rollback();
3550 $this->error = $this->db->error().
" sql=".$sql;
3551 $this->db->rollback();
3568 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3571 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3573 $productStatic =
null;
3574 $warehouseStatic =
null;
3575 $productbatch =
null;
3576 if ($batch_rule > 0) {
3577 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3578 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3579 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3580 $productStatic =
new Product($this->db);
3581 $warehouseStatic =
new Entrepot($this->db);
3588 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3595 if ($this->
status != self::STATUS_DRAFT) {
3596 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3599 if (count($this->lines) <= 0) {
3600 $langs->load(
"errors");
3601 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3605 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3606 $this->error =
'Permission denied';
3607 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3610 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3618 if (!$last_of_type[0]) {
3625 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3626 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'TVA_INTRA',
'ACCOUNTANCY_CODE_CUSTOMER');
3627 foreach ($array_to_check as $key) {
3628 $keymin = strtolower($key);
3629 if (!property_exists($this->thirdparty, $keymin)) {
3632 $vallabel = $this->thirdparty->$keymin;
3634 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3636 if ($this->thirdparty->isACompany()) {
3638 if (
$mysoc->country_id > 0 && $this->thirdparty->country_id ==
$mysoc->country_id) {
3639 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3641 $langs->load(
"errors");
3642 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3643 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3649 if ($key ==
'EMAIL') {
3652 $langs->load(
"errors");
3653 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3654 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3658 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3660 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3661 $langs->load(
"errors");
3662 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3663 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3667 if ($key ==
'TVA_INTRA') {
3670 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3671 $langs->load(
"errors");
3672 $this->error = $langs->trans(
'ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3673 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3676 } elseif (
getDolGlobalString(
'SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3677 $langs->load(
"errors");
3678 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3679 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3688 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3689 foreach ($array_to_check as $key => $val) {
3690 $keymin = strtolower($key);
3691 $vallabel = $this->$keymin;
3694 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3696 $langs->load(
"errors");
3698 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3705 if ($this->
type == self::TYPE_REPLACEMENT) {
3707 if ($this->fk_facture_source <= 0) {
3708 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3709 $this->db->rollback();
3714 $facreplaced =
new Facture($this->db);
3715 $result = $facreplaced->fetch($this->fk_facture_source);
3717 $this->error = $langs->trans(
"ErrorBadInvoice");
3718 $this->db->rollback();
3723 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3724 if ($idreplacement && $idreplacement != $this->
id) {
3725 $facreplacement =
new Facture($this->db);
3726 $facreplacement->fetch($idreplacement);
3727 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3728 $this->db->rollback();
3732 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3734 $this->error = $facreplaced->error;
3735 $this->db->rollback();
3741 if ($force_number) {
3742 $num = $force_number;
3743 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3756 $this->oldref = $this->ref;
3764 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3765 $sql .=
" SET ref = '".$this->db->escape($num).
"', fk_statut = ".self::STATUS_VALIDATED.
", fk_user_valid = ".($user->id > 0 ? ((int) $user->id) :
"null").
", date_valid = '".$this->db->idate($now).
"'";
3767 $sql .=
", datef='".$this->db->idate($this->
date).
"'";
3768 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3770 $sql .=
" WHERE rowid = ".((int) $this->
id);
3772 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3773 $resql = $this->db->query($sql);
3775 $this->error = $this->db->lasterror();
3782 $result = $this->thirdparty->setAsCustomer();
3786 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3787 $langs->load(
"agenda");
3790 $cpt = count($this->lines);
3791 for ($i = 0; $i < $cpt; $i++) {
3792 if ($this->lines[$i]->fk_product > 0) {
3794 $mouvP->origin = &$this;
3795 $mouvP->setOrigin($this->element, $this->
id);
3798 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3801 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3810 $is_batch_line =
false;
3811 if ($batch_rule > 0) {
3812 $productStatic->fetch($this->lines[$i]->fk_product);
3813 if ($productStatic->hasbatch() && is_object($productbatch)) {
3814 $is_batch_line =
true;
3815 $product_qty_remain = $this->lines[$i]->qty;
3821 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3822 $sortorder =
'ASC,ASC,ASC,ASC';
3825 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 :
null), $sortfield, $sortorder);
3826 if (!is_array($resBatchList)) {
3828 $this->error = $this->db->lasterror();
3832 $batchList = $resBatchList;
3833 if (empty($batchList)) {
3835 $langs->load(
'errors');
3836 $warehouseStatic->fetch($idwarehouse);
3837 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3838 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3841 foreach ($batchList as $batch) {
3842 if ($batch->qty <= 0) {
3847 if ($batch->qty >= $product_qty_remain) {
3848 $product_batch_qty = $product_qty_remain;
3851 $product_batch_qty = $batch->qty;
3853 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3860 $product_qty_remain -= $product_batch_qty;
3862 if ($product_qty_remain <= 0) {
3867 if (!$error && $product_qty_remain > 0) {
3870 $langs->load(
'errors');
3871 $warehouseStatic->fetch($idwarehouse);
3872 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3873 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3876 $batch = $batchList[0];
3877 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3888 if (!$is_batch_line) {
3889 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3904 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3905 $invoice_situation =
new Facture($this->db);
3906 $result = $invoice_situation->fetch($this->fk_facture_source);
3907 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3908 $invoice_situation->situation_final = 0;
3910 $result = $invoice_situation->setFinal($user, 1);
3913 $this->error = $invoice_situation->error;
3914 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3920 if (!$error && !$notrigger) {
3922 $result = $this->call_trigger(
'BILL_VALIDATE', $user);
3931 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3933 $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).
"'";
3934 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3935 $resql = $this->db->query($sql);
3938 $this->error = $this->db->lasterror();
3940 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3941 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3942 $resql = $this->db->query($sql);
3945 $this->error = $this->db->lasterror();
3952 if (!$resupdatenext) {
3962 $this->date_validation = $now;
3967 $nboflines = count($this->lines);
3968 while (($i < $nboflines) && $final) {
3969 $line = $this->lines[$i];
3970 '@phan-var-force FactureLigne $line';
3972 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3973 $current_progress = (float) $line->situation_percent;
3974 $full_progress = $previousprogress + $current_progress;
3975 $final = ($full_progress == 100);
3977 $final = ($line->situation_percent == 100);
3983 if ($this->situation_final) {
3985 $this->situation_final = 0;
3989 if (!$this->situation_final) {
3991 $this->situation_final = 1;
4001 if (!$error && preg_match(
'/^[\(]?PROV/i', $this->oldref)) {
4005 $dirsource =
$conf->facture->dir_output.
'/'.$oldref;
4006 $dirdest =
$conf->facture->dir_output.
'/'.$newref;
4007 if (!$error && file_exists($dirsource)) {
4008 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
4010 if (@rename($dirsource, $dirdest)) {
4013 $listoffiles =
dol_dir_list(
$conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
4014 foreach ($listoffiles as $fileentry) {
4015 $dirsource = $fileentry[
'name'];
4016 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
4017 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
4018 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
4019 @rename($dirsource, $dirdest);
4026 $this->db->commit();
4029 $this->db->rollback();
4042 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4043 $is_last = $next_invoice->is_last_in_cycle();
4045 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4046 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4050 foreach ($next_invoice->lines as $line) {
4051 '@phan-var-force FactureLigne $line';
4052 $result = $next_invoice->updateline(
4057 $line->remise_percent,
4061 $line->localtax1_tx,
4062 $line->localtax2_tx,
4065 $line->product_type,
4066 $line->fk_parent_line,
4068 $line->fk_fournprice,
4071 $line->special_code,
4072 $line->array_options,
4073 $line->situation_percent,
4078 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4103 if ($this->
status == self::STATUS_DRAFT) {
4104 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
4112 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4113 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
4114 $sql .=
" WHERE rowid = ".((int) $this->
id);
4116 $result = $this->db->query($sql);
4119 $this->oldcopy = clone $this;
4124 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
4125 $langs->load(
"agenda");
4127 $num = count($this->lines);
4128 for ($i = 0; $i < $num; $i++) {
4129 if ($this->lines[$i]->fk_product > 0) {
4131 $mouvP->origin = &$this;
4132 $mouvP->setOrigin($this->element, $this->
id);
4134 if ($this->
type == self::TYPE_CREDIT_NOTE) {
4135 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
4137 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
4144 $old_statut = $this->status;
4149 $result = $this->call_trigger(
'BILL_UNVALIDATE', $user);
4152 $this->statut = $old_statut;
4153 $this->
status = $old_statut;
4157 $this->db->rollback();
4162 $this->db->commit();
4165 $this->db->rollback();
4169 $this->error = $this->db->error();
4170 $this->db->rollback();
4224 $remise_percent = 0,
4227 $fk_code_ventilation = 0,
4229 $fk_remise_except = 0,
4230 $price_base_type =
'HT',
4237 $fk_parent_line = 0,
4238 $fk_fournprice =
null,
4241 $array_options = array(),
4242 $situation_percent = 100,
4247 $noupdateafterinsertline = 0
4251 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4257 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);
4259 if ($this->
status == self::STATUS_DRAFT) {
4260 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4263 if (empty($remise_percent)) {
4264 $remise_percent = 0;
4269 if (empty($info_bits)) {
4275 if (empty($fk_code_ventilation)) {
4276 $fk_code_ventilation = 0;
4278 if (empty($txtva)) {
4281 if (empty($txlocaltax1)) {
4284 if (empty($txlocaltax2)) {
4287 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4288 $fk_parent_line = 0;
4290 if (empty($fk_prev_id)) {
4291 $fk_prev_id =
'null';
4294 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4297 $situation_percent = 0;
4299 $situation_percent = 100;
4303 if (empty($ref_ext)) {
4307 $remise_percent = (float)
price2num($remise_percent);
4311 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4314 if (strpos((
string) $txtva,
'*') !==
false) {
4317 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4320 $txlocaltax1 = (float)
price2num($txlocaltax1);
4321 $txlocaltax2 = (float)
price2num($txlocaltax2);
4323 if ($price_base_type ==
'HT') {
4335 $langs->load(
"errors");
4336 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4342 $product_type = $type;
4343 if (!empty($fk_product) && $fk_product > 0) {
4344 $product =
new Product($this->db);
4345 $result = $product->fetch($fk_product);
4346 $product_type = $product->type;
4348 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4350 $productChildrenNb = 0;
4352 $productChildrenNb = $product->hasFatherOrChild(1);
4354 if ($productChildrenNb > 0) {
4356 $product_stock =
null;
4357 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4358 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4359 if ($product_stock ===
null) {
4360 $product_stock = $componentStockWarehouse->real;
4362 $product_stock = min($product_stock, $componentStockWarehouse->real);
4365 if ($product_stock ===
null) {
4369 $product_stock = $product->stock_reel;
4372 if ($product_stock < $qty) {
4373 $langs->load(
"errors");
4374 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4375 $this->db->rollback();
4381 $tmpproduct =
new Product($this->db);
4382 $result = $tmpproduct->fetch($fk_product);
4383 if (abs((
float) $qty) < $tmpproduct->packaging) {
4384 $qty = (float) $tmpproduct->packaging;
4385 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4387 if (!empty($tmpproduct->packaging) && (
float)
price2num(fmod((
float) $qty, (
float) $tmpproduct->packaging),
'MS')) {
4388 $coeff = intval(abs((
float) $qty) / $tmpproduct->packaging) + 1;
4389 $qty =
price2num((
float) $tmpproduct->packaging * $coeff,
'MS');
4390 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4401 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4402 $vat_src_code = $reg[1];
4403 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4410 $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);
4412 $total_ht = $tabprice[0];
4413 $total_tva = $tabprice[1];
4414 $total_ttc = $tabprice[2];
4415 $total_localtax1 = $tabprice[9];
4416 $total_localtax2 = $tabprice[10];
4417 $pu_ht = $tabprice[3];
4420 $multicurrency_total_ht = $tabprice[16];
4421 $multicurrency_total_tva = $tabprice[17];
4422 $multicurrency_total_ttc = $tabprice[18];
4423 $pu_ht_devise = $tabprice[19];
4427 if (empty($ranktouse) || $ranktouse == -1) {
4428 $rangmax = $this->
line_max($fk_parent_line);
4429 $ranktouse = $rangmax + 1;
4434 $apply_abs_price_on_credit_note =
false;
4436 $apply_abs_price_on_credit_note =
true;
4442 $this->line->context = $this->context;
4444 $this->line->fk_facture = $this->id;
4445 $this->line->label = $label;
4446 $this->line->desc = $desc;
4447 $this->line->ref_ext = $ref_ext;
4449 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : (float) $qty);
4450 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4452 $this->line->vat_src_code = $vat_src_code;
4453 $this->line->tva_tx = $txtva;
4454 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4455 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4456 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4457 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4459 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4460 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4461 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4462 $this->line->total_localtax1 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax1) : (float) $total_localtax1);
4463 $this->line->total_localtax2 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax2) : (float) $total_localtax2);
4465 $this->line->fk_product = $fk_product;
4466 $this->line->product_type = $product_type;
4467 $this->line->remise_percent = $remise_percent;
4469 $this->line->date_end = $date_end;
4470 $this->line->fk_code_ventilation = $fk_code_ventilation;
4471 $this->line->rang = $ranktouse;
4472 $this->line->info_bits = $info_bits;
4473 $this->line->fk_remise_except = $fk_remise_except;
4475 $this->line->special_code = $special_code;
4476 $this->line->fk_parent_line = $fk_parent_line;
4478 $this->line->origin = $origin;
4479 $this->line->origin_id = $origin_id;
4481 $this->line->situation_percent = $situation_percent;
4482 $this->line->fk_prev_id = $fk_prev_id;
4483 $this->line->fk_unit = $fk_unit;
4486 $this->line->fk_fournprice = $fk_fournprice;
4487 $this->line->pa_ht = $pa_ht;
4490 $this->line->fk_multicurrency = $this->fk_multicurrency;
4491 $this->line->multicurrency_code = $this->multicurrency_code;
4492 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4494 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4495 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4496 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4498 if (is_array($array_options) && count($array_options) > 0) {
4499 $this->line->array_options = $array_options;
4502 $result = $this->line->insert();
4505 if (empty($noupdateafterinsertline)) {
4509 if (!isset($this->context[
'createfromclone'])) {
4510 if (!empty($fk_parent_line)) {
4513 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4515 $linecount = count($this->lines);
4516 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4521 $this->lines[] = $this->line;
4524 foreach ($this->lines as $tmpline) {
4525 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
4526 $this->line->extraparams = $tmpline->extraparams;
4527 $this->line->setExtraParameters();
4533 $this->db->commit();
4534 return $this->line->id;
4536 $this->error = $this->db->lasterror();
4537 $this->db->rollback();
4541 $this->error = $this->line->error;
4542 $this->errors = $this->line->errors;
4543 $this->db->rollback();
4547 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4548 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4584 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)
4590 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4593 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4597 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);
4599 if ($this->
status == self::STATUS_DRAFT) {
4602 if (!$this->error) {
4603 $this->error = $langs->trans(
'invoiceLineProgressError');
4610 $langs->load(
"errors");
4611 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4621 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4622 $fk_parent_line = 0;
4624 if (empty($special_code) || $special_code == 3) {
4627 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
4630 $situation_percent = 0;
4632 $situation_percent = 100;
4635 if (empty($ref_ext)) {
4639 $remise_percent = (float)
price2num($remise_percent);
4643 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4646 if (strpos((
string) $txtva,
'*') !==
false) {
4649 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4652 $txlocaltax1 = (float)
price2num($txlocaltax1);
4653 $txlocaltax2 = (float)
price2num($txlocaltax2);
4669 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4670 $vat_src_code = $reg[1];
4671 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4674 $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);
4676 $total_ht = $tabprice[0];
4677 $total_tva = $tabprice[1];
4678 $total_ttc = $tabprice[2];
4679 $total_localtax1 = $tabprice[9];
4680 $total_localtax2 = $tabprice[10];
4681 $pu_ht = $tabprice[3];
4682 $pu_tva = $tabprice[4];
4683 $pu_ttc = $tabprice[5];
4686 $multicurrency_total_ht = $tabprice[16];
4687 $multicurrency_total_tva = $tabprice[17];
4688 $multicurrency_total_ttc = $tabprice[18];
4689 $pu_ht_devise = $tabprice[19];
4694 if ($remise_percent > 0) {
4695 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4696 $price = ((float) $pu - $remise);
4702 $line->fetch($rowid);
4703 $line->fetch_optionals();
4705 if (!empty($line->fk_product)) {
4706 $product =
new Product($this->db);
4707 $result = $product->fetch($line->fk_product);
4708 $product_type = $product->type;
4710 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4712 $productChildrenNb = 0;
4714 $productChildrenNb = $product->hasFatherOrChild(1);
4716 if ($productChildrenNb > 0) {
4718 $product_stock =
null;
4719 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4720 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4721 if ($product_stock ===
null) {
4722 $product_stock = $componentStockWarehouse->real;
4724 $product_stock = min($product_stock, $componentStockWarehouse->real);
4727 if ($product_stock ===
null) {
4731 $product_stock = $product->stock_reel;
4734 if ($product_stock < $qty) {
4735 $langs->load(
"errors");
4736 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', (
string) $product->ref);
4737 $this->db->rollback();
4743 $staticline = clone $line;
4745 $line->oldline = $staticline;
4746 $this->line = $line;
4747 $this->line->context = $this->context;
4748 $this->line->rang = $rang;
4751 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4752 $rangmax = $this->
line_max($fk_parent_line);
4753 $this->line->rang = $rangmax + 1;
4755 $apply_abs_price_on_credit_note =
false;
4757 $apply_abs_price_on_credit_note =
true;
4762 if ($qty < $this->line->packaging) {
4763 $qty = $this->line->packaging;
4764 setEventMessage($langs->trans(
'QtyRecalculatedWithPackaging'),
'warnings');
4766 if (!empty($this->line->packaging)
4767 && is_numeric($this->line->packaging)
4768 && (
float) $this->line->packaging > 0
4769 && (
float)
price2num(fmod((
float) $qty, (
float) $this->line->packaging),
'MS')) {
4770 $coeff = intval($qty / $this->line->packaging) + 1;
4771 $qty = $this->line->packaging * $coeff;
4772 setEventMessage($langs->trans(
'QtyRecalculatedWithPackaging'),
'warnings');
4777 $this->line->id = $rowid;
4778 $this->line->rowid = $rowid;
4779 $this->line->label = $label;
4780 $this->line->desc = $desc;
4781 $this->line->ref_ext = $ref_ext;
4782 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4784 $this->line->vat_src_code = $vat_src_code;
4785 $this->line->tva_tx = $txtva;
4786 $this->line->localtax1_tx = $txlocaltax1;
4787 $this->line->localtax2_tx = $txlocaltax2;
4788 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4789 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4791 $this->line->remise_percent = $remise_percent;
4792 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4794 $this->line->date_end = $date_end;
4795 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4796 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4797 $this->line->total_localtax1 = (float) $total_localtax1;
4798 $this->line->total_localtax2 = (float) $total_localtax2;
4799 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4800 $this->line->info_bits = $info_bits;
4801 $this->line->special_code = $special_code;
4802 $this->line->product_type = $type;
4803 $this->line->fk_parent_line = $fk_parent_line;
4804 $this->line->skip_update_total = $skip_update_total;
4805 $this->line->situation_percent = $situation_percent;
4806 $this->line->fk_unit = $fk_unit;
4808 $this->line->fk_fournprice = $fk_fournprice;
4809 $this->line->pa_ht = $pa_ht;
4812 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4813 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4814 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4815 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4817 if (is_array($array_options) && count($array_options) > 0) {
4819 foreach ($array_options as $key => $value) {
4820 $this->line->array_options[$key] = $array_options[$key];
4824 $result = $this->line->update($user, $notrigger);
4827 if (!empty($fk_parent_line)) {
4833 $this->db->commit();
4836 $this->error = $this->line->error;
4837 $this->db->rollback();
4841 $this->error =
"Invoice statut makes operation forbidden";
4855 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4856 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4857 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4859 $result = $this->db->query($sql);
4861 $this->error = $this->db->error();
4865 $obj = $this->db->fetch_object($result);
4867 if ($obj ===
null) {
4870 return ($situation_percent < $obj->situation_percent);
4889 if (($line->info_bits & 2) == 2) {
4893 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4896 if ($percent > 100) {
4900 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4901 $current_progress = $percent - $previous_progress;
4902 $line->situation_percent = $current_progress;
4903 $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);
4905 $line->situation_percent = $percent;
4906 $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);
4908 $line->total_ht = (float) $tabprice[0];
4909 $line->total_tva = (float) $tabprice[1];
4910 $line->total_ttc = (float) $tabprice[2];
4911 $line->total_localtax1 = (float) $tabprice[9];
4912 $line->total_localtax2 = (float) $tabprice[10];
4913 $line->multicurrency_total_ht = (float) $tabprice[16];
4914 $line->multicurrency_total_tva = (float) $tabprice[17];
4915 $line->multicurrency_total_ttc = (float) $tabprice[18];
4916 $line->update($user);
4919 if ($update_price) {
4935 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4937 if ($this->
status != self::STATUS_DRAFT) {
4938 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4944 $line->context = $this->context;
4947 $result = $line->fetch($rowid);
4948 if (!($result > 0)) {
4953 if ($id > 0 && $line->fk_facture != $id) {
4954 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4961 $staticline = clone $line;
4962 $line->oldline = $staticline;
4964 if ($line->delete($user) > 0) {
4968 $this->db->commit();
4971 $this->db->rollback();
4972 $this->error = $this->db->lasterror();
4976 $this->db->rollback();
4977 $this->error = $line->error;
4996 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4998 return $this->
setDiscount($user, $remise, $notrigger);
5012 if (empty($remise)) {
5016 if ($user->hasRight(
'facture',
'creer')) {
5017 $remise = (float)
price2num($remise, 2);
5023 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
5024 $sql .=
" SET remise_percent = ".((float) $remise);
5025 $sql .=
" WHERE rowid = ".((int) $this->
id);
5026 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
5029 $resql = $this->db->query($sql);
5031 $this->errors[] = $this->db->error();
5035 if (!$notrigger && empty($error)) {
5037 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5045 $this->remise_percent = $remise;
5048 $this->db->commit();
5051 foreach ($this->errors as $errmsg) {
5052 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5053 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5055 $this->db->rollback();
5076 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
5077 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5090 global
$conf, $langs;
5092 if ($this->module_source ==
'takepos') {
5093 $langs->load(
'cashdesk');
5095 $moduleName =
'takepos';
5096 $moduleSourceName =
'Takepos';
5097 $addonConstName =
'TAKEPOS_REF_ADDON';
5101 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
5106 $langs->load(
'bills');
5108 $moduleName =
'facture';
5109 $moduleSourceName =
'Invoice';
5110 $addonConstName =
'FACTURE_ADDON';
5114 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5116 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5118 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
5124 if (!empty($addon)) {
5125 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
5129 $file = $addon.
'.php';
5130 $classname = $addon;
5134 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
5135 foreach ($dirmodels as $reldir) {
5136 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
5139 if (is_file($dir.$file) && is_readable($dir.$file)) {
5140 $mybool = ((bool) include_once $dir.$file) || $mybool;
5146 $file = $addon.
'/'.$addon.
'.modules.php';
5147 $classname =
'mod_'.$moduleName.
'_'.$addon;
5148 $classname = preg_replace(
'/\-.*$/',
'', $classname);
5150 foreach (
$conf->file->dol_document_root as $dirroot) {
5151 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
5154 if (is_file($dir.$file) && is_readable($dir.$file)) {
5155 $mybool = (include_once $dir.$file) || $mybool;
5165 $obj =
new $classname();
5166 '@phan-var-force ModeleNumRefFactures $obj';
5168 $numref = $obj->getNextValue($soc, $this, $mode);
5175 if ($mode !=
'last' && !$numref) {
5176 $this->error = $obj->error;
5182 $langs->load(
'errors');
5183 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5196 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5197 $sql .=
' date_closing as dateclosing,';
5198 $sql .=
' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5199 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
5200 $sql .=
' WHERE c.rowid = '.((int) $id);
5202 $result = $this->db->query($sql);
5204 if ($this->db->num_rows($result)) {
5205 $obj = $this->db->fetch_object($result);
5207 $this->
id = $obj->rowid;
5208 $this->user_creation_id = $obj->fk_user_author;
5209 $this->user_modification_id = $obj->fk_user_modif;
5210 $this->user_validation_id = $obj->fk_user_valid;
5211 $this->user_closing_id = $obj->fk_user_closing;
5213 $this->date_creation = $this->db->jdate($obj->datec);
5214 $this->date_modification = $this->db->jdate($obj->datem);
5215 $this->date_validation = $this->db->jdate($obj->datev);
5216 $this->date_closing = $this->db->jdate($obj->dateclosing);
5218 $this->db->free($result);
5239 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
5246 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
5247 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
5248 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
5249 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5250 $sql .=
" AND f.fk_soc = s.rowid";
5252 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
5254 if (is_object($excluser)) {
5255 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
5259 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5260 $search_sale = $user->id;
5263 if ($search_sale && $search_sale !=
'-1') {
5264 if ($search_sale == -2) {
5265 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5266 } elseif ($search_sale > 0) {
5267 $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).
")";
5272 $sql .=
" AND f.fk_soc = ".((int) $socid);
5274 $sql .= $this->db->order($sortfield, $sortorder);
5275 $sql .= $this->db->plimit($limit, $offset);
5277 $result = $this->db->query($sql);
5279 $numc = $this->db->num_rows($result);
5282 while ($i < $numc) {
5283 $obj = $this->db->fetch_object($result);
5285 if ($shortlist == 1) {
5286 $ga[$obj->fid] = $obj->ref;
5287 } elseif ($shortlist == 2) {
5288 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
5290 $ga[$i][
'id'] = $obj->fid;
5291 $ga[$i][
'ref'] = $obj->ref;
5292 $ga[$i][
'name'] = $obj->name;
5321 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5322 $sql .=
" ff.rowid as rowidnext";
5324 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5325 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5326 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
5327 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
5328 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5329 $sql .=
" AND f.paye = 0";
5330 $sql .=
" AND pf.fk_paiement IS NULL";
5331 $sql .=
" AND ff.fk_statut IS NULL";
5333 $sql .=
" AND f.fk_soc = ".((int) $socid);
5336 $sql .=
" ORDER BY f.ref";
5338 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
5339 $resql = $this->db->query($sql);
5341 while ($obj = $this->db->fetch_object($resql)) {
5342 $return[$obj->rowid] = array(
5343 'id' => $obj->rowid,
5345 'status' => $obj->status,
5346 'paid' => $obj->paid,
5353 $this->error = $this->db->error();
5377 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
5378 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5379 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5380 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
5381 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5382 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5386 $sql .=
" AND ff.type IS NULL";
5387 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
5391 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
5392 $sql .=
'(SELECT MAX(fs.rowid)';
5393 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
5394 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
5395 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
5396 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5398 $sql .=
" AND fs.fk_soc = ".((int) $socid);
5400 $sql .=
" GROUP BY fs.situation_cycle_ref)";
5403 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
5407 $sql .=
" AND f.fk_soc = ".((int) $socid);
5410 if (
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5411 $sql .=
" ORDER BY CASE WHEN f.rowid = ".((int)
GETPOST(
'fac_avoir')).
" THEN 0 ELSE 1 END, f.ref";
5413 $sql .= $this->db->plimit(
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5415 $sql .=
" ORDER BY f.ref";
5418 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
5419 $resql = $this->db->query($sql);
5421 while ($obj = $this->db->fetch_object($resql)) {
5423 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5426 if ($obj->fk_statut == self::STATUS_CLOSED) {
5431 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5432 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
5438 $this->error = $this->db->error();
5454 global
$conf, $langs;
5456 $sanitizedclause =
" WHERE";
5458 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5459 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5460 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5461 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5462 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5463 $sanitizedclause =
" AND";
5465 $sql .= $sanitizedclause.
" f.paye=0";
5466 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5467 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5469 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5472 $resql = $this->db->query($sql);
5474 $langs->load(
"bills");
5477 $response->warning_delay =
getWarningDelay(
'invoice',
'client') / 60 / 60 / 24;
5478 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5479 $response->labelShort = $langs->trans(
"Unpaid");
5480 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5483 $generic_facture =
new Facture($this->db);
5485 while ($obj = $this->db->fetch_object($resql)) {
5486 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5487 $generic_facture->statut = $obj->status;
5488 $generic_facture->status = $obj->status;
5490 $response->nbtodo++;
5491 $response->total += $obj->total_ht;
5493 if ($generic_facture->hasDelay()) {
5494 $response->nbtodolate++;
5495 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5499 $this->db->free($resql);
5503 $this->error = $this->db->error();
5542 global
$conf, $langs, $user;
5546 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5551 $sql =
"SELECT rowid";
5552 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5553 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5554 $sql .= $this->db->plimit(100);
5556 $resql = $this->db->query($sql);
5558 $num_prods = $this->db->num_rows($resql);
5560 while ($i < $num_prods) {
5562 $row = $this->db->fetch_row($resql);
5563 $prodids[$i] = $row[0];
5567 if (empty($num_prods)) {
5569 $prodids[$num_prods] = 1;
5574 $this->entity =
$conf->entity;
5575 $this->
ref =
'SPECIMEN';
5576 $this->specimen = 1;
5578 $this->
date = $nownotime;
5579 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5580 $this->cond_reglement_id = 1;
5581 $this->cond_reglement_code =
'RECEP';
5583 $this->mode_reglement_id = 0;
5584 $this->mode_reglement_code =
'';
5586 $this->note_public =
'This is a comment (public)';
5587 $this->note_private =
'This is a comment (private)';
5589 $this->user_creation_id = $user->id;
5591 $this->multicurrency_tx = 1;
5592 $this->multicurrency_code =
$conf->currency;
5594 $this->fk_incoterms = 0;
5595 $this->location_incoterms =
'';
5597 $this->pos_print_counter = 0;
5598 $this->email_sent_counter = 0;
5602 if (empty($option) || $option !=
'nolines') {
5606 while ($xnbp < $nbp) {
5608 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5610 $line->subprice = 100;
5611 $line->tva_tx = 19.6;
5612 $line->localtax1_tx = 0;
5613 $line->localtax2_tx = 0;
5614 $line->remise_percent = 0;
5615 if ($xnbp == 1 && $option !=
'takepos' && $option !=
'nonegativeup') {
5616 $prodid = mt_rand(1, $num_prods);
5617 if (isset($prodids[$prodid])) {
5618 $line->fk_product = $prodids[$prodid];
5621 $line->total_ht = -100;
5622 $line->total_ttc = -119.6;
5623 $line->total_tva = -19.6;
5624 $line->multicurrency_total_ht = -200;
5625 $line->multicurrency_total_ttc = -239.2;
5626 $line->multicurrency_total_tva = -39.2;
5627 } elseif ($xnbp == 2 && $option !=
'takepos' && $option !=
'nonegativeup') {
5628 $line->subprice = -100;
5629 $line->total_ht = -100;
5630 $line->total_ttc = -119.6;
5631 $line->total_tva = -19.6;
5632 $line->remise_percent = 0;
5633 $line->multicurrency_total_ht = -200;
5634 $line->multicurrency_total_ttc = -239.2;
5635 $line->multicurrency_total_tva = -39.2;
5636 } elseif ($xnbp == 3) {
5637 $prodid = mt_rand(1, $num_prods);
5638 if (isset($prodids[$prodid])) {
5639 $line->fk_product = $prodids[$prodid];
5641 $line->total_ht = 50;
5642 $line->total_ttc = 59.8;
5643 $line->total_tva = 9.8;
5644 $line->multicurrency_total_ht = 100;
5645 $line->multicurrency_total_ttc = 119.6;
5646 $line->multicurrency_total_tva = 19.6;
5647 $line->remise_percent = 50;
5649 $prodid = mt_rand(1, $num_prods);
5650 if (isset($prodids[$prodid])) {
5651 $line->fk_product = $prodids[$prodid];
5653 $line->total_ht = 100;
5654 $line->total_ttc = 119.6;
5655 $line->total_tva = 19.6;
5656 $line->multicurrency_total_ht = 200;
5657 $line->multicurrency_total_ttc = 239.2;
5658 $line->multicurrency_total_tva = 39.2;
5659 $line->remise_percent = 0;
5662 $this->lines[$xnbp] = $line;
5665 $this->total_ht += $line->total_ht;
5666 $this->total_tva += $line->total_tva;
5667 $this->total_ttc += $line->total_ttc;
5669 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5670 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5671 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5675 $this->revenuestamp = 0;
5678 if ($option !=
'takepos') {
5680 $line->desc = $langs->trans(
"Description").
" (offered line)";
5682 $line->subprice = 100;
5683 $line->tva_tx = 19.6;
5684 $line->localtax1_tx = 0;
5685 $line->localtax2_tx = 0;
5686 $line->remise_percent = 100;
5687 $line->total_ht = 0;
5688 $line->total_ttc = 0;
5689 $line->total_tva = 0;
5690 $line->multicurrency_total_ht = 0;
5691 $line->multicurrency_total_ttc = 0;
5692 $line->multicurrency_total_tva = 0;
5693 $prodid = mt_rand(1, $num_prods);
5694 if (isset($prodids[$prodid])) {
5695 $line->fk_product = $prodids[$prodid];
5698 $this->lines[$xnbp] = $line;
5715 $this->nb = array();
5717 $sanitizedclause =
"WHERE";
5719 $sql =
"SELECT count(f.rowid) as nb";
5720 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5721 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5722 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5723 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5724 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5725 $sanitizedclause =
"AND";
5727 $sql .=
" ".$sanitizedclause.
" f.entity IN (".
getEntity(
'invoice').
")";
5729 $resql = $this->db->query($sql);
5731 while ($obj = $this->db->fetch_object($resql)) {
5732 $this->nb[
"invoices"] = $obj->nb;
5734 $this->db->free($resql);
5738 $this->error = $this->db->error();
5764 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5766 $outputlangs->loadLangs(array(
"bills",
"products"));
5770 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5772 if (!empty($this->model_pdf)) {
5773 $modele = $this->model_pdf;
5781 $modelpath =
"core/modules/facture/doc/";
5783 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5793 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5794 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5795 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5797 $resql = $this->db->query($sql);
5799 if ($this->db->num_rows($resql) > 0) {
5801 $obj = $this->db->fetch_object($resql);
5803 $ref = (int) $obj->maxsituationref;
5809 $this->db->free($resql);
5812 $this->error = $this->db->lasterror();
5813 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5827 return ($this->situation_counter == 1);
5841 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5842 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5843 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5844 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5845 $resql = $this->db->query($sql);
5847 if ($resql && $this->db->num_rows($resql) > 0) {
5848 while ($row = $this->db->fetch_object($resql)) {
5850 $situation =
new Facture($this->db);
5851 $situation->fetch($id);
5852 $res[] = $situation;
5855 $this->error = $this->db->error();
5856 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5876 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5879 $resql = $this->db->query($sql);
5881 $this->errors[] = $this->db->error();
5885 if (!$notrigger && empty($error)) {
5887 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5895 $this->db->commit();
5898 foreach ($this->errors as $errmsg) {
5899 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5900 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5902 $this->db->rollback();
5918 if (!empty($this->situation_cycle_ref)) {
5920 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5921 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5922 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5923 $resql = $this->db->query($sql);
5925 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5926 $last = $res[
'max(situation_counter)'];
5927 return ($last == $this->situation_counter);
5929 $this->error = $this->db->lasterror();
5930 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5988 $hasDelay = $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'));
5989 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5991 $totalpaid = (float) $totalpaid;
5993 if ($totalpaid >= 0 && $retainedWarrantyAmount >= 0) {
5994 if (($totalpaid < $this->total_ttc - $retainedWarrantyAmount) && $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'))) {
5996 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now -
getWarningDelay(
'invoice',
'client'))) {
6014 return $this->situation_cycle_ref;
6027 $displayWarranty =
false;
6028 if (!empty($this->retained_warranty)) {
6029 $displayWarranty =
true;
6033 $displayWarranty =
false;
6034 if (!empty($this->situation_final)) {
6035 $displayWarranty =
true;
6038 $displayWarranty =
true;
6040 foreach ($this->lines as $i => $line) {
6041 if ($line->product_type < 2 && $line->situation_percent < 100) {
6042 $displayWarranty =
false;
6050 return $displayWarranty;
6061 if (empty($this->retained_warranty)) {
6065 $retainedWarrantyAmount = 0;
6069 $displayWarranty =
true;
6071 if (!empty($this->lines)) {
6072 foreach ($this->lines as $i => $line) {
6073 if ($line->product_type < 2 && $line->situation_percent < 100) {
6074 $displayWarranty =
false;
6080 if ($displayWarranty && !empty($this->situation_final)) {
6082 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6086 foreach ($TPreviousIncoice as &$fac) {
6087 $total2BillWT += $fac->total_ttc;
6089 $total2BillWT += $this->total_ttc;
6092 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6098 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6101 if (is_numeric($rounding) && $rounding < 0) {
6105 if (is_numeric($rounding) && $rounding > 0) {
6106 return round($retainedWarrantyAmount, $rounding);
6109 return (
float)
price2num($retainedWarrantyAmount, $rounding);
6120 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
6122 if ($this->
status >= 0) {
6123 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6124 $sql .=
" SET retained_warranty = ".((float) $value);
6125 $sql .=
' WHERE rowid='.((int) $this->
id);
6127 if ($this->db->query($sql)) {
6128 $this->retained_warranty = (float) $value;
6131 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
6132 $this->error = $this->db->error();
6136 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
6137 $this->error =
'Status of the object is incompatible '.$this->status;
6152 if (!$timestamp && $dateYmd) {
6153 $timestamp = $this->db->jdate($dateYmd);
6157 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
6158 if ($this->
status >= 0) {
6159 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6160 $sql .=
" SET retained_warranty_date_limit = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
6161 $sql .=
' WHERE rowid = '.((int) $this->
id);
6163 if ($this->db->query($sql)) {
6164 $this->retained_warranty_date_limit = $timestamp;
6167 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
6168 $this->error = $this->db->error();
6172 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6173 $this->error =
'Status of the object is incompatible '.$this->status;
6192 global
$conf, $langs, $user;
6198 $errorsMsg = array();
6200 $langs->load(
"bills");
6203 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Invoice"));
6206 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
6207 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6217 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
6218 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
6219 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
6220 $formmail =
new FormMail($this->db);
6225 $tmpinvoice =
new Facture($this->db);
6230 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
6231 if (!empty($paymentmode) && $paymentmode !=
'all') {
6232 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
6234 $sql .=
" WHERE f.paye = 0";
6235 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
6236 if ($datetouse ==
'invoicedate') {
6237 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
6239 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
6241 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
6242 if (!empty($paymentmode) && $paymentmode !=
'all') {
6243 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
6246 if ($datetouse ==
'invoicedate') {
6247 $sql .= $this->db->order(
"datef",
"ASC");
6249 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
6253 $resql = $this->db->query($sql);
6256 if ($datetouse ==
'invoicedate') {
6257 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
6259 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
6261 if (!empty($paymentmode) && $paymentmode !=
'all') {
6262 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
6264 $this->output .=
'<br>';
6267 while ($obj = $this->db->fetch_object($resql)) {
6272 $res = $tmpinvoice->fetch($obj->id);
6274 $tmpinvoice->fetch_thirdparty();
6277 if ($tmpinvoice->thirdparty->default_lang) {
6278 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6279 $outputlangs->loadLangs(array(
"main",
"bills"));
6281 $outputlangs = $langs;
6285 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
6286 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6287 $langs->load(
"errors");
6288 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
6296 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $tmpinvoice);
6301 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6304 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6310 if ($forcerecipient) {
6311 $to = array($forcerecipient);
6313 $res = $tmpinvoice->fetch_thirdparty();
6314 $recipient = $tmpinvoice->thirdparty;
6316 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
6317 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6318 foreach ($tmparraycontact as $data_email) {
6319 if (!empty($data_email[
'email'])) {
6320 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
6324 if (empty($to) && !empty($recipient->email)) {
6325 $to[] = $recipient->email;
6328 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
6332 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6339 if (!empty($arraymessage->email_from)) {
6340 $email_from = (
string) $arraymessage->email_from;
6342 if (empty($email_from)) {
6343 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6347 if (!$loopError && !empty($to)) {
6348 $to = implode(
',', $to);
6349 if (!empty($arraymessage->email_to)) {
6350 $to = $to.
','.$arraymessage->email_to;
6356 $trackid =
'inv'.$tmpinvoice->id;
6357 $sendcontext =
'standard';
6360 if (!empty($arraymessage->email_tocc)) {
6361 $email_tocc = (
string) $arraymessage->email_tocc;
6365 if (!empty($arraymessage->email_tobcc)) {
6366 $email_tobcc = (
string) $arraymessage->email_tobcc;
6373 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6374 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
6375 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6376 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
6380 $cMailFile =
new CMailFile($sendTopic, $to, $email_from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
6382 $resultsendmail = $cMailFile->sendfile();
6387 if ($resultsendmail) {
6391 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6396 $actioncomm->type_code =
'AC_OTH_AUTO';
6397 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6398 $actioncomm->contact_id = 0;
6400 $actioncomm->code =
'AC_EMAIL';
6401 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
6402 $actioncomm->note_private = $sendContent;
6403 $actioncomm->fk_project = $tmpinvoice->fk_project;
6404 $actioncomm->datep =
dol_now();
6405 $actioncomm->datef = $actioncomm->datep;
6406 $actioncomm->percentage = -1;
6407 $actioncomm->authorid = $user->id;
6408 $actioncomm->userownerid = $user->id;
6410 $actioncomm->email_msgid = $cMailFile->msgid;
6411 $actioncomm->email_subject = $sendTopic;
6412 $actioncomm->email_from = $email_from;
6413 $actioncomm->email_sender =
'';
6414 $actioncomm->email_to = $to;
6418 $actioncomm->errors_to = $errors_to;
6420 $actioncomm->elementtype =
'invoice';
6421 $actioncomm->elementid = $tmpinvoice->id;
6425 $actioncomm->create($user);
6427 $errormesg = $cMailFile->error.
' : '.$to;
6431 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6436 $actioncomm->type_code =
'AC_OTH_AUTO';
6437 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6438 $actioncomm->contact_id = 0;
6440 $actioncomm->code =
'AC_EMAIL';
6441 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
6442 $actioncomm->note_private = $errormesg;
6443 $actioncomm->fk_project = $tmpinvoice->fk_project;
6444 $actioncomm->datep =
dol_now();
6445 $actioncomm->datef = $actioncomm->datep;
6446 $actioncomm->percentage = -1;
6447 $actioncomm->authorid = $user->id;
6448 $actioncomm->userownerid = $user->id;
6450 $actioncomm->email_msgid = $cMailFile->msgid;
6451 $actioncomm->email_subject = $sendTopic;
6452 $actioncomm->email_from = $email_from;
6453 $actioncomm->email_sender =
'';
6454 $actioncomm->email_to = $to;
6458 $actioncomm->errors_to = $errors_to;
6460 $actioncomm->elementtype =
'invoice';
6461 $actioncomm->elementid = $tmpinvoice->id;
6465 $actioncomm->create($user);
6468 $this->db->commit();
6472 $errorsMsg[] = $errormesg;
6475 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6479 $error += $loopError;
6486 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6488 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6492 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6494 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6509 $sql =
"SELECT datef";
6510 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6511 $sql .=
" WHERE type = " . (int) $this->
type ;
6512 $sql .=
" AND date_valid IS NOT NULL";
6513 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6514 $sql .=
" ORDER BY datef DESC LIMIT 1";
6516 $result = $this->db->query($sql);
6519 if ($this->db->num_rows($result)) {
6520 $obj = $this->db->fetch_object($result);
6521 $last_date = $this->db->jdate($obj->datef);
6522 $invoice_date = $this->date;
6524 $is_last_of_same_type = $invoice_date >= $last_date;
6525 if ($allow_validated_drafts) {
6529 return array($is_last_of_same_type, $last_date);
6552 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6554 $picto = $this->picto;
6555 if ($this->
type == self::TYPE_REPLACEMENT) {
6558 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6561 if ($this->
type == self::TYPE_DEPOSIT) {
6565 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6566 $return .=
'<div class="info-box info-box-sm">';
6567 $return .=
'<span class="info-box-icon bg-infobox-action">';
6569 $return .=
'</span>';
6570 $return .=
'<div class="info-box-content">';
6571 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6572 if ($selected >= 0) {
6573 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6575 if (!empty($arraydata[
'thirdparty'])) {
6576 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6578 if (property_exists($this,
'date')) {
6579 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->
date,
'day').
'</span>';
6581 if (property_exists($this,
'total_ht')) {
6582 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6583 $return .=
' '.$langs->trans(
"HT");
6584 $return .=
'</span>';
6586 if (method_exists($this,
'getLibStatut')) {
6587 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6588 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6590 $return .=
'</div>';
6591 $return .=
'</div>';
6592 $return .=
'</div>';
if(! $sortfield) if(! $sortorder) $object
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
getSumCreditNotesUsed($multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice.
getSumDepositsUsed($multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
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.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage invoices.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Returns the IDs of the customer shipping contacts.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
createFromClone(User $user, $fromid=0, $forceentity=null)
Load an object from its id and create a new one in database.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Replace a thirdparty id with another one.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines ...
update(User $user, $notrigger=0)
Update database.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
getIdBillingContact()
Returns the IDs of the customer billing contacts.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=self::TYPE_STANDARD, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=array(), $situation_percent=100, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a detail line.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target='')
Return clickable link of object (with eventually picto)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
fetch($rowid, $ref='', $ref_ext='', $notused=0, $fetch_situation=false)
Get object from database.
setInputReason($inputReasonId, $notrigger=0)
Update invoice input reason.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
updatePriceNextInvoice(&$langs)
Update price of next invoice.
getRetainedWarrantyAmount($rounding='MT')
Calculate the amount of the retained warranty (from the percentage).
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Replace a product id with another one.
setRetainedWarrantyDateLimit($timestamp, $dateYmd='')
Change the retained_warranty_date_limit.
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $datetouse='duedate', $forcerecipient='')
Send reminders by emails for invoices validated that are due.
info($id)
Load miscellaneous information for tab "Info".
const TYPE_PROFORMA
Proforma invoice (should not be used.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setRetainedWarranty($value)
Change the retained warranty.
get_prev_sits()
Returns an array containing the previous situations as Invoice objects.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
newCycle()
Gets the smallest reference available for a new cycle.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
isSituationInvoice()
Check if an invoice is a situation invoice.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getTooltipContentArray($params)
getTooltipContentArray
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
fetch_lines($only_type_product='', $loadalsotranslation=0)
Load all detailed lines into this->lines.
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
const STATUS_VALIDATED
Validated (need to be paid)
hasDelay()
Is the customer invoice delayed?
getLinesArray()
Create an array of invoice lines.
set_unpaid($user)
Tags the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a di...
const TYPE_DEPOSIT
Deposit invoice.
set_paid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
const STATUS_ABANDONED
Classified abandoned and no payment done.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
setPaid($user, $close_code='', $close_note='')
Tag the invoice as :
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed.
const TYPE_CREDIT_NOTE
Credit note invoice.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
create(User $user, $notrigger=0, $forceduedate=0, $updatecurrencyrate=0)
Create invoice in database.
initAsSpecimen($option='')
Initialise an instance with random values.
deleteLine($rowid, $id=0)
Delete line in database.
addline( $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $fk_code_ventilation=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=array(), $situation_percent=100, $fk_prev_id=0, $fk_unit=null, $pu_ht_devise=0, $ref_ext='', $noupdateafterinsertline=0)
Add an invoice line into database (linked to product/service or not).
setUnpaid($user)
Tag the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a dir...
const STATUS_CLOSED
Classified paid.
setCategories($categories)
Sets object to given categories.
createFromContract($object, User $user, $lines=array())
Load an object from a contract and create a new invoice into database.
Class to manage invoice lines.
Class to manage invoice templates.
Class to manage stock movements.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
Manage record for batch number management.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
dol_get_next_month($month, $year)
Return next month.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getWarningDelay($module, $parmlevel1, $parmlevel2='')
Return a warning delay You can use it like this: if (getWarningDelay('module', 'paramlevel1')) It rep...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.