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) {
582 if ($_facrec->rule_for_lines_dates ==
'postpaid') {
584 $originaldatewhen =
dol_time_plus_duree($originaldatewhen, -$_facrec->frequency, $_facrec->unit_frequency, 0,
'tzserver');
586 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, (
int) $_facrec->frequency, $_facrec->unit_frequency, 0,
'tzserver');
592 if (!empty($_facrec->frequency)) {
593 $this->socid = $_facrec->socid;
597 $this->entity = $_facrec->entity;
602 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
603 $this->note_public =
GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
604 $this->note_private =
GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
605 $this->model_pdf =
GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
606 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
607 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
608 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
611 $this->total_ht = $_facrec->total_ht;
612 $this->total_ttc = $_facrec->total_ttc;
615 $this->fk_incoterms = $_facrec->fk_incoterms;
616 $this->location_incoterms = $_facrec->location_incoterms;
622 $this->ref_client = trim($this->ref_client);
623 $this->ref_customer = trim($this->ref_customer);
624 $this->note_public = trim($this->note_public);
625 $this->note_private = trim($this->note_private);
626 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
629 foreach ($_facrec->array_options as $key => $val) {
630 if (!isset($this->array_options[$key]) || $this->array_options[$key] ===
'') {
631 $this->array_options[$key] = $val;
635 if (!$this->mode_reglement_id) {
636 $this->mode_reglement_id = 0;
641 $this->linked_objects = $_facrec->linkedObjectsIds;
646 if ($_facrec->frequency > 0) {
647 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
648 if (empty($_facrec->date_when)) {
649 $_facrec->date_when = $now;
651 $next_date = $_facrec->getNextDate();
653 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
656 $result = $_facrec->setNextDate($next_date, 1);
660 $outputlangs = $langs;
663 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
664 $newlang = $this->thirdparty->default_lang;
667 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
668 $newlang = $this->default_lang;
670 if (!empty($newlang)) {
672 $outputlangs->setDefaultLang($newlang);
676 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $this);
687 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
688 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
689 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
690 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
691 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
702 if (empty($forceduedate)) {
708 $this->date_lim_reglement = $duedate;
710 $this->date_lim_reglement = $forceduedate;
714 $socid = $this->socid;
716 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
725 $sql .=
", date_pointoftax";
726 $sql .=
", note_private";
727 $sql .=
", note_public";
728 $sql .=
", ref_client";
729 $sql .=
", fk_account";
730 $sql .=
", module_source, pos_source, pos_print_counter, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
731 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
732 $sql .=
", fk_input_reason";
733 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
734 $sql .=
", fk_incoterms, location_incoterms";
735 $sql .=
", fk_multicurrency";
736 $sql .=
", multicurrency_code";
737 $sql .=
", multicurrency_tx";
738 $sql .=
", retained_warranty";
739 $sql .=
", retained_warranty_date_limit";
740 $sql .=
", retained_warranty_fk_cond_reglement";
745 $sql .=
", ".(int) $this->entity;
746 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
747 $sql .=
", ".((int) $this->
type);
748 $sql .=
", ".(isset($this->subtype) ? (int) $this->subtype :
"null");
749 $sql .=
", ".((int) $socid);
750 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
753 $sql .=
", '".$this->db->idate($this->
date).
"'";
754 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
755 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
756 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
757 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
758 $sql .=
", ".($this->fk_account > 0 ? ((int) $this->fk_account) :
'NULL');
759 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
760 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape((
string) $this->pos_source).
"'" :
"null");
761 $sql .=
", ".(int) $this->pos_print_counter;
762 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape((
string) $this->fk_fac_rec_source).
"'" :
"null");
763 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape((
string) $this->fk_facture_source).
"'" :
"null");
764 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
765 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
766 $sql .=
", ".((int) $this->cond_reglement_id);
767 $sql .=
", ".((int) $this->mode_reglement_id);
768 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
769 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
770 $sql .=
", ".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id :
"null");
771 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape((
string) $this->situation_cycle_ref).
"'" :
"null");
772 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape((
string) $this->situation_counter).
"'" :
"null");
773 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
774 $sql .=
", ".(int) $this->fk_incoterms;
775 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
776 $sql .=
", ".(int) $this->fk_multicurrency;
777 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
778 $sql .=
", ".(float) $this->multicurrency_tx;
779 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape((
string) $this->retained_warranty));
780 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
781 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
782 $sql .=
", ".(!empty($this->ip) ?
"'".$this->db->escape($this->ip).
"'" :
"null");
785 $resql = $this->db->query($sql);
787 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
790 $this->
ref =
'(PROV'.$this->id.
')';
791 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
793 $resql = $this->db->query($sql);
798 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
799 $this->linked_objects = $this->linkedObjectsIds;
803 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
804 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
805 if (is_array($tmp_origin_id)) {
806 foreach ($tmp_origin_id as $origin_id) {
809 $this->error = $this->db->lasterror();
814 $origin_id = $tmp_origin_id;
817 $this->error = $this->db->lasterror();
825 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && (!empty($this->origin_type) || !empty($this->origin)) && !empty($this->origin_id)) {
826 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
827 $originidforcontact = $this->origin_id;
828 if ($originforcontact ==
'shipping') {
829 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
831 $exp->fetch($this->origin_id);
832 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
833 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
834 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
835 $originforcontact =
'commande';
836 if (is_object($value)) {
837 $originidforcontact = $value->id;
839 $originidforcontact = $value;
846 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople";
847 $sqlcontact .=
" FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
848 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
850 $resqlcontact = $this->db->query($sqlcontact);
852 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
853 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
861 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
864 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
865 foreach ($this->lines as $i => $val) {
866 $newinvoiceline = $this->lines[$i];
867 '@phan-var-force FactureLigne $newinvoiceline';
869 $newinvoiceline->context = $this->context;
871 $newinvoiceline->fk_facture = $this->id;
873 $newinvoiceline->origin = $this->lines[$i]->element;
874 $newinvoiceline->origin_type = $this->lines[$i]->element;
875 $newinvoiceline->origin_id = $this->lines[$i]->id;
878 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
879 $newinvoiceline->date_start = $originaldatewhen;
881 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
882 $newinvoiceline->date_end = $previousdaynextdatewhen;
887 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
892 $vatrate = $newinvoiceline->tva_tx;
893 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
894 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
897 $newinvoiceline->fk_parent_line = $fk_parent_line;
901 $discount->fetch($newinvoiceline->fk_remise_except);
903 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
904 $newinvoiceline->fk_remise_except = $discountId;
908 $newinvoiceline->desc,
909 $newinvoiceline->subprice,
910 $newinvoiceline->qty,
912 $newinvoiceline->localtax1_tx,
913 $newinvoiceline->localtax2_tx,
914 $newinvoiceline->fk_product,
915 $newinvoiceline->remise_percent,
916 $newinvoiceline->date_start,
917 $newinvoiceline->date_end,
918 $newinvoiceline->fk_code_ventilation,
919 $newinvoiceline->info_bits,
920 $newinvoiceline->fk_remise_except,
923 $newinvoiceline->product_type,
924 $newinvoiceline->rang,
925 $newinvoiceline->special_code,
926 $newinvoiceline->element,
929 $newinvoiceline->fk_fournprice,
930 $newinvoiceline->pa_ht,
931 $newinvoiceline->label,
932 $newinvoiceline->array_options,
933 $newinvoiceline->situation_percent,
934 $newinvoiceline->fk_prev_id,
935 $newinvoiceline->fk_unit,
936 $newinvoiceline->multicurrency_subprice,
937 $newinvoiceline->ref_ext,
948 if ($result > 0 && $newinvoiceline->product_type == 9) {
949 $fk_parent_line = $result;
953 } elseif (!$error && empty($this->fac_rec)) {
956 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
958 foreach ($this->lines as $i => $val) {
959 $line = $this->lines[$i];
960 '@phan-var-force FactureLigne $line';
964 if (!is_object($line)) {
965 $line = (object) $line;
970 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
975 $vatrate = $line->tva_tx;
976 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
977 $vatrate .=
' ('.$line->vat_src_code.
')';
981 $originid = $line->origin_id;
982 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
984 $originid = $line->id;
985 $origintype = $this->element;
989 if (empty($line->ref_ext)) {
1001 $line->remise_percent,
1004 $line->fk_code_ventilation,
1006 $line->fk_remise_except,
1009 $line->product_type,
1011 $line->special_code,
1015 $line->fk_fournprice,
1018 $line->array_options,
1019 $line->situation_percent,
1022 $line->multicurrency_subprice,
1027 $this->error = $this->db->lasterror();
1029 $this->db->rollback();
1034 if ($result > 0 && $line->product_type == 9) {
1035 $fk_parent_line = $result;
1042 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1043 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1044 $fk_parent_line = 0;
1046 foreach ($_facrec->lines as $i => $val) {
1048 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1049 $fk_parent_line = 0;
1052 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1053 $tva_npr = (int) $_facrec->lines[$i]->info_bits;
1054 if (empty($tva_tx)) {
1057 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1058 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1060 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1061 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1064 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1065 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1067 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1072 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1073 $buyprice = $producttmp->cost_price;
1075 $buyprice = $producttmp->pmp;
1077 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1078 if ($producttmp->product_fourn_price_id > 0) {
1079 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1086 if ($updatecurrencyrate == 1) {
1088 } elseif ($updatecurrencyrate == 2) {
1092 $result_insert = $this->
addline(
1093 $_facrec->lines[$i]->desc,
1094 $_facrec->lines[$i]->subprice,
1095 $_facrec->lines[$i]->qty,
1099 $_facrec->lines[$i]->fk_product,
1100 $_facrec->lines[$i]->remise_percent,
1101 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1102 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1108 $_facrec->lines[$i]->product_type,
1109 $_facrec->lines[$i]->rang,
1110 $_facrec->lines[$i]->special_code,
1114 $fk_product_fournisseur_price,
1115 is_null($buyprice) ?
'' : $buyprice,
1116 $_facrec->lines[$i]->label,
1117 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1120 $_facrec->lines[$i]->fk_unit,
1121 $_facrec->lines[$i]->multicurrency_subprice,
1122 $_facrec->lines[$i]->ref_ext,
1126 foreach ($this->lines as $line) {
1127 if ($line->id == $result_insert) {
1128 $line->extraparams = $_facrec->lines[$i]->extraparams;
1129 $line->setExtraParameters();
1134 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1135 $fk_parent_line = $result_insert;
1138 if ($result_insert < 0) {
1140 $this->error = $this->db->error();
1149 $this->error = $langs->trans(
'FailedToUpdatePrice');
1150 $this->db->rollback();
1165 if (!$error && !$notrigger) {
1167 $result = $this->call_trigger(
'BILL_CREATE', $user);
1174 $this->db->commit();
1177 $this->db->rollback();
1181 $this->error = $this->db->error();
1182 $this->db->rollback();
1198 $facture =
new Facture($this->db);
1201 $facture->context[
'createfromclone'] = 1;
1206 if (empty($this->array_options)) {
1210 if (!empty($this->array_options)) {
1211 $facture->array_options = $this->array_options;
1214 foreach ($this->lines as &$line) {
1215 $line->fetch_optionals();
1218 $facture->fk_facture_source = $this->fk_facture_source;
1219 $facture->type = $this->type;
1220 $facture->subtype = $this->subtype;
1221 $facture->socid = $this->socid;
1222 $facture->date = $this->date;
1223 $facture->date_pointoftax = $this->date_pointoftax;
1224 $facture->note_public = $this->note_public;
1225 $facture->note_private = $this->note_private;
1226 $facture->ref_client = $this->ref_client;
1227 $facture->ref_customer = $this->ref_customer;
1228 $facture->model_pdf = $this->model_pdf;
1229 $facture->fk_project = $this->fk_project;
1230 $facture->cond_reglement_id = $this->cond_reglement_id;
1231 $facture->mode_reglement_id = $this->mode_reglement_id;
1233 $facture->origin = $this->origin;
1234 $facture->origin_id = $this->origin_id;
1235 $facture->fk_account = $this->fk_account;
1237 $facture->lines = $this->lines;
1238 $facture->situation_counter = $this->situation_counter;
1239 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1240 $facture->situation_final = $this->situation_final;
1242 $facture->retained_warranty = $this->retained_warranty;
1243 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1244 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1246 $facture->fk_user_author = $user->id;
1247 $facture->user_creation_id = $user->id;
1251 foreach ($facture->lines as $i => $tmpline) {
1252 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1253 if ($invertdetail) {
1254 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1255 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1256 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1257 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1258 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1259 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1260 $facture->lines[$i]->ref_ext =
'';
1264 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1266 $facid = $facture->create($user);
1268 $this->error = $facture->error;
1269 $this->errors = $facture->errors;
1273 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1274 foreach ($Tfk_object as $fk_object) {
1275 $facture->add_object_linked($typeObject, $fk_object);
1279 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1296 global $hookmanager;
1316 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1317 $objsoc =
new Societe($this->db);
1319 if ($objsoc->fetch($this->socid) > 0) {
1321 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1322 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1324 $object->fk_delivery_address = 0;
1330 $object->entity = (!empty($forceentity) ? $forceentity :
$object->entity);
1338 $object->user_creation_id = $user->id;
1339 $object->user_validation_id =
null;
1340 $object->user_modification_id =
null;
1341 $object->fk_user_author = $user->id;
1342 $object->fk_user_valid =
null;
1343 $object->fk_facture_source = 0;
1344 $object->fk_fac_rec_source = 0;
1346 $object->date_modification =
'';
1347 $object->date_validation =
'';
1358 foreach (
$object->lines as $i => $line) {
1359 '@phan-var-force FactureLigne $line';
1360 if (($line->info_bits & 0x02) == 0x02) {
1367 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1379 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1380 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1384 $object->lines[$i]->date_start = $newFirst;
1385 $object->lines[$i]->date_end = $newLast;
1389 $object->lines[$i]->ref_ext =
'';
1392 $object->lines[$i]->fk_code_ventilation = 0;
1396 $object->context[
'createfromclone'] =
'createfromclone';
1397 $result =
$object->create($user);
1404 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1407 } elseif (
$object->socid == $objFrom->socid) {
1409 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1418 if (is_object($hookmanager)) {
1419 $parameters = array(
'objFrom' => $objFrom,
'clonedObj' =>
$object);
1421 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1429 unset(
$object->context[
'createfromclone']);
1433 $this->db->commit();
1436 $this->db->rollback();
1450 global $hookmanager;
1459 $this->context[
'createfromclone'] = 1;
1462 for ($i = 0; $i < $num; $i++) {
1464 $src_line =
$object->lines[$i];
1465 '@phan-var-force FactureLigne $src_line';
1466 $line->libelle = $src_line->libelle;
1467 $line->label = $src_line->label;
1468 $line->desc = $src_line->desc;
1469 $line->subprice = $src_line->subprice;
1470 $line->total_ht = $src_line->total_ht;
1471 $line->total_tva = $src_line->total_tva;
1472 $line->total_localtax1 = $src_line->total_localtax1;
1473 $line->total_localtax2 = $src_line->total_localtax2;
1474 $line->total_ttc = $src_line->total_ttc;
1475 $line->vat_src_code = $src_line->vat_src_code;
1476 $line->tva_tx = $src_line->tva_tx;
1477 $line->localtax1_tx = $src_line->localtax1_tx;
1478 $line->localtax2_tx = $src_line->localtax2_tx;
1479 $line->qty = $src_line->qty;
1480 $line->fk_remise_except = $src_line->fk_remise_except;
1481 $line->remise_percent = $src_line->remise_percent;
1482 $line->fk_product = $src_line->fk_product;
1483 $line->info_bits = $src_line->info_bits;
1484 $line->product_type = $src_line->product_type;
1485 $line->rang = $src_line->rang;
1486 $line->special_code = $src_line->special_code;
1487 $line->fk_parent_line = $src_line->fk_parent_line;
1488 $line->fk_unit = $src_line->fk_unit;
1489 $line->date_start = $src_line->date_start;
1490 $line->date_end = $src_line->date_end;
1493 $line->fk_multicurrency = $src_line->fk_multicurrency;
1494 $line->multicurrency_code = $src_line->multicurrency_code;
1495 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1496 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1497 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1498 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1500 $line->fk_fournprice = $src_line->fk_fournprice;
1501 $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);
1502 $line->pa_ht = $marginInfos[0];
1505 $src_line->fetch_optionals();
1506 foreach ($src_line->array_options as $options_key => $value) {
1507 $line->array_options[$options_key] = $value;
1510 $this->lines[$i] = $line;
1513 $this->socid =
$object->socid;
1514 $this->fk_project =
$object->fk_project;
1515 $this->fk_account =
$object->fk_account;
1516 $this->cond_reglement_id =
$object->cond_reglement_id;
1517 $this->mode_reglement_id =
$object->mode_reglement_id;
1518 $this->fk_incoterms =
$object->fk_incoterms;
1519 $this->location_incoterms =
$object->location_incoterms;
1520 $this->availability_id =
$object->availability_id;
1521 $this->demand_reason_id =
$object->demand_reason_id;
1522 $this->delivery_date =
$object->delivery_date;
1523 $this->fk_delivery_address =
$object->fk_delivery_address;
1524 $this->contact_id =
$object->contact_id;
1525 $this->ref_client =
$object->ref_client;
1526 $this->ref_customer =
$object->ref_client;
1529 $this->note_private =
$object->note_private;
1530 $this->note_public =
$object->note_public;
1533 $this->module_source =
$object->module_source;
1534 $this->pos_source =
$object->pos_source;
1536 $this->origin =
$object->element;
1537 $this->origin_type =
$object->element;
1538 $this->origin_id =
$object->id;
1540 $this->fk_user_author = $user->id;
1541 $this->user_creation_id = $user->id;
1545 foreach (
$object->array_options as $options_key => $value) {
1546 $this->array_options[$options_key] = $value;
1550 $this->linked_objects[$this->origin] = $this->origin_id;
1551 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1552 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1555 $ret = $this->
create($user);
1559 $hookmanager->initHooks(array(
'invoicedao'));
1561 $parameters = array(
'objFrom' =>
$object);
1563 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1572 unset($this->context[
'createfromclone']);
1591 global $hookmanager;
1599 $use_all_lines = empty($lines);
1601 for ($i = 0; $i < $num; $i++) {
1602 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1608 $line->libelle =
$object->lines[$i]->libelle;
1609 $line->label =
$object->lines[$i]->label;
1610 $line->desc =
$object->lines[$i]->desc;
1611 $line->subprice =
$object->lines[$i]->subprice;
1612 $line->total_ht =
$object->lines[$i]->total_ht;
1613 $line->total_tva =
$object->lines[$i]->total_tva;
1614 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1615 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1616 $line->total_ttc =
$object->lines[$i]->total_ttc;
1617 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1618 $line->tva_tx =
$object->lines[$i]->tva_tx;
1619 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1620 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1621 $line->qty =
$object->lines[$i]->qty;
1622 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1623 $line->remise_percent =
$object->lines[$i]->remise_percent;
1624 $line->fk_product =
$object->lines[$i]->fk_product;
1625 $line->info_bits =
$object->lines[$i]->info_bits;
1626 $line->product_type =
$object->lines[$i]->product_type;
1627 $line->rang =
$object->lines[$i]->rang;
1628 $line->special_code =
$object->lines[$i]->special_code;
1629 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1630 $line->fk_unit =
$object->lines[$i]->fk_unit;
1631 $line->date_start =
$object->lines[$i]->date_start;
1632 $line->date_end =
$object->lines[$i]->date_end;
1635 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1636 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1637 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1638 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1639 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1640 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1642 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1644 $line->pa_ht = $marginInfos[0];
1647 $object->lines[$i]->fetch_optionals();
1648 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1649 $line->array_options[$options_key] = $value;
1652 $this->lines[$i] = $line;
1655 $this->socid =
$object->socid;
1656 $this->fk_project =
$object->fk_project;
1657 $this->fk_account =
$object->fk_account;
1658 $this->cond_reglement_id =
$object->cond_reglement_id;
1659 $this->mode_reglement_id =
$object->mode_reglement_id;
1660 $this->availability_id =
$object->availability_id;
1661 $this->demand_reason_id =
$object->demand_reason_id;
1662 $this->delivery_date =
$object->delivery_date;
1663 $this->fk_delivery_address =
$object->fk_delivery_address;
1664 $this->contact_id =
$object->contact_id;
1665 $this->ref_client =
$object->ref_client;
1668 $this->note_private =
$object->note_private;
1669 $this->note_public =
$object->note_public;
1672 $this->module_source =
$object->module_source;
1673 $this->pos_source =
$object->pos_source;
1675 $this->origin =
$object->element;
1676 $this->origin_id =
$object->id;
1678 $this->fk_user_author = $user->id;
1679 $this->user_creation_id = $user->id;
1683 foreach (
$object->array_options as $options_key => $value) {
1684 $this->array_options[$options_key] = $value;
1688 $this->linked_objects[$this->origin] = $this->origin_id;
1689 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1690 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1693 $ret = $this->
create($user);
1697 $hookmanager->initHooks(array(
'invoicedao'));
1699 $parameters = array(
'objFrom' =>
$object);
1701 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1731 global
$conf, $langs, $hookmanager, $action;
1733 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1734 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1739 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1743 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1746 $origin->error =
'ErrorDateIsInFuture';
1750 if ($payment_terms_id <= 0) {
1751 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1755 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1757 if (empty($payment_conditions_deposit_percent)) {
1758 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1762 if (empty($origin->deposit_percent)) {
1763 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1767 $deposit =
new self($origin->db);
1768 $deposit->socid = $origin->socid;
1770 $deposit->fk_project = $origin->fk_project;
1771 $deposit->ref_client = $origin->ref_client;
1772 $deposit->ref_customer = $origin->ref_client;
1773 $deposit->date = $date;
1774 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1775 $deposit->cond_reglement_id = $payment_terms_id;
1776 $deposit->availability_id = $origin->availability_id;
1777 $deposit->demand_reason_id = $origin->demand_reason_id;
1778 $deposit->fk_account = $origin->fk_account;
1779 $deposit->fk_incoterms = $origin->fk_incoterms;
1780 $deposit->location_incoterms = $origin->location_incoterms;
1781 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1782 $deposit->multicurrency_code = $origin->multicurrency_code;
1783 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1784 $deposit->module_source = $origin->module_source;
1785 $deposit->pos_source = $origin->pos_source;
1786 $deposit->model_pdf =
'sponge';
1788 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1797 $deposit->note_private = $origin->note_private;
1798 $deposit->note_public = $origin->note_public;
1801 $deposit->origin = $origin->element;
1802 $deposit->origin_type = $origin->element;
1803 $deposit->origin_id = $origin->id;
1805 $origin->fetch_optionals();
1807 foreach ($origin->array_options as $extrakey => $value) {
1808 $deposit->array_options[$extrakey] = $value;
1811 $deposit->linked_objects[$deposit->origin_type] = $deposit->origin_id;
1813 foreach ($overrideFields as $key => $value) {
1814 $deposit->$key = $value;
1817 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1819 $origin->db->begin();
1822 $createReturn = $deposit->create($user, $notrigger);
1824 if ($createReturn <= 0) {
1825 $origin->db->rollback();
1826 $origin->error = $deposit->error;
1827 $origin->errors = $deposit->errors;
1831 $amount_ttc_diff = 0;
1832 $amountdeposit = array();
1833 $descriptions = array();
1840 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1842 $TTotalByTva = array();
1843 foreach ($origin->lines as &$line) {
1844 if (!empty($line->special_code)) {
1847 $key = $line->tva_tx . ($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
1848 if (!array_key_exists($key, $TTotalByTva)) {
1849 $TTotalByTva[$key] = 0;
1850 $descriptions[$key] =
'';
1852 $TTotalByTva[$key] += $line->total_ttc;
1853 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1854 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1855 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1856 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1859 foreach ($TTotalByTva as $tva => &$total) {
1860 $tva_rate_only = preg_replace(
'/\s*\(.*\)/',
'', (
string) $tva);
1861 $coef = $total / $origin->total_ttc;
1862 $am = $amount * $coef;
1863 $amount_ttc_diff += $am;
1864 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100);
1868 $lines = $origin->lines;
1869 $numlines = count($lines);
1870 for ($i = 0; $i < $numlines; $i++) {
1871 if (empty($lines[$i]->qty)) {
1874 if (!empty($lines[$i]->special_code)) {
1878 $totalamount += $lines[$i]->total_ht;
1879 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ?
' ('.$lines[$i]->vat_src_code.
')' :
'');
1880 if (!isset($amountdeposit[$tva_key])) {
1881 $amountdeposit[$tva_key] = 0;
1882 $descriptions[$tva_key] =
'';
1884 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1885 $descriptions[$tva_key] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1886 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1887 $descriptions[$tva_key] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1888 $descriptions[$tva_key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1891 if ($totalamount == 0) {
1892 $amountdeposit[0] = 0;
1895 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1898 foreach ($amountdeposit as $tva => $amount) {
1899 if (empty($amount)) {
1903 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1906 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1907 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1910 $addlineResult = $deposit->addline(
1937 if ($addlineResult < 0) {
1938 $origin->db->rollback();
1939 $origin->error = $deposit->error;
1940 $origin->errors = $deposit->errors;
1945 $diff = $deposit->total_ttc - $amount_ttc_diff;
1948 $deposit->fetch_lines();
1949 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1953 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ?
' ('.$deposit->lines[0]->vat_src_code.
')' :
'');
1954 $updatelineResult = $deposit->updateline(
1955 $deposit->lines[0]->id,
1956 $deposit->lines[0]->desc,
1958 $deposit->lines[0]->qty,
1959 $deposit->lines[0]->remise_percent,
1960 $deposit->lines[0]->date_start,
1961 $deposit->lines[0]->date_end,
1966 $deposit->lines[0]->info_bits,
1967 $deposit->lines[0]->product_type,
1971 $deposit->lines[0]->pa_ht,
1972 $deposit->lines[0]->label,
1978 if ($updatelineResult < 0) {
1979 $origin->db->rollback();
1980 $origin->error = $deposit->error;
1981 $origin->errors = $deposit->errors;
1986 $hookmanager->initHooks(array(
'invoicedao'));
1988 $parameters = array(
'objFrom' => $origin);
1989 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1992 $origin->db->rollback();
1993 $origin->error = $hookmanager->error;
1994 $origin->errors = $hookmanager->errors;
1998 if (!empty($autoValidateDeposit)) {
1999 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
2001 if ($validateReturn < 0) {
2002 $origin->db->rollback();
2003 $origin->error = $deposit->error;
2004 $origin->errors = $deposit->errors;
2009 unset($deposit->context[
'createdepositfromorigin']);
2011 $origin->db->commit();
2027 $langs->load(
'bills');
2030 $moretitle = $params[
'moretitle'] ??
'';
2032 $picto = $this->picto;
2033 if ($this->
type == self::TYPE_REPLACEMENT) {
2036 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2039 if ($this->
type == self::TYPE_DEPOSIT) {
2043 if ($user->hasRight(
"facture",
"read")) {
2044 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
2046 $datas[
'picto'] .=
' '.$this->getLibType(1);
2049 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
2052 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2055 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
2058 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2059 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2062 $datas[
'picto'] .=
' - '.$moretitle;
2064 if (!empty($this->
ref)) {
2065 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2067 if (!empty($this->ref_customer)) {
2068 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
2070 if (!empty($this->
date)) {
2071 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->
date,
'day');
2073 if (!empty($this->total_ht)) {
2074 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2076 if (!empty($this->total_tva)) {
2077 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2079 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2080 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1,
$conf->currency);
2082 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2084 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1',
$mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency);
2086 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2087 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2',
$mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency);
2089 if (!empty($this->total_ttc)) {
2090 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2111 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2113 global $langs,
$conf, $user;
2115 if (!empty(
$conf->dol_no_mouse_hover)) {
2121 if ($option ==
'withdraw') {
2122 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2124 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2127 if (!$user->hasRight(
"facture",
"read")) {
2131 if ($option !==
'nolink') {
2133 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2134 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2135 $add_save_lastsearch_values = 1;
2137 if ($add_save_lastsearch_values) {
2138 $url .=
'&save_lastsearch_values=1';
2146 $picto = $this->picto;
2147 if ($this->
type == self::TYPE_REPLACEMENT) {
2150 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2153 if ($this->
type == self::TYPE_DEPOSIT) {
2159 'objecttype' => $this->element,
2160 'moretitle' => $moretitle,
2161 'option' => $option,
2163 $classfortooltip =
'classfortooltip';
2166 $classfortooltip =
'classforajaxtooltip';
2167 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2173 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2174 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2176 $label = $langs->trans(
"Invoice");
2177 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2179 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2180 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2183 $linkstart =
'<a href="'.$url.
'"';
2184 $linkstart .= $linkclose.
'>';
2187 if ($option ==
'nolink') {
2192 $result .= $linkstart;
2194 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2196 if ($withpicto != 2) {
2197 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2199 $result .= $linkend;
2201 if ($addlinktonotes) {
2202 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2204 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2205 $result .=
' <span class="note inline-block">';
2206 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dolPrintHTMLForAttribute($notetoshow).
'">';
2209 $result .=
'</span>';
2213 global $action, $hookmanager;
2214 $hookmanager->initHooks(array(
'invoicedao'));
2215 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2216 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2218 $result = $hookmanager->resPrint;
2220 $result .= $hookmanager->resPrint;
2236 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2238 global
$conf, $extrafields;
2240 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2244 $extraFieldsCheck =
false;
2245 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2247 if ($doFetchInOneSqlRequest) {
2249 if (!isset($extrafields) || !is_object($extrafields)) {
2250 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2255 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
2256 $extrafields->fetch_name_optionals_label($this->table_element);
2259 $extraFieldsCheck = (
2260 !empty($extrafields->attributes[$this->table_element][
'label'])
2261 && is_array($extrafields->attributes[$this->table_element][
'label'])
2262 && count($extrafields->attributes[$this->table_element][
'label']) > 0
2268 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2269 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2270 $sql .=
', f.datef as df, f.date_pointoftax';
2271 $sql .=
', f.date_lim_reglement as dlr';
2272 $sql .=
', f.datec as datec';
2273 $sql .=
', f.date_valid as datev';
2274 $sql .=
', f.tms as datem';
2275 $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';
2276 $sql .=
", f.fk_input_reason";
2277 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2278 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2279 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2280 $sql .=
', f.fk_account';
2281 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2282 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2283 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2284 $sql .=
', f.fk_incoterms, f.location_incoterms';
2285 $sql .=
', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2286 $sql .=
", i.libelle as label_incoterms";
2287 $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";
2288 $sql .=
", f.payment_reference, f.dispute_status";
2290 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2291 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2292 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2293 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2296 if ($type !==
'separate') {
2297 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2298 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2300 $sql .=
", ef.".$this->db->sanitize($key);
2306 $sql .=
' FROM '.$this->db->prefix().
'facture as f';
2309 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2311 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element.
'_extrafields as ef ON f.rowid = ef.fk_object';
2314 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2315 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_paiement as p ON f.fk_mode_reglement = p.id';
2316 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2317 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2320 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2322 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2324 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2327 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2331 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2332 $resql = $this->db->query($sql);
2334 if ($this->db->num_rows($resql)) {
2335 $obj = $this->db->fetch_object($resql);
2337 $this->
id = $obj->rowid;
2338 $this->entity = $obj->entity;
2340 $this->
ref = $obj->ref;
2341 $this->ref_client = $obj->ref_client;
2342 $this->ref_customer = $obj->ref_client;
2343 $this->ref_ext = $obj->ref_ext;
2344 $this->
type = $obj->type;
2345 $this->subtype = $obj->subtype;
2346 $this->
date = $this->db->jdate($obj->df);
2347 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2348 $this->date_creation = $this->db->jdate($obj->datec);
2349 $this->date_validation = $this->db->jdate($obj->datev);
2350 $this->date_modification = $this->db->jdate($obj->datem);
2351 $this->datem = $this->db->jdate($obj->datem);
2352 $this->total_ht = $obj->total_ht;
2353 $this->total_tva = $obj->total_tva;
2354 $this->total_localtax1 = $obj->localtax1;
2355 $this->total_localtax2 = $obj->localtax2;
2356 $this->total_ttc = $obj->total_ttc;
2357 $this->revenuestamp = $obj->revenuestamp;
2358 $this->paye = $obj->paye;
2359 $this->close_code = $obj->close_code;
2360 $this->close_note = $obj->close_note;
2362 $this->socid = $obj->fk_soc;
2363 $this->thirdparty =
null;
2365 $this->fk_project = $obj->fk_project;
2366 $this->project =
null;
2368 $this->statut = $obj->status;
2369 $this->
status = $obj->status;
2371 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2372 $this->mode_reglement_id = $obj->fk_mode_reglement;
2373 $this->mode_reglement_code = $obj->mode_reglement_code;
2374 $this->mode_reglement = $obj->mode_reglement_libelle;
2375 $this->cond_reglement_id = $obj->fk_cond_reglement;
2376 $this->cond_reglement_code = $obj->cond_reglement_code;
2377 $this->cond_reglement = $obj->cond_reglement_libelle;
2378 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2379 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2380 $this->fk_facture_source = $obj->fk_facture_source;
2381 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2382 $this->note = $obj->note_private;
2383 $this->note_private = $obj->note_private;
2384 $this->note_public = $obj->note_public;
2385 $this->user_creation_id = $obj->fk_user_author;
2386 $this->user_validation_id = $obj->fk_user_valid;
2387 $this->user_modification_id = $obj->fk_user_modif;
2388 $this->fk_user_author = $obj->fk_user_author;
2389 $this->fk_user_valid = $obj->fk_user_valid;
2390 $this->fk_user_modif = $obj->fk_user_modif;
2391 $this->model_pdf = $obj->model_pdf;
2392 $this->last_main_doc = $obj->last_main_doc;
2393 $this->demand_reason_id = $obj->fk_input_reason;
2394 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2395 $this->situation_counter = $obj->situation_counter;
2396 $this->situation_final = $obj->situation_final;
2397 $this->retained_warranty = $obj->retained_warranty;
2398 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2399 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2401 $this->payment_reference = $obj->payment_reference;
2402 $this->dispute_status = $obj->dispute_status;
2404 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2407 $this->fk_incoterms = $obj->fk_incoterms;
2408 $this->location_incoterms = $obj->location_incoterms;
2409 $this->label_incoterms = $obj->label_incoterms;
2411 $this->module_source = $obj->module_source;
2412 $this->pos_source = $obj->pos_source;
2413 $this->pos_print_counter = (int) $obj->pos_print_counter;
2414 $this->email_sent_counter = $obj->email_sent_counter;
2417 $this->fk_multicurrency = $obj->fk_multicurrency;
2418 $this->multicurrency_code = $obj->multicurrency_code;
2419 $this->multicurrency_tx = $obj->multicurrency_tx;
2420 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2421 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2422 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2425 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2426 $this->array_options = array();
2428 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2429 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2430 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2433 if ($type !==
'separate') {
2434 $rawval = $obj->$key;
2437 if (in_array($type, array(
'date',
'datetime'))) {
2438 $this->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2439 } elseif ($type ==
'password') {
2440 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2441 $this->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2443 $this->array_options[
'options_' . $key] = $rawval;
2446 $this->array_options[
'options_' . $key] = $rawval;
2452 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2453 if (!empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
2454 if (empty(
$conf->disable_compute)) {
2455 global $objectoffield;
2456 $objectoffield = $this;
2457 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
2463 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2467 if (!$doFetchInOneSqlRequest) {
2474 $this->lines = array();
2478 $this->error = $this->db->error();
2482 $this->db->free($resql);
2486 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2488 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2492 $this->error = $this->db->lasterror();
2506 public function fetch_lines($only_type_product =
'', $loadalsotranslation = 0)
2508 global
$conf, $extrafields;
2511 $this->lines = array();
2513 $extraFieldsCheck =
false;
2514 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2516 if ($doFetchInOneSqlRequest) {
2518 if (!isset($extrafields) || !is_object($extrafields)) {
2519 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2524 if (empty($extrafields->attributes[$this->table_element_line][
'loaded'])) {
2525 $extrafields->fetch_name_optionals_label($this->table_element_line);
2528 $extraFieldsCheck = (
2529 !empty($extrafields->attributes[$this->table_element_line][
'label'])
2530 && is_array($extrafields->attributes[$this->table_element_line][
'label'])
2531 && count($extrafields->attributes[$this->table_element_line][
'label']) > 0
2535 $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,';
2536 $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,';
2537 $sql .=
' l.situation_percent, l.fk_prev_id,';
2538 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2539 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2540 $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,';
2541 $sql .=
' l.fk_unit, l.extraparams,';
2542 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2543 $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';
2545 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2546 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2547 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2548 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2551 if ($type !==
'separate') {
2552 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2553 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2555 $sql .=
", ef.".$this->db->sanitize($key);
2561 $sql .=
' FROM '.$this->db->prefix().
'facturedet as l';
2564 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2566 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element_line.
'_extrafields as ef ON l.rowid = ef.fk_object';
2569 $sql .=
' LEFT JOIN '.$this->db->prefix().
'product as p ON l.fk_product = p.rowid';
2570 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2571 if (is_int($only_type_product)) {
2572 $sql .=
" AND p.fk_product_type = ".((int) $only_type_product);
2574 $sql .=
' ORDER BY l.rang, l.rowid';
2576 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2577 $result = $this->db->query($sql);
2579 $num = $this->db->num_rows($result);
2582 $objp = $this->db->fetch_object($result);
2585 $line->id = $objp->rowid;
2586 $line->rowid = $objp->rowid;
2587 $line->fk_facture = $objp->fk_facture;
2588 $line->label = $objp->custom_label;
2589 $line->desc = $objp->description;
2590 $line->description = $objp->description;
2591 $line->product_type = $objp->product_type;
2592 $line->ref = $objp->product_ref;
2593 $line->product_ref = $objp->product_ref;
2594 $line->libelle = $objp->product_label;
2595 $line->product_label = $objp->product_label;
2596 $line->product_barcode = $objp->product_barcode;
2597 $line->product_desc = $objp->product_desc;
2598 $line->fk_product_type = $objp->fk_product_type;
2599 $line->qty = $objp->qty;
2600 $line->subprice = $objp->subprice;
2601 $line->ref_ext = $objp->ref_ext;
2603 $line->vat_src_code = $objp->vat_src_code;
2604 $line->tva_tx = $objp->tva_tx;
2605 $line->localtax1_tx = $objp->localtax1_tx;
2606 $line->localtax2_tx = $objp->localtax2_tx;
2607 $line->localtax1_type = $objp->localtax1_type;
2608 $line->localtax2_type = $objp->localtax2_type;
2609 $line->remise_percent = $objp->remise_percent;
2610 $line->fk_remise_except = $objp->fk_remise_except;
2611 $line->fk_product = $objp->fk_product;
2612 $line->date_start = $this->db->jdate($objp->date_start);
2613 $line->date_end = $this->db->jdate($objp->date_end);
2614 $line->info_bits = $objp->info_bits;
2615 $line->total_ht = $objp->total_ht;
2616 $line->total_tva = $objp->total_tva;
2617 $line->total_localtax1 = $objp->total_localtax1;
2618 $line->total_localtax2 = $objp->total_localtax2;
2619 $line->total_ttc = $objp->total_ttc;
2621 $line->fk_fournprice = $objp->fk_fournprice;
2622 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2623 $line->pa_ht = $marginInfos[0];
2624 $line->marge_tx = (
string) $marginInfos[1];
2625 $line->marque_tx = (
string) $marginInfos[2];
2626 $line->rang = $objp->rang;
2627 $line->special_code = $objp->special_code;
2628 $line->fk_parent_line = $objp->fk_parent_line;
2629 $line->situation_percent = $objp->situation_percent;
2630 $line->fk_prev_id = $objp->fk_prev_id;
2631 $line->fk_unit = $objp->fk_unit;
2633 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
2635 $line->batch = $objp->batch;
2636 $line->fk_warehouse = $objp->fk_warehouse;
2639 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2642 $line->fk_multicurrency = $objp->fk_multicurrency;
2643 $line->multicurrency_code = $objp->multicurrency_code;
2644 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2645 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2646 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2647 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2649 $line->array_options = array();
2650 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2651 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2652 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2653 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2656 if ($type !==
'separate') {
2657 $rawval = $objp->$key;
2660 if (in_array($type, array(
'date',
'datetime'))) {
2661 $line->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2662 } elseif ($type ==
'password') {
2663 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2664 $line->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2666 $line->array_options[
'options_' . $key] = $rawval;
2669 $line->array_options[
'options_' . $key] = $rawval;
2675 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2676 if (!empty($extrafields->attributes[$this->table_element_line][
'computed'][$key])) {
2677 if (empty(
$conf->disable_compute)) {
2678 global $objectoffield;
2679 $objectoffield = $line;
2680 $line->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element_line][
'computed'][$key], 1, 0,
'2');
2686 if (!$doFetchInOneSqlRequest) {
2688 $line->fetch_optionals();
2692 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2693 $tmpproduct =
new Product($this->db);
2694 $tmpproduct->fetch($objp->fk_product);
2695 $tmpproduct->getMultiLangs();
2697 $line->multilangs = $tmpproduct->multilangs;
2700 $this->lines[$i] = $line;
2704 $this->db->free($result);
2707 $this->error = $this->db->error();
2720 $this->tab_previous_situation_invoice = array();
2721 $this->tab_next_situation_invoice = array();
2723 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2724 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2725 $sql .=
' AND entity = '.((int) $this->entity);
2726 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2727 $sql .=
' ORDER BY situation_counter ASC';
2729 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2730 $result = $this->db->query($sql);
2731 if ($result && $this->db->num_rows($result) > 0) {
2732 while ($objp = $this->db->fetch_object($result)) {
2733 $invoice =
new Facture($this->db);
2734 if ($invoice->fetch($objp->rowid) > 0) {
2735 if ($objp->situation_counter < $this->situation_counter
2736 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2738 $this->tab_previous_situation_invoice[] = $invoice;
2740 $this->tab_next_situation_invoice[] = $invoice;
2761 if (empty($this->
type)) {
2764 if (isset($this->subtype)) {
2765 $this->subtype = (int) $this->subtype;
2767 if (isset($this->
ref)) {
2768 $this->
ref = trim($this->
ref);
2770 if (isset($this->ref_ext)) {
2771 $this->ref_ext = trim($this->ref_ext);
2773 if (!empty($this->ref_customer)) {
2774 $this->ref_customer = trim($this->ref_customer);
2776 if (isset($this->increment)) {
2777 $this->increment = trim($this->increment);
2779 if (isset($this->close_code)) {
2780 $this->close_code = trim($this->close_code);
2782 if (isset($this->close_note)) {
2783 $this->close_note = trim($this->close_note);
2785 if (isset($this->note) || isset($this->note_private)) {
2786 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2788 if (isset($this->note) || isset($this->note_private)) {
2789 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2791 if (isset($this->note_public)) {
2792 $this->note_public = trim($this->note_public);
2794 if (isset($this->model_pdf)) {
2795 $this->model_pdf = trim($this->model_pdf);
2797 if (isset($this->import_key)) {
2798 $this->import_key = trim($this->import_key);
2800 if (isset($this->retained_warranty)) {
2801 $this->retained_warranty = (float) $this->retained_warranty;
2803 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2804 $this->user_creation_id = $this->fk_user_author;
2806 if (!isset($this->user_modification_id) && !empty($user->id)) {
2807 $this->user_modification_id = $user->id;
2809 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2810 $this->user_validation_id = $this->fk_user_valid;
2815 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2816 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2817 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2818 $sql .=
" type=".(isset($this->
type) ? ((int) $this->
type) :
"null").
",";
2819 $sql .=
" subtype=".(isset($this->subtype) ? (int) $this->subtype :
"null").
",";
2820 $sql .=
" ref_client=".(!empty($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2821 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2822 $sql .=
" fk_soc=".(isset($this->socid) ? ((int) $this->socid) :
"null").
",";
2823 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2824 $sql .=
" datef=".(strval($this->
date) !=
'' ?
"'".$this->db->idate($this->
date).
"'" :
'null').
",";
2825 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2826 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2827 $sql .=
" paye=".(isset($this->paye) ? ((int) $this->paye) : 0).
",";
2828 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2829 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2830 $sql .=
" total_tva=".((float) $this->total_tva).
",";
2831 $sql .=
" localtax1=".((float) $this->total_localtax1).
",";
2832 $sql .=
" localtax2=".((float) $this->total_localtax2).
",";
2833 $sql .=
" total_ht=".((float) $this->total_ht).
",";
2834 $sql .=
" total_ttc=".((float) $this->total_ttc).
",";
2835 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2836 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2837 $sql .=
" fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) :
"null").
",";
2838 $sql .=
" fk_user_modif=".(!empty($user->id) ? ((int) $user->id) :
"null").
",";
2839 $sql .=
" fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id :
"null").
",";
2840 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2841 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2842 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2843 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2844 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2845 $sql .=
" note_private = ".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2846 $sql .=
" note_public = ".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2847 $sql .=
" model_pdf = ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2848 $sql .=
" import_key = ".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2849 $sql .=
" module_source = ".(isset($this->module_source) ?
"'".$this->db->escape($this->module_source).
"'" :
"null").
",";
2850 $sql .=
" pos_source = ".(isset($this->pos_source) ?
"'".$this->db->escape($this->pos_source).
"'" :
"null").
",";
2851 $sql .=
" pos_print_counter = ".(int) $this->pos_print_counter.
",";
2852 $sql .=
" situation_cycle_ref = ".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2853 $sql .=
" situation_counter = ".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2854 $sql .=
" situation_final = ".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2855 $sql .=
" retained_warranty = ".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2856 $sql .=
" retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2857 $sql .=
" retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2858 $sql .=
" WHERE rowid = ".((int) $this->
id);
2862 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2863 $resql = $this->db->query($sql);
2866 $this->errors[] =
"Error ".$this->db->lasterror();
2876 if (!$error && !$notrigger) {
2878 $result = $this->call_trigger(
'BILL_MODIFY', $user);
2887 foreach ($this->errors as $errmsg) {
2888 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2889 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2891 $this->db->rollback();
2894 $this->db->commit();
2912 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2913 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2918 $result = $remise->fetch($idremise);
2921 if ($this->socid > 0 && $remise->fk_soc != $this->socid) {
2922 $this->error = $langs->trans(
"ErrorDiscountNotSameCompany");
2923 $this->db->rollback();
2926 if ($remise->fk_facture) {
2927 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2928 $this->db->rollback();
2933 $facligne->fk_facture = $this->id;
2934 $facligne->fk_remise_except = $remise->id;
2935 $facligne->desc = $remise->description;
2936 $facligne->vat_src_code = $remise->vat_src_code;
2937 $facligne->tva_tx = $remise->tva_tx;
2938 $facligne->localtax1_tx = $remise->localtax1_tx;
2939 $facligne->localtax1_type = (int) $remise->localtax1_type;
2940 $facligne->localtax2_tx = $remise->localtax2_tx;
2941 $facligne->localtax2_type = (int) $remise->localtax2_type;
2942 $facligne->subprice = -(float) $remise->total_ht;
2943 $facligne->fk_product = 0;
2945 $facligne->remise_percent = 0;
2946 $facligne->rang = -1;
2947 $facligne->info_bits = 2;
2950 $facligne->rang = 1;
2951 $linecount = count($this->lines);
2952 for ($ii = 1; $ii <= $linecount; $ii++) {
2958 if ($remise->fk_facture_source > 0) {
2959 $srcinvoice =
new Facture($this->db);
2960 $srcinvoice->fetch($remise->fk_facture_source);
2961 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2963 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2964 $facligne->pa_ht = $arraytmp[
'pa_total'];
2967 $facligne->total_ht = -(float) $remise->total_ht;
2968 $facligne->total_tva = -(float) $remise->total_tva;
2969 $facligne->total_ttc = -(float) $remise->total_ttc;
2970 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
2971 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
2973 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2974 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
2975 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
2976 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
2978 $lineid = $facligne->insert();
2983 $result = $remise->link_to_invoice($lineid, 0);
2985 $this->error = $remise->error;
2986 $this->db->rollback();
2990 $this->db->commit();
2993 $this->error = $facligne->error;
2994 $this->db->rollback();
2998 $this->error = $facligne->error;
2999 $this->db->rollback();
3003 $this->db->rollback();
3025 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3026 if (empty($ref_client)) {
3027 $sql .=
" SET ref_client = NULL";
3029 $sql .=
" SET ref_client = '".$this->db->escape($ref_client).
"'";
3031 $sql .=
" WHERE rowid = ".((int) $this->
id);
3033 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
3034 $resql = $this->db->query($sql);
3036 $this->errors[] = $this->db->error();
3041 $this->ref_client = $ref_client;
3042 $this->ref_customer = $ref_client;
3045 if (!$notrigger && empty($error)) {
3047 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3055 $this->ref_client = $ref_client;
3056 $this->ref_customer = $ref_client;
3058 $this->db->commit();
3061 foreach ($this->errors as $errmsg) {
3062 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
3063 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
3065 $this->db->rollback();
3085 dol_syslog(__METHOD__.
' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3086 if ($this->
status >= self::STATUS_DRAFT) {
3088 $this->demand_reason_id = $inputReasonId;
3092 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3093 $sql .=
" SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId :
'null');
3094 $sql .=
" WHERE rowid = ".((int) $this->
id);
3097 $res = $this->db->query($sql);
3100 $this->error = $this->db->lasterror();
3101 $this->errors[] = $this->error;
3107 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3116 $this->db->commit();
3118 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3119 $this->db->rollback();
3120 dol_syslog(__METHOD__.
' Error : '.$this->errorsToString(), LOG_ERR);
3141 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3143 global $langs,
$conf;
3144 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3148 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
3161 if (!$error && !$notrigger) {
3163 $result = $this->call_trigger(
'BILL_DELETE', $user);
3172 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"categorie_invoice";
3173 $sql .=
" WHERE fk_invoice = ".((int) $this->
id);
3175 $result = $this->db->query($sql);
3178 $this->errors[] = $this->db->lasterror();
3187 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
3201 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
3202 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
3203 $sql .=
' AND fk_facture_line IS NULL';
3204 $resql = $this->db->query($sql);
3208 $list_rowid_det = array();
3209 foreach ($this->lines as $key => $invoiceline) {
3210 $list_rowid_det[] = $invoiceline->id;
3214 if (count($list_rowid_det)) {
3215 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3216 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
3217 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
3219 if (!$this->db->query($sql)) {
3220 $this->error = $this->db->error().
" sql=".$sql;
3221 $this->errors[] = $this->error;
3222 $this->db->rollback();
3229 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
3230 $sql .=
' SET fk_invoice = NULL';
3231 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
3233 if (!$this->db->query($sql)) {
3234 $this->error = $this->db->error().
" sql=".$sql;
3235 $this->errors[] = $this->error;
3236 $this->db->rollback();
3240 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
3241 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
3242 $sql .=
' WHERE invoice_id = '.((int) $rowid);
3244 if (!$this->db->query($sql)) {
3245 $this->error = $this->db->error().
" sql=".$sql;
3246 $this->errors[] = $this->error;
3247 $this->db->rollback();
3253 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3254 $langs->load(
"agenda");
3256 $num = count($this->lines);
3257 for ($i = 0; $i < $num; $i++) {
3258 if ($this->lines[$i]->fk_product > 0) {
3260 $mouvP->origin = &$this;
3261 $mouvP->setOrigin($this->element, $this->
id);
3263 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3264 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3266 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3273 $sql_main_table = MAIN_DB_PREFIX.
'facturedet';
3274 $sql_ef_table = $sql_main_table.
"_extrafields";
3275 $sqlef =
"DELETE FROM ".$sql_ef_table.
" WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table.
" WHERE fk_facture = ".((int) $rowid).
")";
3277 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
3280 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
3282 $resql = $this->db->query($sql);
3290 if ($conf->facture->dir_output && !empty($this->
ref)) {
3291 $dir =
$conf->facture->dir_output.
"/".$ref;
3292 $file =
$conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
3293 if (file_exists($file)) {
3297 $langs->load(
"errors");
3298 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
3299 $this->errors[] = $this->error;
3300 $this->db->rollback();
3304 if (file_exists($dir)) {
3306 $langs->load(
"errors");
3307 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
3308 $this->errors[] = $this->error;
3309 $this->db->rollback();
3315 $this->db->commit();
3318 $this->error = $this->db->lasterror().
" sql=".$sql;
3319 $this->errors[] = $this->error;
3320 $this->db->rollback();
3324 $this->error = $this->db->lasterror().
" sql=".$sql;
3325 $this->errors[] = $this->error;
3326 $this->db->rollback();
3330 $this->db->rollback();
3347 public function set_paid($user, $close_code =
'', $close_note =
'')
3350 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3351 return $this->
setPaid($user, $close_code, $close_note);
3364 public function setPaid($user, $close_code =
'', $close_note =
'')
3368 if ($this->paye != 1 || $this->
status != self::STATUS_CLOSED) {
3373 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3375 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3376 $sql .=
' fk_statut = '.self::STATUS_CLOSED;
3378 $sql .=
', paye = 1';
3381 $sql .=
", close_code = '".$this->db->escape($close_code).
"'";
3384 $sql .=
", close_note = '".$this->db->escape($close_note).
"'";
3386 $sql .=
', fk_user_closing = '.((int) $user->id);
3387 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3388 $sql .=
" WHERE rowid = ".((int) $this->
id);
3390 $resql = $this->db->query($sql);
3393 $result = $this->call_trigger(
'BILL_PAYED', $user);
3400 $this->error = $this->db->lasterror();
3406 $this->db->commit();
3409 $this->db->rollback();
3432 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3450 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3451 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3452 $sql .=
' date_closing=null,';
3453 $sql .=
' fk_user_closing=null';
3454 $sql .=
" WHERE rowid = ".((int) $this->
id);
3456 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3457 $resql = $this->db->query($sql);
3460 $result = $this->call_trigger(
'BILL_UNPAYED', $user);
3467 $this->error = $this->db->error();
3472 $this->db->commit();
3475 $this->db->rollback();
3497 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3498 return $this->
setCanceled($user, $close_code, $close_note);
3511 public function setCanceled($user, $close_code =
'', $close_note =
'')
3513 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3518 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3519 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3521 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3524 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3526 $sql .=
', fk_user_closing = '.((int) $user->id);
3527 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3528 $sql .=
" WHERE rowid = ".((int) $this->
id);
3530 $resql = $this->db->query($sql);
3534 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3535 $sql .=
' SET fk_facture = NULL';
3536 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3538 $resql = $this->db->query($sql);
3541 $result = $this->call_trigger(
'BILL_CANCEL', $user);
3543 $this->db->rollback();
3548 $this->db->commit();
3551 $this->error = $this->db->error().
" sql=".$sql;
3552 $this->db->rollback();
3556 $this->error = $this->db->error().
" sql=".$sql;
3557 $this->db->rollback();
3574 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3577 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3579 $productStatic =
null;
3580 $warehouseStatic =
null;
3581 $productbatch =
null;
3582 if ($batch_rule > 0) {
3583 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3584 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3585 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3586 $productStatic =
new Product($this->db);
3587 $warehouseStatic =
new Entrepot($this->db);
3594 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3601 if ($this->
status != self::STATUS_DRAFT) {
3602 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3605 if (count($this->lines) <= 0) {
3606 $langs->load(
"errors");
3607 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3611 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3612 $this->error =
'Permission denied';
3613 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3616 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3624 if (!$last_of_type[0]) {
3631 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3632 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'TVA_INTRA',
'ACCOUNTANCY_CODE_CUSTOMER');
3633 foreach ($array_to_check as $key) {
3634 $keymin = strtolower($key);
3635 if (!property_exists($this->thirdparty, $keymin)) {
3638 $vallabel = $this->thirdparty->$keymin;
3640 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3642 if ($this->thirdparty->isACompany()) {
3644 if (
$mysoc->country_id > 0 && $this->thirdparty->country_id ==
$mysoc->country_id) {
3645 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3647 $langs->load(
"errors");
3648 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3649 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3655 if ($key ==
'EMAIL') {
3658 $langs->load(
"errors");
3659 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3660 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3664 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3666 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3667 $langs->load(
"errors");
3668 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3669 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3673 if ($key ==
'TVA_INTRA') {
3676 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3677 $langs->load(
"errors");
3678 $this->error = $langs->trans(
'ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3679 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3682 } elseif (
getDolGlobalString(
'SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3683 $langs->load(
"errors");
3684 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3685 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3694 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3695 foreach ($array_to_check as $key => $val) {
3696 $keymin = strtolower($key);
3697 $vallabel = $this->$keymin;
3700 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3702 $langs->load(
"errors");
3704 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3711 if ($this->
type == self::TYPE_REPLACEMENT) {
3713 if ($this->fk_facture_source <= 0) {
3714 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3715 $this->db->rollback();
3720 $facreplaced =
new Facture($this->db);
3721 $result = $facreplaced->fetch($this->fk_facture_source);
3723 $this->error = $langs->trans(
"ErrorBadInvoice");
3724 $this->db->rollback();
3729 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3730 if ($idreplacement && $idreplacement != $this->
id) {
3731 $facreplacement =
new Facture($this->db);
3732 $facreplacement->fetch($idreplacement);
3733 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3734 $this->db->rollback();
3738 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3740 $this->error = $facreplaced->error;
3741 $this->db->rollback();
3747 if ($force_number) {
3748 $num = $force_number;
3749 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3762 $this->oldref = $this->ref;
3770 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3771 $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).
"'";
3773 $sql .=
", datef='".$this->db->idate($this->
date).
"'";
3774 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3776 $sql .=
" WHERE rowid = ".((int) $this->
id);
3778 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3779 $resql = $this->db->query($sql);
3781 $this->error = $this->db->lasterror();
3788 $result = $this->thirdparty->setAsCustomer();
3792 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3793 $langs->load(
"agenda");
3796 $cpt = count($this->lines);
3797 for ($i = 0; $i < $cpt; $i++) {
3798 if ($this->lines[$i]->fk_product > 0) {
3800 $mouvP->origin = &$this;
3801 $mouvP->setOrigin($this->element, $this->
id);
3804 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3807 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3816 $is_batch_line =
false;
3817 if ($batch_rule > 0) {
3818 $productStatic->fetch($this->lines[$i]->fk_product);
3819 if ($productStatic->hasbatch() && is_object($productbatch)) {
3820 $is_batch_line =
true;
3821 $product_qty_remain = $this->lines[$i]->qty;
3827 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3828 $sortorder =
'ASC,ASC,ASC,ASC';
3831 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 :
null), $sortfield, $sortorder);
3832 if (!is_array($resBatchList)) {
3834 $this->error = $this->db->lasterror();
3838 $batchList = $resBatchList;
3839 if (empty($batchList)) {
3841 $langs->load(
'errors');
3842 $warehouseStatic->fetch($idwarehouse);
3843 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3844 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3847 foreach ($batchList as $batch) {
3848 if ($batch->qty <= 0) {
3853 if ($batch->qty >= $product_qty_remain) {
3854 $product_batch_qty = $product_qty_remain;
3857 $product_batch_qty = $batch->qty;
3859 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3866 $product_qty_remain -= $product_batch_qty;
3868 if ($product_qty_remain <= 0) {
3873 if (!$error && $product_qty_remain > 0) {
3876 $langs->load(
'errors');
3877 $warehouseStatic->fetch($idwarehouse);
3878 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3879 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3882 $batch = $batchList[0];
3883 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3894 if (!$is_batch_line) {
3895 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3910 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3911 $invoice_situation =
new Facture($this->db);
3912 $result = $invoice_situation->fetch($this->fk_facture_source);
3913 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3914 $invoice_situation->situation_final = 0;
3916 $result = $invoice_situation->setFinal($user, 1);
3919 $this->error = $invoice_situation->error;
3920 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3926 if (!$error && !$notrigger) {
3928 $result = $this->call_trigger(
'BILL_VALIDATE', $user);
3937 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3939 $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).
"'";
3940 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3941 $resql = $this->db->query($sql);
3944 $this->error = $this->db->lasterror();
3946 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3947 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3948 $resql = $this->db->query($sql);
3951 $this->error = $this->db->lasterror();
3958 if (!$resupdatenext) {
3968 $this->date_validation = $now;
3973 $nboflines = count($this->lines);
3974 while (($i < $nboflines) && $final) {
3975 $line = $this->lines[$i];
3976 '@phan-var-force FactureLigne $line';
3978 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3979 $current_progress = (float) $line->situation_percent;
3980 $full_progress = $previousprogress + $current_progress;
3981 $final = ($full_progress == 100);
3983 $final = ($line->situation_percent == 100);
3989 if ($this->situation_final) {
3991 $this->situation_final = 0;
3995 if (!$this->situation_final) {
3997 $this->situation_final = 1;
4007 if (!$error && preg_match(
'/^[\(]?PROV/i', $this->oldref)) {
4011 $dirsource =
$conf->facture->dir_output.
'/'.$oldref;
4012 $dirdest =
$conf->facture->dir_output.
'/'.$newref;
4013 if (!$error && file_exists($dirsource)) {
4014 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
4016 if (@rename($dirsource, $dirdest)) {
4019 $listoffiles =
dol_dir_list(
$conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
4020 foreach ($listoffiles as $fileentry) {
4021 $dirsource = $fileentry[
'name'];
4022 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
4023 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
4024 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
4025 @rename($dirsource, $dirdest);
4032 $this->db->commit();
4035 $this->db->rollback();
4048 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4049 $is_last = $next_invoice->is_last_in_cycle();
4051 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4052 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4056 foreach ($next_invoice->lines as $line) {
4057 '@phan-var-force FactureLigne $line';
4058 $result = $next_invoice->updateline(
4063 $line->remise_percent,
4067 $line->localtax1_tx,
4068 $line->localtax2_tx,
4071 $line->product_type,
4072 $line->fk_parent_line,
4074 $line->fk_fournprice,
4077 $line->special_code,
4078 $line->array_options,
4079 $line->situation_percent,
4084 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4109 if ($this->
status == self::STATUS_DRAFT) {
4110 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
4118 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4119 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
4120 $sql .=
" WHERE rowid = ".((int) $this->
id);
4122 $result = $this->db->query($sql);
4125 $this->oldcopy = clone $this;
4130 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
4131 $langs->load(
"agenda");
4133 $num = count($this->lines);
4134 for ($i = 0; $i < $num; $i++) {
4135 if ($this->lines[$i]->fk_product > 0) {
4137 $mouvP->origin = &$this;
4138 $mouvP->setOrigin($this->element, $this->
id);
4140 if ($this->
type == self::TYPE_CREDIT_NOTE) {
4141 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv(
"InvoiceBackToDraftInDolibarr", $this->ref));
4143 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv(
"InvoiceBackToDraftInDolibarr", $this->ref));
4148 dol_syslog(__METHOD__.
" stock movement failed for line ".$i.
": ".$mouvP->error, LOG_ERR);
4155 $old_statut = $this->status;
4160 $result = $this->call_trigger(
'BILL_UNVALIDATE', $user);
4163 $this->statut = $old_statut;
4164 $this->
status = $old_statut;
4168 $this->db->rollback();
4173 $this->db->commit();
4176 $this->db->rollback();
4180 $this->error = $this->db->error();
4181 $this->db->rollback();
4235 $remise_percent = 0,
4238 $fk_code_ventilation = 0,
4240 $fk_remise_except = 0,
4241 $price_base_type =
'HT',
4248 $fk_parent_line = 0,
4249 $fk_fournprice =
null,
4252 $array_options = array(),
4253 $situation_percent = 100,
4258 $noupdateafterinsertline = 0
4262 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4268 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);
4270 if ($this->
status == self::STATUS_DRAFT) {
4271 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4274 if (empty($remise_percent)) {
4275 $remise_percent = 0;
4280 if (empty($info_bits)) {
4286 if (empty($fk_code_ventilation)) {
4287 $fk_code_ventilation = 0;
4289 if (empty($txtva)) {
4292 if (empty($txlocaltax1)) {
4295 if (empty($txlocaltax2)) {
4298 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4299 $fk_parent_line = 0;
4301 if (empty($fk_prev_id)) {
4302 $fk_prev_id =
'null';
4305 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4308 $situation_percent = 0;
4310 $situation_percent = 100;
4314 if (empty($ref_ext)) {
4318 $remise_percent = (float)
price2num($remise_percent);
4322 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4325 if (strpos((
string) $txtva,
'*') !==
false) {
4328 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4331 $txlocaltax1 = (float)
price2num($txlocaltax1);
4332 $txlocaltax2 = (float)
price2num($txlocaltax2);
4334 if ($price_base_type ==
'HT') {
4346 $langs->load(
"errors");
4347 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4353 $product_type = $type;
4354 if (!empty($fk_product) && $fk_product > 0) {
4355 $product =
new Product($this->db);
4356 $result = $product->fetch($fk_product);
4357 $product_type = $product->type;
4359 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4361 $productChildrenNb = 0;
4363 $productChildrenNb = $product->hasFatherOrChild(1);
4365 if ($productChildrenNb > 0) {
4367 $product_stock =
null;
4368 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4369 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4370 if ($product_stock ===
null) {
4371 $product_stock = $componentStockWarehouse->real;
4373 $product_stock = min($product_stock, $componentStockWarehouse->real);
4376 if ($product_stock ===
null) {
4380 $product_stock = $product->stock_reel;
4383 if ($product_stock < $qty) {
4384 $langs->load(
"errors");
4385 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4386 $this->db->rollback();
4392 $tmpproduct =
new Product($this->db);
4393 $result = $tmpproduct->fetch($fk_product);
4395 if ($newqty != $qty) {
4397 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4407 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4408 $vat_src_code = $reg[1];
4409 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4416 $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);
4418 $total_ht = $tabprice[0];
4419 $total_tva = $tabprice[1];
4420 $total_ttc = $tabprice[2];
4421 $total_localtax1 = $tabprice[9];
4422 $total_localtax2 = $tabprice[10];
4423 $pu_ht = $tabprice[3];
4426 $multicurrency_total_ht = $tabprice[16];
4427 $multicurrency_total_tva = $tabprice[17];
4428 $multicurrency_total_ttc = $tabprice[18];
4429 $pu_ht_devise = $tabprice[19];
4433 if (empty($ranktouse) || $ranktouse == -1) {
4434 $rangmax = $this->
line_max($fk_parent_line);
4435 $ranktouse = $rangmax + 1;
4440 $apply_abs_price_on_credit_note =
false;
4442 $apply_abs_price_on_credit_note =
true;
4448 $this->line->context = $this->context;
4450 $this->line->fk_facture = $this->id;
4451 $this->line->label = $label;
4452 $this->line->desc = $desc;
4453 $this->line->ref_ext = $ref_ext;
4455 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : (float) $qty);
4456 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4458 $this->line->vat_src_code = $vat_src_code;
4459 $this->line->tva_tx = $txtva;
4460 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4461 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4462 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4463 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4465 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4466 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4467 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4468 $this->line->total_localtax1 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax1) : (float) $total_localtax1);
4469 $this->line->total_localtax2 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax2) : (float) $total_localtax2);
4471 $this->line->fk_product = $fk_product;
4472 $this->line->product_type = $product_type;
4473 $this->line->remise_percent = $remise_percent;
4475 $this->line->date_end = $date_end;
4476 $this->line->fk_code_ventilation = $fk_code_ventilation;
4477 $this->line->rang = $ranktouse;
4478 $this->line->info_bits = $info_bits;
4479 $this->line->fk_remise_except = $fk_remise_except;
4481 $this->line->special_code = $special_code;
4482 $this->line->fk_parent_line = $fk_parent_line;
4484 $this->line->origin = $origin;
4485 $this->line->origin_id = $origin_id;
4487 $this->line->situation_percent = $situation_percent;
4488 $this->line->fk_prev_id = $fk_prev_id;
4489 $this->line->fk_unit = $fk_unit;
4492 $this->line->fk_fournprice = $fk_fournprice;
4493 $this->line->pa_ht = $pa_ht;
4496 $this->line->fk_multicurrency = $this->fk_multicurrency;
4497 $this->line->multicurrency_code = $this->multicurrency_code;
4498 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4500 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4501 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4502 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4504 if (is_array($array_options) && count($array_options) > 0) {
4505 $this->line->array_options = $array_options;
4508 $result = $this->line->insert();
4511 if (empty($noupdateafterinsertline)) {
4515 if (!isset($this->context[
'createfromclone'])) {
4516 if (!empty($fk_parent_line)) {
4519 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4521 $linecount = count($this->lines);
4522 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4527 $this->lines[] = $this->line;
4530 foreach ($this->lines as $tmpline) {
4531 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
4532 $this->line->extraparams = $tmpline->extraparams;
4533 $this->line->setExtraParameters();
4539 $this->db->commit();
4540 return $this->line->id;
4542 $this->error = $this->db->lasterror();
4543 $this->db->rollback();
4547 $this->error = $this->line->error;
4548 $this->errors = $this->line->errors;
4549 $this->db->rollback();
4553 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4554 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4590 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)
4595 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4601 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4604 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4608 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);
4610 if ($this->
status == self::STATUS_DRAFT) {
4613 if (!$this->error) {
4614 $this->error = $langs->trans(
'invoiceLineProgressError');
4621 $langs->load(
"errors");
4622 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4632 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4633 $fk_parent_line = 0;
4635 if (empty($special_code) || $special_code == 3) {
4638 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
4641 $situation_percent = 0;
4643 $situation_percent = 100;
4646 if (empty($ref_ext)) {
4650 $remise_percent = (float)
price2num($remise_percent);
4654 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4657 if (strpos((
string) $txtva,
'*') !==
false) {
4660 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4663 $txlocaltax1 = (float)
price2num($txlocaltax1);
4664 $txlocaltax2 = (float)
price2num($txlocaltax2);
4680 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4681 $vat_src_code = $reg[1];
4682 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4689 if ($tmpline->fetch($rowid) > 0) {
4691 if ($newqty != $qty) {
4693 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4698 $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);
4700 $total_ht = $tabprice[0];
4701 $total_tva = $tabprice[1];
4702 $total_ttc = $tabprice[2];
4703 $total_localtax1 = $tabprice[9];
4704 $total_localtax2 = $tabprice[10];
4705 $pu_ht = $tabprice[3];
4706 $pu_tva = $tabprice[4];
4707 $pu_ttc = $tabprice[5];
4710 $multicurrency_total_ht = $tabprice[16];
4711 $multicurrency_total_tva = $tabprice[17];
4712 $multicurrency_total_ttc = $tabprice[18];
4713 $pu_ht_devise = $tabprice[19];
4718 if ($remise_percent > 0) {
4719 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4720 $price = ((float) $pu - $remise);
4726 $line->fetch($rowid);
4727 $line->fetch_optionals();
4729 if (!empty($line->fk_product)) {
4730 $product =
new Product($this->db);
4731 $result = $product->fetch($line->fk_product);
4732 $product_type = $product->type;
4734 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4736 $productChildrenNb = 0;
4738 $productChildrenNb = $product->hasFatherOrChild(1);
4740 if ($productChildrenNb > 0) {
4742 $product_stock =
null;
4743 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4744 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4745 if ($product_stock ===
null) {
4746 $product_stock = $componentStockWarehouse->real;
4748 $product_stock = min($product_stock, $componentStockWarehouse->real);
4751 if ($product_stock ===
null) {
4755 $product_stock = $product->stock_reel;
4758 if ($product_stock < $qty) {
4759 $langs->load(
"errors");
4760 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', (
string) $product->ref);
4761 $this->db->rollback();
4767 $staticline = clone $line;
4769 $line->oldline = $staticline;
4770 $this->line = $line;
4771 $this->line->context = $this->context;
4772 $this->line->rang = $rang;
4775 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4776 $rangmax = $this->
line_max($fk_parent_line);
4777 $this->line->rang = $rangmax + 1;
4779 $apply_abs_price_on_credit_note =
false;
4781 $apply_abs_price_on_credit_note =
true;
4786 $this->line->id = $rowid;
4787 $this->line->rowid = $rowid;
4788 $this->line->label = $label;
4789 $this->line->desc = $desc;
4790 $this->line->ref_ext = $ref_ext;
4791 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4793 $this->line->vat_src_code = $vat_src_code;
4794 $this->line->tva_tx = $txtva;
4795 $this->line->localtax1_tx = $txlocaltax1;
4796 $this->line->localtax2_tx = $txlocaltax2;
4797 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4798 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4800 $this->line->remise_percent = $remise_percent;
4801 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4803 $this->line->date_end = $date_end;
4804 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4805 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4806 $this->line->total_localtax1 = (float) $total_localtax1;
4807 $this->line->total_localtax2 = (float) $total_localtax2;
4808 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4809 $this->line->info_bits = $info_bits;
4810 $this->line->special_code = $special_code;
4811 $this->line->product_type = $type;
4812 $this->line->fk_parent_line = $fk_parent_line;
4813 $this->line->skip_update_total = $skip_update_total;
4814 $this->line->situation_percent = $situation_percent;
4815 $this->line->fk_unit = $fk_unit;
4817 $this->line->fk_fournprice = $fk_fournprice;
4818 $this->line->pa_ht = $pa_ht;
4821 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4822 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4823 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4824 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4826 if (is_array($array_options) && count($array_options) > 0) {
4828 foreach ($array_options as $key => $value) {
4829 $this->line->array_options[$key] = $array_options[$key];
4833 $result = $this->line->update($user, $notrigger);
4836 if (!empty($fk_parent_line)) {
4842 $this->db->commit();
4845 $this->error = $this->line->error;
4846 $this->db->rollback();
4850 $this->error =
"Invoice statut makes operation forbidden";
4864 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4865 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4866 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4868 $result = $this->db->query($sql);
4870 $this->error = $this->db->error();
4874 $obj = $this->db->fetch_object($result);
4876 if ($obj ===
null) {
4879 return ($situation_percent < $obj->situation_percent);
4898 if (($line->info_bits & 2) == 2) {
4902 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4905 if ($percent > 100) {
4909 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4910 $current_progress = $percent - $previous_progress;
4911 $line->situation_percent = $current_progress;
4912 $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);
4914 $line->situation_percent = $percent;
4915 $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);
4917 $line->total_ht = (float) $tabprice[0];
4918 $line->total_tva = (float) $tabprice[1];
4919 $line->total_ttc = (float) $tabprice[2];
4920 $line->total_localtax1 = (float) $tabprice[9];
4921 $line->total_localtax2 = (float) $tabprice[10];
4922 $line->multicurrency_total_ht = (float) $tabprice[16];
4923 $line->multicurrency_total_tva = (float) $tabprice[17];
4924 $line->multicurrency_total_ttc = (float) $tabprice[18];
4925 $line->update($user);
4928 if ($update_price) {
4944 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4946 if ($this->
status != self::STATUS_DRAFT) {
4947 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4953 $line->context = $this->context;
4956 $result = $line->fetch($rowid);
4957 if (!($result > 0)) {
4965 if ($id > 0 && (
int) $line->fk_facture !== (
int) $id) {
4966 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4973 $staticline = clone $line;
4974 $line->oldline = $staticline;
4976 if ($line->delete($user) > 0) {
4980 $this->db->commit();
4983 $this->db->rollback();
4984 $this->error = $this->db->lasterror();
4988 $this->db->rollback();
4989 $this->error = $line->error;
5008 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
5010 return $this->
setDiscount($user, $remise, $notrigger);
5024 if (empty($remise)) {
5028 if ($user->hasRight(
'facture',
'creer')) {
5029 $remise = (float)
price2num($remise, 2);
5035 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
5036 $sql .=
" SET remise_percent = ".((float) $remise);
5037 $sql .=
" WHERE rowid = ".((int) $this->
id);
5038 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
5041 $resql = $this->db->query($sql);
5043 $this->errors[] = $this->db->error();
5047 if (!$notrigger && empty($error)) {
5049 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5057 $this->remise_percent = $remise;
5060 $this->db->commit();
5063 foreach ($this->errors as $errmsg) {
5064 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5065 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5067 $this->db->rollback();
5088 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
5089 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5102 global
$conf, $langs;
5104 if ($this->module_source ==
'takepos') {
5105 $langs->load(
'cashdesk');
5107 $moduleName =
'takepos';
5108 $moduleSourceName =
'Takepos';
5109 $addonConstName =
'TAKEPOS_REF_ADDON';
5113 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
5118 $langs->load(
'bills');
5120 $moduleName =
'facture';
5121 $moduleSourceName =
'Invoice';
5122 $addonConstName =
'FACTURE_ADDON';
5126 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5128 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5130 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
5136 if (!empty($addon)) {
5137 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
5141 $file = $addon.
'.php';
5142 $classname = $addon;
5146 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
5147 foreach ($dirmodels as $reldir) {
5148 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
5151 if (is_file($dir.$file) && is_readable($dir.$file)) {
5152 $mybool = ((bool) include_once $dir.$file) || $mybool;
5158 $file = $addon.
'/'.$addon.
'.modules.php';
5159 $classname =
'mod_'.$moduleName.
'_'.$addon;
5160 $classname = preg_replace(
'/\-.*$/',
'', $classname);
5162 foreach (
$conf->file->dol_document_root as $dirroot) {
5163 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
5166 if (is_file($dir.$file) && is_readable($dir.$file)) {
5167 $mybool = (include_once $dir.$file) || $mybool;
5177 $obj =
new $classname();
5178 '@phan-var-force ModeleNumRefFactures $obj';
5180 $numref = $obj->getNextValue($soc, $this, $mode);
5187 if ($mode !=
'last' && !$numref) {
5188 $this->error = $obj->error;
5194 $langs->load(
'errors');
5195 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5208 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5209 $sql .=
' date_closing as dateclosing,';
5210 $sql .=
' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5211 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
5212 $sql .=
' WHERE c.rowid = '.((int) $id);
5214 $result = $this->db->query($sql);
5216 if ($this->db->num_rows($result)) {
5217 $obj = $this->db->fetch_object($result);
5219 $this->
id = $obj->rowid;
5220 $this->user_creation_id = $obj->fk_user_author;
5221 $this->user_modification_id = $obj->fk_user_modif;
5222 $this->user_validation_id = $obj->fk_user_valid;
5223 $this->user_closing_id = $obj->fk_user_closing;
5225 $this->date_creation = $this->db->jdate($obj->datec);
5226 $this->date_modification = $this->db->jdate($obj->datem);
5227 $this->date_validation = $this->db->jdate($obj->datev);
5228 $this->date_closing = $this->db->jdate($obj->dateclosing);
5230 $this->db->free($result);
5251 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
5258 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
5259 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
5260 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
5261 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5262 $sql .=
" AND f.fk_soc = s.rowid";
5264 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
5266 if (is_object($excluser)) {
5267 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
5271 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5272 $search_sale = $user->id;
5275 if ($search_sale && $search_sale !=
'-1') {
5276 if ($search_sale == -2) {
5277 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5278 } elseif ($search_sale > 0) {
5279 $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).
")";
5284 $sql .=
" AND f.fk_soc = ".((int) $socid);
5286 $sql .= $this->db->order($sortfield, $sortorder);
5287 $sql .= $this->db->plimit($limit, $offset);
5289 $result = $this->db->query($sql);
5291 $numc = $this->db->num_rows($result);
5294 while ($i < $numc) {
5295 $obj = $this->db->fetch_object($result);
5297 if ($shortlist == 1) {
5298 $ga[$obj->fid] = $obj->ref;
5299 } elseif ($shortlist == 2) {
5300 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
5302 $ga[$i][
'id'] = $obj->fid;
5303 $ga[$i][
'ref'] = $obj->ref;
5304 $ga[$i][
'name'] = $obj->name;
5333 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5334 $sql .=
" ff.rowid as rowidnext";
5336 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5337 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5338 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
5339 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
5340 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5341 $sql .=
" AND f.paye = 0";
5342 $sql .=
" AND pf.fk_paiement IS NULL";
5343 $sql .=
" AND ff.fk_statut IS NULL";
5345 $sql .=
" AND f.fk_soc = ".((int) $socid);
5348 $sql .=
" ORDER BY f.ref";
5350 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
5351 $resql = $this->db->query($sql);
5353 while ($obj = $this->db->fetch_object($resql)) {
5354 $return[$obj->rowid] = array(
5355 'id' => $obj->rowid,
5357 'status' => $obj->status,
5358 'paid' => $obj->paid,
5365 $this->error = $this->db->error();
5389 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
5390 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5391 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5392 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
5393 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5394 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5398 $sql .=
" AND ff.type IS NULL";
5399 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
5403 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
5404 $sql .=
'(SELECT MAX(fs.rowid)';
5405 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
5406 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
5407 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
5408 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5410 $sql .=
" AND fs.fk_soc = ".((int) $socid);
5412 $sql .=
" GROUP BY fs.situation_cycle_ref)";
5415 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
5419 $sql .=
" AND f.fk_soc = ".((int) $socid);
5422 if (
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5423 $sql .=
" ORDER BY CASE WHEN f.rowid = ".((int)
GETPOST(
'fac_avoir')).
" THEN 0 ELSE 1 END, f.ref";
5425 $sql .= $this->db->plimit(
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5427 $sql .=
" ORDER BY f.ref";
5430 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
5431 $resql = $this->db->query($sql);
5433 while ($obj = $this->db->fetch_object($resql)) {
5435 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5438 if ($obj->fk_statut == self::STATUS_CLOSED) {
5443 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5444 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
5450 $this->error = $this->db->error();
5466 global
$conf, $langs;
5468 $sanitizedclause =
" WHERE";
5470 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5471 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5472 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5473 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5474 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5475 $sanitizedclause =
" AND";
5477 $sql .= $sanitizedclause.
" f.paye=0";
5478 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5479 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5481 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5484 $resql = $this->db->query($sql);
5486 $langs->load(
"bills");
5489 $response->warning_delay =
getWarningDelay(
'invoice',
'client') / 60 / 60 / 24;
5490 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5491 $response->labelShort = $langs->trans(
"Unpaid");
5492 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5495 $generic_facture =
new Facture($this->db);
5497 while ($obj = $this->db->fetch_object($resql)) {
5498 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5499 $generic_facture->statut = $obj->status;
5500 $generic_facture->status = $obj->status;
5502 $response->nbtodo++;
5503 $response->total += $obj->total_ht;
5505 if ($generic_facture->hasDelay()) {
5506 $response->nbtodolate++;
5507 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5511 $this->db->free($resql);
5515 $this->error = $this->db->error();
5554 global
$conf, $langs, $user;
5558 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5563 $sql =
"SELECT rowid";
5564 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5565 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5566 $sql .= $this->db->plimit(100);
5568 $resql = $this->db->query($sql);
5570 $num_prods = $this->db->num_rows($resql);
5572 while ($i < $num_prods) {
5574 $row = $this->db->fetch_row($resql);
5575 $prodids[$i] = $row[0];
5579 if (empty($num_prods)) {
5581 $prodids[$num_prods] = 1;
5586 $this->entity =
$conf->entity;
5587 $this->
ref =
'SPECIMEN';
5588 $this->specimen = 1;
5590 $this->
date = $nownotime;
5591 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5592 $this->cond_reglement_id = 1;
5593 $this->cond_reglement_code =
'RECEP';
5595 $this->mode_reglement_id = 0;
5596 $this->mode_reglement_code =
'';
5598 $this->note_public =
'This is a comment (public)';
5599 $this->note_private =
'This is a comment (private)';
5601 $this->user_creation_id = $user->id;
5603 $this->multicurrency_tx = 1;
5604 $this->multicurrency_code =
$conf->currency;
5606 $this->fk_incoterms = 0;
5607 $this->location_incoterms =
'';
5609 $this->pos_print_counter = 0;
5610 $this->email_sent_counter = 0;
5614 if (empty($option) || $option !=
'nolines') {
5618 while ($xnbp < $nbp) {
5620 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5622 $line->subprice = 100;
5623 $line->tva_tx = 19.6;
5624 $line->localtax1_tx = 0;
5625 $line->localtax2_tx = 0;
5626 $line->remise_percent = 0;
5627 if ($xnbp == 1 && $option !=
'takepos' && $option !=
'nonegativeup') {
5628 $prodid = mt_rand(1, $num_prods);
5629 if (isset($prodids[$prodid])) {
5630 $line->fk_product = $prodids[$prodid];
5633 $line->total_ht = -100;
5634 $line->total_ttc = -119.6;
5635 $line->total_tva = -19.6;
5636 $line->multicurrency_total_ht = -200;
5637 $line->multicurrency_total_ttc = -239.2;
5638 $line->multicurrency_total_tva = -39.2;
5639 } elseif ($xnbp == 2 && $option !=
'takepos' && $option !=
'nonegativeup') {
5640 $line->subprice = -100;
5641 $line->total_ht = -100;
5642 $line->total_ttc = -119.6;
5643 $line->total_tva = -19.6;
5644 $line->remise_percent = 0;
5645 $line->multicurrency_total_ht = -200;
5646 $line->multicurrency_total_ttc = -239.2;
5647 $line->multicurrency_total_tva = -39.2;
5648 } elseif ($xnbp == 3) {
5649 $prodid = mt_rand(1, $num_prods);
5650 if (isset($prodids[$prodid])) {
5651 $line->fk_product = $prodids[$prodid];
5653 $line->total_ht = 50;
5654 $line->total_ttc = 59.8;
5655 $line->total_tva = 9.8;
5656 $line->multicurrency_total_ht = 100;
5657 $line->multicurrency_total_ttc = 119.6;
5658 $line->multicurrency_total_tva = 19.6;
5659 $line->remise_percent = 50;
5661 $prodid = mt_rand(1, $num_prods);
5662 if (isset($prodids[$prodid])) {
5663 $line->fk_product = $prodids[$prodid];
5665 $line->total_ht = 100;
5666 $line->total_ttc = 119.6;
5667 $line->total_tva = 19.6;
5668 $line->multicurrency_total_ht = 200;
5669 $line->multicurrency_total_ttc = 239.2;
5670 $line->multicurrency_total_tva = 39.2;
5671 $line->remise_percent = 0;
5674 $this->lines[$xnbp] = $line;
5677 $this->total_ht += $line->total_ht;
5678 $this->total_tva += $line->total_tva;
5679 $this->total_ttc += $line->total_ttc;
5681 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5682 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5683 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5687 $this->revenuestamp = 0;
5690 if ($option !=
'takepos') {
5692 $line->desc = $langs->trans(
"Description").
" (offered line)";
5694 $line->subprice = 100;
5695 $line->tva_tx = 19.6;
5696 $line->localtax1_tx = 0;
5697 $line->localtax2_tx = 0;
5698 $line->remise_percent = 100;
5699 $line->total_ht = 0;
5700 $line->total_ttc = 0;
5701 $line->total_tva = 0;
5702 $line->multicurrency_total_ht = 0;
5703 $line->multicurrency_total_ttc = 0;
5704 $line->multicurrency_total_tva = 0;
5705 $prodid = mt_rand(1, $num_prods);
5706 if (isset($prodids[$prodid])) {
5707 $line->fk_product = $prodids[$prodid];
5710 $this->lines[$xnbp] = $line;
5727 $this->nb = array();
5729 $sanitizedclause =
"WHERE";
5731 $sql =
"SELECT count(f.rowid) as nb";
5732 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5733 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5734 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5735 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5736 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5737 $sanitizedclause =
"AND";
5739 $sql .=
" ".$sanitizedclause.
" f.entity IN (".
getEntity(
'invoice').
")";
5741 $resql = $this->db->query($sql);
5743 while ($obj = $this->db->fetch_object($resql)) {
5744 $this->nb[
"invoices"] = $obj->nb;
5746 $this->db->free($resql);
5750 $this->error = $this->db->error();
5776 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5778 $outputlangs->loadLangs(array(
"bills",
"products"));
5782 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5784 if (!empty($this->model_pdf)) {
5785 $modele = $this->model_pdf;
5793 $modelpath =
"core/modules/facture/doc/";
5795 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5805 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5806 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5807 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5809 $resql = $this->db->query($sql);
5811 if ($this->db->num_rows($resql) > 0) {
5813 $obj = $this->db->fetch_object($resql);
5815 $ref = (int) $obj->maxsituationref;
5821 $this->db->free($resql);
5824 $this->error = $this->db->lasterror();
5825 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5839 return ($this->situation_counter == 1);
5853 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5854 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5855 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5856 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5857 $resql = $this->db->query($sql);
5859 if ($resql && $this->db->num_rows($resql) > 0) {
5860 while ($row = $this->db->fetch_object($resql)) {
5862 $situation =
new Facture($this->db);
5863 $situation->fetch($id);
5864 $res[] = $situation;
5867 $this->error = $this->db->error();
5868 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5888 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5891 $resql = $this->db->query($sql);
5893 $this->errors[] = $this->db->error();
5897 if (!$notrigger && empty($error)) {
5899 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5907 $this->db->commit();
5910 foreach ($this->errors as $errmsg) {
5911 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5912 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5914 $this->db->rollback();
5930 if (!empty($this->situation_cycle_ref)) {
5932 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5933 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5934 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5935 $resql = $this->db->query($sql);
5937 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5938 $last = $res[
'max(situation_counter)'];
5939 return ($last == $this->situation_counter);
5941 $this->error = $this->db->lasterror();
5942 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6000 $hasDelay = $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'));
6001 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
6003 $totalpaid = (float) $totalpaid;
6005 if ($totalpaid >= 0 && $retainedWarrantyAmount >= 0) {
6006 if (($totalpaid < $this->total_ttc - $retainedWarrantyAmount) && $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'))) {
6008 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now -
getWarningDelay(
'invoice',
'client'))) {
6026 return $this->situation_cycle_ref;
6039 $displayWarranty =
false;
6040 if (!empty($this->retained_warranty)) {
6041 $displayWarranty =
true;
6045 $displayWarranty =
false;
6046 if (!empty($this->situation_final)) {
6047 $displayWarranty =
true;
6050 $displayWarranty =
true;
6052 foreach ($this->lines as $i => $line) {
6053 if ($line->product_type < 2 && $line->situation_percent < 100) {
6054 $displayWarranty =
false;
6062 return $displayWarranty;
6073 if (empty($this->retained_warranty)) {
6077 $retainedWarrantyAmount = 0;
6081 $displayWarranty =
true;
6083 if (!empty($this->lines)) {
6084 foreach ($this->lines as $i => $line) {
6085 if ($line->product_type < 2 && $line->situation_percent < 100) {
6086 $displayWarranty =
false;
6092 if ($displayWarranty && !empty($this->situation_final)) {
6094 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6098 foreach ($TPreviousIncoice as &$fac) {
6099 $total2BillWT += $fac->total_ttc;
6101 $total2BillWT += $this->total_ttc;
6104 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6110 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6113 if (is_numeric($rounding) && $rounding < 0) {
6117 if (is_numeric($rounding) && $rounding > 0) {
6118 return round($retainedWarrantyAmount, $rounding);
6121 return (
float)
price2num($retainedWarrantyAmount, $rounding);
6132 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
6134 if ($this->
status >= 0) {
6135 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6136 $sql .=
" SET retained_warranty = ".((float) $value);
6137 $sql .=
' WHERE rowid='.((int) $this->
id);
6139 if ($this->db->query($sql)) {
6140 $this->retained_warranty = (float) $value;
6143 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
6144 $this->error = $this->db->error();
6148 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
6149 $this->error =
'Status of the object is incompatible '.$this->status;
6164 if (!$timestamp && $dateYmd) {
6165 $timestamp = $this->db->jdate($dateYmd);
6169 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
6170 if ($this->
status >= 0) {
6171 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6172 $sql .=
" SET retained_warranty_date_limit = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
6173 $sql .=
' WHERE rowid = '.((int) $this->
id);
6175 if ($this->db->query($sql)) {
6176 $this->retained_warranty_date_limit = $timestamp;
6179 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
6180 $this->error = $this->db->error();
6184 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6185 $this->error =
'Status of the object is incompatible '.$this->status;
6204 global
$conf, $langs, $user;
6210 $errorsMsg = array();
6212 $langs->load(
"bills");
6215 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Invoice"));
6218 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
6219 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6229 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
6230 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
6231 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
6232 $formmail =
new FormMail($this->db);
6237 $tmpinvoice =
new Facture($this->db);
6242 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
6243 if (!empty($paymentmode) && $paymentmode !=
'all') {
6244 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
6246 $sql .=
" WHERE f.paye = 0";
6247 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
6248 if ($datetouse ==
'invoicedate') {
6249 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
6251 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
6253 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
6254 if (!empty($paymentmode) && $paymentmode !=
'all') {
6255 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
6258 if ($datetouse ==
'invoicedate') {
6259 $sql .= $this->db->order(
"datef",
"ASC");
6261 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
6265 $resql = $this->db->query($sql);
6268 if ($datetouse ==
'invoicedate') {
6269 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
6271 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
6273 if (!empty($paymentmode) && $paymentmode !=
'all') {
6274 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
6276 $this->output .=
'<br>';
6279 while ($obj = $this->db->fetch_object($resql)) {
6284 $res = $tmpinvoice->fetch($obj->id);
6286 $tmpinvoice->fetch_thirdparty();
6289 if ($tmpinvoice->thirdparty->default_lang) {
6290 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6291 $outputlangs->loadLangs(array(
"main",
"bills"));
6293 $outputlangs = $langs;
6297 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
6298 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6299 $langs->load(
"errors");
6300 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
6308 $tmpinvoice->totalpaid = $tmpinvoice->getSommePaiement();
6309 $tmpinvoice->totalcreditnotes = $tmpinvoice->getSumCreditNotesUsed();
6310 $tmpinvoice->totaldeposits = $tmpinvoice->getSumDepositsUsed();
6311 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $tmpinvoice);
6316 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6319 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6325 if ($forcerecipient) {
6326 $to = array($forcerecipient);
6328 $res = $tmpinvoice->fetch_thirdparty();
6329 $recipient = $tmpinvoice->thirdparty;
6331 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
6332 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6333 foreach ($tmparraycontact as $data_email) {
6334 if (!empty($data_email[
'email'])) {
6335 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
6339 if (empty($to) && !empty($recipient->email)) {
6340 $to[] = $recipient->email;
6343 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
6347 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6354 if (!empty($arraymessage->email_from)) {
6355 $email_from = (
string) $arraymessage->email_from;
6357 if (empty($email_from)) {
6358 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6362 if (!$loopError && !empty($to)) {
6363 $to = implode(
',', $to);
6364 if (!empty($arraymessage->email_to)) {
6365 $to = $to.
','.$arraymessage->email_to;
6371 $trackid =
'inv'.$tmpinvoice->id;
6372 $sendcontext =
'standard';
6375 if (!empty($arraymessage->email_tocc)) {
6376 $email_tocc = (
string) $arraymessage->email_tocc;
6380 if (!empty($arraymessage->email_tobcc)) {
6381 $email_tobcc = (
string) $arraymessage->email_tobcc;
6388 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6389 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
6390 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6391 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
6395 $cMailFile =
new CMailFile($sendTopic, $to, $email_from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
6397 $resultsendmail = $cMailFile->sendfile();
6402 if ($resultsendmail) {
6406 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6411 $actioncomm->type_code =
'AC_OTH_AUTO';
6412 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6413 $actioncomm->contact_id = 0;
6415 $actioncomm->code =
'AC_EMAIL';
6416 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
6417 $actioncomm->note_private = $sendContent;
6418 $actioncomm->fk_project = $tmpinvoice->fk_project;
6419 $actioncomm->datep =
dol_now();
6420 $actioncomm->datef = $actioncomm->datep;
6421 $actioncomm->percentage = -1;
6422 $actioncomm->authorid = $user->id;
6423 $actioncomm->userownerid = $user->id;
6425 $actioncomm->email_msgid = $cMailFile->msgid;
6426 $actioncomm->email_subject = $sendTopic;
6427 $actioncomm->email_from = $email_from;
6428 $actioncomm->email_sender =
'';
6429 $actioncomm->email_to = $to;
6433 $actioncomm->errors_to = $errors_to;
6435 $actioncomm->elementtype =
'invoice';
6436 $actioncomm->elementid = $tmpinvoice->id;
6440 $actioncomm->create($user);
6442 $errormesg = $cMailFile->error.
' : '.$to;
6446 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6451 $actioncomm->type_code =
'AC_OTH_AUTO';
6452 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6453 $actioncomm->contact_id = 0;
6455 $actioncomm->code =
'AC_EMAIL';
6456 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
6457 $actioncomm->note_private = $errormesg;
6458 $actioncomm->fk_project = $tmpinvoice->fk_project;
6459 $actioncomm->datep =
dol_now();
6460 $actioncomm->datef = $actioncomm->datep;
6461 $actioncomm->percentage = -1;
6462 $actioncomm->authorid = $user->id;
6463 $actioncomm->userownerid = $user->id;
6465 $actioncomm->email_msgid = $cMailFile->msgid;
6466 $actioncomm->email_subject = $sendTopic;
6467 $actioncomm->email_from = $email_from;
6468 $actioncomm->email_sender =
'';
6469 $actioncomm->email_to = $to;
6473 $actioncomm->errors_to = $errors_to;
6475 $actioncomm->elementtype =
'invoice';
6476 $actioncomm->elementid = $tmpinvoice->id;
6480 $actioncomm->create($user);
6483 $this->db->commit();
6487 $errorsMsg[] = $errormesg;
6490 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6494 $error += $loopError;
6501 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6503 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6507 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6509 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6524 $sql =
"SELECT datef";
6525 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6526 $sql .=
" WHERE type = " . (int) $this->
type ;
6527 $sql .=
" AND date_valid IS NOT NULL";
6528 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6529 $sql .=
" ORDER BY datef DESC LIMIT 1";
6531 $result = $this->db->query($sql);
6534 if ($this->db->num_rows($result)) {
6535 $obj = $this->db->fetch_object($result);
6536 $last_date = $this->db->jdate($obj->datef);
6537 $invoice_date = $this->date;
6539 $is_last_of_same_type = $invoice_date >= $last_date;
6540 if ($allow_validated_drafts) {
6544 return array($is_last_of_same_type, $last_date);
6567 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6569 $picto = $this->picto;
6570 if ($this->
type == self::TYPE_REPLACEMENT) {
6573 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6576 if ($this->
type == self::TYPE_DEPOSIT) {
6580 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6581 $return .=
'<div class="info-box info-box-sm">';
6582 $return .=
'<span class="info-box-icon bg-infobox-action">';
6584 $return .=
'</span>';
6585 $return .=
'<div class="info-box-content">';
6586 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6587 if ($selected >= 0) {
6588 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6590 if (!empty($arraydata[
'thirdparty'])) {
6591 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6593 if (property_exists($this,
'date')) {
6594 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->
date,
'day').
'</span>';
6596 if (property_exists($this,
'total_ht')) {
6597 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6598 $return .=
' '.$langs->trans(
"HT");
6599 $return .=
'</span>';
6601 if (method_exists($this,
'getLibStatut')) {
6602 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6603 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6605 $return .=
'</div>';
6606 $return .=
'</div>';
6607 $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.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage invoices.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Returns the IDs of the customer shipping contacts.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
createFromClone(User $user, $fromid=0, $forceentity=null)
Load an object from its id and create a new one in database.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Replace a thirdparty id with another one.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
__construct($db)
Constructor.
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines ...
update(User $user, $notrigger=0)
Update database.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
getIdBillingContact()
Returns the IDs of the customer billing contacts.
const STATUS_DRAFT
Draft status.
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_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
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)
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.