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 if ($origin_user_author_id > 0) {
791 $this->user_creation_id = $origin_user_author_id;
792 $this->fk_user_author = $origin_user_author_id;
796 $this->
ref =
'(PROV'.$this->id.
')';
797 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
799 $resql = $this->db->query($sql);
804 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
805 $this->linked_objects = $this->linkedObjectsIds;
809 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
810 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
811 if (is_array($tmp_origin_id)) {
812 foreach ($tmp_origin_id as $origin_id) {
815 $this->error = $this->db->lasterror();
820 $origin_id = $tmp_origin_id;
823 $this->error = $this->db->lasterror();
831 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && (!empty($this->origin_type) || !empty($this->origin)) && !empty($this->origin_id)) {
832 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
833 $originidforcontact = $this->origin_id;
834 if ($originforcontact ==
'shipping') {
835 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
837 $exp->fetch($this->origin_id);
838 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
839 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
840 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
841 $originforcontact =
'commande';
842 if (is_object($value)) {
843 $originidforcontact = $value->id;
845 $originidforcontact = $value;
852 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople";
853 $sqlcontact .=
" FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
854 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
856 $resqlcontact = $this->db->query($sqlcontact);
858 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
859 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
867 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
870 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
871 foreach ($this->lines as $i => $val) {
872 $newinvoiceline = $this->lines[$i];
873 '@phan-var-force FactureLigne $newinvoiceline';
875 $newinvoiceline->context = $this->context;
877 $newinvoiceline->fk_facture = $this->id;
879 $newinvoiceline->origin = $this->lines[$i]->element;
880 $newinvoiceline->origin_type = $this->lines[$i]->element;
881 $newinvoiceline->origin_id = $this->lines[$i]->id;
884 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
885 $newinvoiceline->date_start = $originaldatewhen;
887 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
888 $newinvoiceline->date_end = $previousdaynextdatewhen;
893 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
898 $vatrate = $newinvoiceline->tva_tx;
899 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
900 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
903 $newinvoiceline->fk_parent_line = $fk_parent_line;
907 $discount->fetch($newinvoiceline->fk_remise_except);
909 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
910 $newinvoiceline->fk_remise_except = $discountId;
914 $newinvoiceline->desc,
915 $newinvoiceline->subprice,
916 $newinvoiceline->qty,
918 $newinvoiceline->localtax1_tx,
919 $newinvoiceline->localtax2_tx,
920 $newinvoiceline->fk_product,
921 $newinvoiceline->remise_percent,
922 $newinvoiceline->date_start,
923 $newinvoiceline->date_end,
924 $newinvoiceline->fk_code_ventilation,
925 $newinvoiceline->info_bits,
926 $newinvoiceline->fk_remise_except,
929 $newinvoiceline->product_type,
930 $newinvoiceline->rang,
931 $newinvoiceline->special_code,
932 $newinvoiceline->element,
935 $newinvoiceline->fk_fournprice,
936 $newinvoiceline->pa_ht,
937 $newinvoiceline->label,
938 $newinvoiceline->array_options,
939 $newinvoiceline->situation_percent,
940 $newinvoiceline->fk_prev_id,
941 $newinvoiceline->fk_unit,
942 $newinvoiceline->multicurrency_subprice,
943 $newinvoiceline->ref_ext,
954 if ($result > 0 && $newinvoiceline->product_type == 9) {
955 $fk_parent_line = $result;
959 } elseif (!$error && empty($this->fac_rec)) {
962 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
966 $linestoadd = $this->lines;
967 $this->lines = array();
968 foreach ($linestoadd as $i => $val) {
969 $line = $linestoadd[$i];
970 '@phan-var-force FactureLigne $line';
974 if (!is_object($line)) {
975 $line = (object) $line;
980 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
985 $vatrate = $line->tva_tx;
986 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
987 $vatrate .=
' ('.$line->vat_src_code.
')';
991 $originid = $line->origin_id;
992 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
994 $originid = $line->id;
995 $origintype = $this->element;
999 if (empty($line->ref_ext)) {
1000 $line->ref_ext =
'';
1008 $line->localtax1_tx,
1009 $line->localtax2_tx,
1011 $line->remise_percent,
1014 $line->fk_code_ventilation,
1016 $line->fk_remise_except,
1019 $line->product_type,
1021 $line->special_code,
1025 $line->fk_fournprice,
1028 $line->array_options,
1029 $line->situation_percent,
1032 $line->multicurrency_subprice,
1037 $this->error = $this->db->lasterror();
1039 $this->db->rollback();
1044 if ($result > 0 && $line->product_type == 9) {
1045 $fk_parent_line = $result;
1052 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1053 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1054 $fk_parent_line = 0;
1056 foreach ($_facrec->lines as $i => $val) {
1058 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1059 $fk_parent_line = 0;
1062 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1063 $tva_npr = (int) $_facrec->lines[$i]->info_bits;
1064 if (empty($tva_tx)) {
1067 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1068 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1070 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1071 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1074 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1075 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1077 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1082 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1083 $buyprice = $producttmp->cost_price;
1085 $buyprice = $producttmp->pmp;
1087 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1088 if ($producttmp->product_fourn_price_id > 0) {
1089 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1096 if ($updatecurrencyrate == 1) {
1098 } elseif ($updatecurrencyrate == 2) {
1102 $result_insert = $this->
addline(
1103 $_facrec->lines[$i]->desc,
1104 $_facrec->lines[$i]->subprice,
1105 $_facrec->lines[$i]->qty,
1109 $_facrec->lines[$i]->fk_product,
1110 $_facrec->lines[$i]->remise_percent,
1111 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1112 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1118 $_facrec->lines[$i]->product_type,
1119 $_facrec->lines[$i]->rang,
1120 $_facrec->lines[$i]->special_code,
1124 $fk_product_fournisseur_price,
1125 is_null($buyprice) ?
'' : $buyprice,
1126 $_facrec->lines[$i]->label,
1127 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1130 $_facrec->lines[$i]->fk_unit,
1131 $_facrec->lines[$i]->multicurrency_subprice,
1132 $_facrec->lines[$i]->ref_ext,
1136 foreach ($this->lines as $line) {
1137 if ($line->id == $result_insert) {
1138 $line->extraparams = $_facrec->lines[$i]->extraparams;
1139 $line->setExtraParameters();
1144 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1145 $fk_parent_line = $result_insert;
1148 if ($result_insert < 0) {
1150 $this->error = $this->db->error();
1159 $this->error = $langs->trans(
'FailedToUpdatePrice');
1160 $this->db->rollback();
1175 if (!$error && !$notrigger) {
1177 $result = $this->call_trigger(
'BILL_CREATE', $user);
1184 $this->db->commit();
1187 $this->db->rollback();
1191 $this->error = $this->db->error();
1192 $this->db->rollback();
1208 $facture =
new Facture($this->db);
1211 $facture->context[
'createfromclone'] = 1;
1216 if (empty($this->array_options)) {
1220 if (!empty($this->array_options)) {
1221 $facture->array_options = $this->array_options;
1224 foreach ($this->lines as &$line) {
1225 $line->fetch_optionals();
1228 $facture->fk_facture_source = $this->fk_facture_source;
1229 $facture->type = $this->type;
1230 $facture->subtype = $this->subtype;
1231 $facture->socid = $this->socid;
1232 $facture->date = $this->date;
1233 $facture->date_pointoftax = $this->date_pointoftax;
1234 $facture->note_public = $this->note_public;
1235 $facture->note_private = $this->note_private;
1236 $facture->ref_client = $this->ref_client;
1237 $facture->ref_customer = $this->ref_customer;
1238 $facture->model_pdf = $this->model_pdf;
1239 $facture->fk_project = $this->fk_project;
1240 $facture->cond_reglement_id = $this->cond_reglement_id;
1241 $facture->mode_reglement_id = $this->mode_reglement_id;
1243 $facture->origin = $this->origin;
1244 $facture->origin_id = $this->origin_id;
1245 $facture->fk_account = $this->fk_account;
1247 $facture->lines = $this->lines;
1248 $facture->situation_counter = $this->situation_counter;
1249 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1250 $facture->situation_final = $this->situation_final;
1252 $facture->retained_warranty = $this->retained_warranty;
1253 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1254 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1256 $facture->fk_user_author = $user->id;
1257 $facture->user_creation_id = $user->id;
1261 foreach ($facture->lines as $i => $tmpline) {
1262 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1263 if ($invertdetail) {
1264 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1265 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1266 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1267 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1268 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1269 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1270 $facture->lines[$i]->ref_ext =
'';
1274 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1276 $facid = $facture->create($user);
1278 $this->error = $facture->error;
1279 $this->errors = $facture->errors;
1283 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1284 foreach ($Tfk_object as $fk_object) {
1285 $facture->add_object_linked($typeObject, $fk_object);
1289 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1306 global $hookmanager;
1326 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1327 $objsoc =
new Societe($this->db);
1329 if ($objsoc->fetch($this->socid) > 0) {
1331 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1332 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1334 $object->fk_delivery_address = 0;
1340 $object->entity = (!empty($forceentity) ? $forceentity :
$object->entity);
1348 $object->user_creation_id = $user->id;
1349 $object->user_validation_id =
null;
1350 $object->user_modification_id =
null;
1351 $object->fk_user_author = $user->id;
1352 $object->fk_user_valid =
null;
1353 $object->fk_facture_source = 0;
1354 $object->fk_fac_rec_source = 0;
1356 $object->date_modification =
'';
1357 $object->date_validation =
'';
1370 foreach (
$object->lines as $i => $line) {
1371 '@phan-var-force FactureLigne $line';
1372 if (($line->info_bits & 0x02) == 0x02) {
1379 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1391 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1392 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1396 $object->lines[$i]->date_start = $newFirst;
1397 $object->lines[$i]->date_end = $newLast;
1401 $object->lines[$i]->ref_ext =
'';
1404 $object->lines[$i]->fk_code_ventilation = 0;
1408 $object->context[
'createfromclone'] =
'createfromclone';
1409 $result =
$object->create($user);
1416 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1419 } elseif (
$object->socid == $objFrom->socid) {
1421 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1430 if (is_object($hookmanager)) {
1431 $parameters = array(
'objFrom' => $objFrom,
'clonedObj' =>
$object);
1433 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1441 unset(
$object->context[
'createfromclone']);
1445 $this->db->commit();
1448 $this->db->rollback();
1462 global $hookmanager;
1471 $this->context[
'createfromclone'] = 1;
1474 for ($i = 0; $i < $num; $i++) {
1476 $src_line =
$object->lines[$i];
1477 '@phan-var-force FactureLigne $src_line';
1478 $line->libelle = $src_line->libelle;
1479 $line->label = $src_line->label;
1480 $line->desc = $src_line->desc;
1481 $line->subprice = $src_line->subprice;
1482 $line->total_ht = $src_line->total_ht;
1483 $line->total_tva = $src_line->total_tva;
1484 $line->total_localtax1 = $src_line->total_localtax1;
1485 $line->total_localtax2 = $src_line->total_localtax2;
1486 $line->total_ttc = $src_line->total_ttc;
1487 $line->vat_src_code = $src_line->vat_src_code;
1488 $line->tva_tx = $src_line->tva_tx;
1489 $line->localtax1_tx = $src_line->localtax1_tx;
1490 $line->localtax2_tx = $src_line->localtax2_tx;
1491 $line->qty = $src_line->qty;
1492 $line->fk_remise_except = $src_line->fk_remise_except;
1493 $line->remise_percent = $src_line->remise_percent;
1494 $line->fk_product = $src_line->fk_product;
1495 $line->info_bits = $src_line->info_bits;
1496 $line->product_type = $src_line->product_type;
1497 $line->rang = $src_line->rang;
1498 $line->special_code = $src_line->special_code;
1499 $line->fk_parent_line = $src_line->fk_parent_line;
1500 $line->fk_unit = $src_line->fk_unit;
1501 $line->date_start = $src_line->date_start;
1502 $line->date_end = $src_line->date_end;
1505 $line->fk_multicurrency = $src_line->fk_multicurrency;
1506 $line->multicurrency_code = $src_line->multicurrency_code;
1507 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1508 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1509 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1510 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1512 $line->fk_fournprice = $src_line->fk_fournprice;
1513 $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);
1514 $line->pa_ht = $marginInfos[0];
1517 $src_line->fetch_optionals();
1518 foreach ($src_line->array_options as $options_key => $value) {
1519 $line->array_options[$options_key] = $value;
1522 $this->lines[$i] = $line;
1525 $this->socid =
$object->socid;
1526 $this->fk_project =
$object->fk_project;
1527 $this->fk_account =
$object->fk_account;
1528 $this->cond_reglement_id =
$object->cond_reglement_id;
1529 $this->mode_reglement_id =
$object->mode_reglement_id;
1530 $this->fk_incoterms =
$object->fk_incoterms;
1531 $this->location_incoterms =
$object->location_incoterms;
1532 $this->availability_id =
$object->availability_id;
1533 $this->demand_reason_id =
$object->demand_reason_id;
1534 $this->delivery_date =
$object->delivery_date;
1535 $this->fk_delivery_address =
$object->fk_delivery_address;
1536 $this->contact_id =
$object->contact_id;
1537 $this->ref_client =
$object->ref_client;
1538 $this->ref_customer =
$object->ref_client;
1541 $this->note_private =
$object->note_private;
1542 $this->note_public =
$object->note_public;
1545 $this->module_source =
$object->module_source;
1546 $this->pos_source =
$object->pos_source;
1548 $this->origin =
$object->element;
1549 $this->origin_type =
$object->element;
1550 $this->origin_id =
$object->id;
1552 $this->fk_user_author = $user->id;
1553 $this->user_creation_id = $user->id;
1557 foreach (
$object->array_options as $options_key => $value) {
1558 $this->array_options[$options_key] = $value;
1562 $this->linked_objects[$this->origin] = $this->origin_id;
1563 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1564 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1567 $ret = $this->
create($user);
1571 $hookmanager->initHooks(array(
'invoicedao'));
1573 $parameters = array(
'objFrom' =>
$object);
1575 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1584 unset($this->context[
'createfromclone']);
1603 global $hookmanager;
1611 $use_all_lines = empty($lines);
1613 for ($i = 0; $i < $num; $i++) {
1614 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1620 $line->libelle =
$object->lines[$i]->libelle;
1621 $line->label =
$object->lines[$i]->label;
1622 $line->desc =
$object->lines[$i]->desc;
1623 $line->subprice =
$object->lines[$i]->subprice;
1624 $line->total_ht =
$object->lines[$i]->total_ht;
1625 $line->total_tva =
$object->lines[$i]->total_tva;
1626 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1627 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1628 $line->total_ttc =
$object->lines[$i]->total_ttc;
1629 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1630 $line->tva_tx =
$object->lines[$i]->tva_tx;
1631 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1632 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1633 $line->qty =
$object->lines[$i]->qty;
1634 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1635 $line->remise_percent =
$object->lines[$i]->remise_percent;
1636 $line->fk_product =
$object->lines[$i]->fk_product;
1637 $line->info_bits =
$object->lines[$i]->info_bits;
1638 $line->product_type =
$object->lines[$i]->product_type;
1639 $line->rang =
$object->lines[$i]->rang;
1640 $line->special_code =
$object->lines[$i]->special_code;
1641 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1642 $line->fk_unit =
$object->lines[$i]->fk_unit;
1643 $line->date_start =
$object->lines[$i]->date_start;
1644 $line->date_end =
$object->lines[$i]->date_end;
1647 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1648 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1649 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1650 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1651 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1652 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1654 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1656 $line->pa_ht = $marginInfos[0];
1659 $object->lines[$i]->fetch_optionals();
1660 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1661 $line->array_options[$options_key] = $value;
1664 $this->lines[$i] = $line;
1667 $this->socid =
$object->socid;
1668 $this->fk_project =
$object->fk_project;
1669 $this->fk_account =
$object->fk_account;
1670 $this->cond_reglement_id =
$object->cond_reglement_id;
1671 $this->mode_reglement_id =
$object->mode_reglement_id;
1672 $this->availability_id =
$object->availability_id;
1673 $this->demand_reason_id =
$object->demand_reason_id;
1674 $this->delivery_date =
$object->delivery_date;
1675 $this->fk_delivery_address =
$object->fk_delivery_address;
1676 $this->contact_id =
$object->contact_id;
1677 $this->ref_client =
$object->ref_client;
1680 $this->note_private =
$object->note_private;
1681 $this->note_public =
$object->note_public;
1684 $this->module_source =
$object->module_source;
1685 $this->pos_source =
$object->pos_source;
1687 $this->origin =
$object->element;
1688 $this->origin_id =
$object->id;
1690 $this->fk_user_author = $user->id;
1691 $this->user_creation_id = $user->id;
1695 foreach (
$object->array_options as $options_key => $value) {
1696 $this->array_options[$options_key] = $value;
1700 $this->linked_objects[$this->origin] = $this->origin_id;
1701 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1702 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1705 $ret = $this->
create($user);
1709 $hookmanager->initHooks(array(
'invoicedao'));
1711 $parameters = array(
'objFrom' =>
$object);
1713 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1743 global
$conf, $langs, $hookmanager, $action;
1745 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1746 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1751 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1755 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1758 $origin->error =
'ErrorDateIsInFuture';
1762 if ($payment_terms_id <= 0) {
1763 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1767 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1769 if (empty($payment_conditions_deposit_percent)) {
1770 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1774 if (empty($origin->deposit_percent)) {
1775 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1779 $deposit =
new self($origin->db);
1780 $deposit->socid = $origin->socid;
1782 $deposit->fk_project = $origin->fk_project;
1783 $deposit->ref_client = $origin->ref_client;
1784 $deposit->ref_customer = $origin->ref_client;
1785 $deposit->date = $date;
1786 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1787 $deposit->cond_reglement_id = $payment_terms_id;
1788 $deposit->availability_id = $origin->availability_id;
1789 $deposit->demand_reason_id = $origin->demand_reason_id;
1790 $deposit->fk_account = $origin->fk_account;
1791 $deposit->fk_incoterms = $origin->fk_incoterms;
1792 $deposit->location_incoterms = $origin->location_incoterms;
1793 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1794 $deposit->multicurrency_code = $origin->multicurrency_code;
1795 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1796 $deposit->module_source = $origin->module_source;
1797 $deposit->pos_source = $origin->pos_source;
1798 $deposit->model_pdf =
'sponge';
1800 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1809 $deposit->note_private = $origin->note_private;
1810 $deposit->note_public = $origin->note_public;
1813 $deposit->origin = $origin->element;
1814 $deposit->origin_type = $origin->element;
1815 $deposit->origin_id = $origin->id;
1817 $origin->fetch_optionals();
1819 foreach ($origin->array_options as $extrakey => $value) {
1820 $deposit->array_options[$extrakey] = $value;
1823 $deposit->linked_objects[$deposit->origin_type] = $deposit->origin_id;
1825 foreach ($overrideFields as $key => $value) {
1826 $deposit->$key = $value;
1829 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1831 $origin->db->begin();
1834 $createReturn = $deposit->create($user, $notrigger);
1836 if ($createReturn <= 0) {
1837 $origin->db->rollback();
1838 $origin->error = $deposit->error;
1839 $origin->errors = $deposit->errors;
1843 $amount_ttc_diff = 0;
1844 $amountdeposit = array();
1845 $descriptions = array();
1852 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1854 $TTotalByTva = array();
1855 foreach ($origin->lines as &$line) {
1856 if (!empty($line->special_code)) {
1859 $key = $line->tva_tx . ($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
1860 if (!array_key_exists($key, $TTotalByTva)) {
1861 $TTotalByTva[$key] = 0;
1862 $descriptions[$key] =
'';
1864 $TTotalByTva[$key] += $line->total_ttc;
1865 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1866 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1867 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1868 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1871 foreach ($TTotalByTva as $tva => &$total) {
1872 $tva_rate_only = preg_replace(
'/\s*\(.*\)/',
'', (
string) $tva);
1873 $coef = ($origin->total_ttc != 0 ? $total / $origin->total_ttc : 0);
1874 $am = $amount * $coef;
1875 $amount_ttc_diff += $am;
1876 if (!isset($amountdeposit[$tva])) {
1877 $amountdeposit[$tva] = 0;
1879 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100);
1884 $lines = $origin->lines;
1885 $numlines = count($lines);
1886 for ($i = 0; $i < $numlines; $i++) {
1887 if (empty($lines[$i]->qty)) {
1890 if (!empty($lines[$i]->special_code)) {
1894 $totalamount += $lines[$i]->total_ht;
1895 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ?
' ('.$lines[$i]->vat_src_code.
')' :
'');
1896 if (!isset($amountdeposit[$tva_key])) {
1897 $amountdeposit[$tva_key] = 0;
1898 $descriptions[$tva_key] =
'';
1900 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1901 $descriptions[$tva_key] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1902 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1903 $descriptions[$tva_key] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1904 $descriptions[$tva_key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1907 if ($totalamount == 0) {
1908 $amountdeposit[0] = 0;
1911 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1914 foreach ($amountdeposit as $tva => $amount) {
1915 if (empty($amount)) {
1919 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1922 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1923 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1926 $addlineResult = $deposit->addline(
1953 if ($addlineResult < 0) {
1954 $origin->db->rollback();
1955 $origin->error = $deposit->error;
1956 $origin->errors = $deposit->errors;
1961 $diff = $deposit->total_ttc - $amount_ttc_diff;
1964 $deposit->fetch_lines();
1965 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1969 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ?
' ('.$deposit->lines[0]->vat_src_code.
')' :
'');
1970 $updatelineResult = $deposit->updateline(
1971 $deposit->lines[0]->id,
1972 $deposit->lines[0]->desc,
1974 $deposit->lines[0]->qty,
1975 $deposit->lines[0]->remise_percent,
1976 $deposit->lines[0]->date_start,
1977 $deposit->lines[0]->date_end,
1982 $deposit->lines[0]->info_bits,
1983 $deposit->lines[0]->product_type,
1987 $deposit->lines[0]->pa_ht,
1988 $deposit->lines[0]->label,
1994 if ($updatelineResult < 0) {
1995 $origin->db->rollback();
1996 $origin->error = $deposit->error;
1997 $origin->errors = $deposit->errors;
2002 $hookmanager->initHooks(array(
'invoicedao'));
2004 $parameters = array(
'objFrom' => $origin);
2005 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
2008 $origin->db->rollback();
2009 $origin->error = $hookmanager->error;
2010 $origin->errors = $hookmanager->errors;
2014 if (!empty($autoValidateDeposit)) {
2015 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
2017 if ($validateReturn < 0) {
2018 $origin->db->rollback();
2019 $origin->error = $deposit->error;
2020 $origin->errors = $deposit->errors;
2025 unset($deposit->context[
'createdepositfromorigin']);
2027 $origin->db->commit();
2043 $langs->load(
'bills');
2046 $moretitle = $params[
'moretitle'] ??
'';
2048 $picto = $this->picto;
2049 if ($this->
type == self::TYPE_REPLACEMENT) {
2052 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2055 if ($this->
type == self::TYPE_DEPOSIT) {
2059 if ($user->hasRight(
"facture",
"read")) {
2060 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
2062 $datas[
'picto'] .=
' '.$this->getLibType(1);
2065 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
2068 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2071 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
2074 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2075 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2078 $datas[
'picto'] .=
' - '.$moretitle;
2080 if (!empty($this->
ref)) {
2081 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2083 if (!empty($this->ref_customer)) {
2084 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
2086 if (!empty($this->
date)) {
2087 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->
date,
'day');
2089 if (!empty($this->total_ht)) {
2090 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2092 if (!empty($this->total_tva)) {
2093 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2095 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2096 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1,
$conf->currency);
2098 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2100 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1',
$mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency);
2102 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2103 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2',
$mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency);
2105 if (!empty($this->total_ttc)) {
2106 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2127 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2129 global $langs,
$conf, $user;
2131 if (!empty(
$conf->dol_no_mouse_hover)) {
2137 if ($option ==
'withdraw') {
2138 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2140 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2143 if (!$user->hasRight(
"facture",
"read")) {
2147 if ($option !==
'nolink') {
2149 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2150 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2151 $add_save_lastsearch_values = 1;
2153 if ($add_save_lastsearch_values) {
2154 $url .=
'&save_lastsearch_values=1';
2162 $picto = $this->picto;
2163 if ($this->
type == self::TYPE_REPLACEMENT) {
2166 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2169 if ($this->
type == self::TYPE_DEPOSIT) {
2175 'objecttype' => $this->element,
2176 'moretitle' => $moretitle,
2177 'option' => $option,
2179 $classfortooltip =
'classfortooltip';
2182 $classfortooltip =
'classforajaxtooltip';
2183 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2189 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2190 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2192 $label = $langs->trans(
"Invoice");
2193 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2195 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2196 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2199 $linkstart =
'<a href="'.$url.
'"';
2200 $linkstart .= $linkclose.
'>';
2203 if ($option ==
'nolink') {
2208 $result .= $linkstart;
2210 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2212 if ($withpicto != 2) {
2213 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2215 $result .= $linkend;
2217 if ($addlinktonotes) {
2218 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2220 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2221 $result .=
' <span class="note inline-block">';
2222 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dolPrintHTMLForAttribute($notetoshow).
'">';
2225 $result .=
'</span>';
2229 global $action, $hookmanager;
2230 $hookmanager->initHooks(array(
'invoicedao'));
2231 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2232 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2234 $result = $hookmanager->resPrint;
2236 $result .= $hookmanager->resPrint;
2252 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2254 global
$conf, $extrafields;
2256 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2260 $extraFieldsCheck =
false;
2261 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2263 if ($doFetchInOneSqlRequest) {
2265 if (!isset($extrafields) || !is_object($extrafields)) {
2266 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2271 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
2272 $extrafields->fetch_name_optionals_label($this->table_element);
2275 $extraFieldsCheck = (
2276 !empty($extrafields->attributes[$this->table_element][
'label'])
2277 && is_array($extrafields->attributes[$this->table_element][
'label'])
2278 && count($extrafields->attributes[$this->table_element][
'label']) > 0
2284 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2285 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2286 $sql .=
', f.datef as df, f.date_pointoftax';
2287 $sql .=
', f.date_lim_reglement as dlr';
2288 $sql .=
', f.datec as datec';
2289 $sql .=
', f.date_valid as datev';
2290 $sql .=
', f.tms as datem';
2291 $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';
2292 $sql .=
", f.fk_input_reason";
2293 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2294 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2295 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2296 $sql .=
', f.fk_account';
2297 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2298 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2299 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2300 $sql .=
', f.fk_incoterms, f.location_incoterms';
2301 $sql .=
', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2302 $sql .=
", i.libelle as label_incoterms";
2303 $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";
2304 $sql .=
", f.payment_reference, f.dispute_status";
2306 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2307 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2308 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2309 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2312 if ($type !==
'separate') {
2313 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2314 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2316 $sql .=
", ef.".$this->db->sanitize($key);
2322 $sql .=
' FROM '.$this->db->prefix().
'facture as f';
2325 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2327 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element.
'_extrafields as ef ON f.rowid = ef.fk_object';
2330 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2331 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_paiement as p ON f.fk_mode_reglement = p.id';
2332 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2333 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2336 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2338 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2340 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2343 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2347 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2348 $resql = $this->db->query($sql);
2350 if ($this->db->num_rows($resql)) {
2351 $obj = $this->db->fetch_object($resql);
2353 $this->
id = $obj->rowid;
2354 $this->entity = $obj->entity;
2356 $this->
ref = $obj->ref;
2357 $this->ref_client = $obj->ref_client;
2358 $this->ref_customer = $obj->ref_client;
2359 $this->ref_ext = $obj->ref_ext;
2360 $this->
type = $obj->type;
2361 $this->subtype = $obj->subtype;
2362 $this->
date = $this->db->jdate($obj->df);
2363 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2364 $this->date_creation = $this->db->jdate($obj->datec);
2365 $this->date_validation = $this->db->jdate($obj->datev);
2366 $this->date_modification = $this->db->jdate($obj->datem);
2367 $this->datem = $this->db->jdate($obj->datem);
2368 $this->total_ht = $obj->total_ht;
2369 $this->total_tva = $obj->total_tva;
2370 $this->total_localtax1 = $obj->localtax1;
2371 $this->total_localtax2 = $obj->localtax2;
2372 $this->total_ttc = $obj->total_ttc;
2373 $this->revenuestamp = $obj->revenuestamp;
2374 $this->paye = $obj->paye;
2375 $this->close_code = $obj->close_code;
2376 $this->close_note = $obj->close_note;
2378 $this->socid = $obj->fk_soc;
2379 $this->thirdparty =
null;
2381 $this->fk_project = $obj->fk_project;
2382 $this->project =
null;
2384 $this->statut = $obj->status;
2385 $this->
status = $obj->status;
2387 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2388 $this->mode_reglement_id = $obj->fk_mode_reglement;
2389 $this->mode_reglement_code = $obj->mode_reglement_code;
2390 $this->mode_reglement = $obj->mode_reglement_libelle;
2391 $this->cond_reglement_id = $obj->fk_cond_reglement;
2392 $this->cond_reglement_code = $obj->cond_reglement_code;
2393 $this->cond_reglement = $obj->cond_reglement_libelle;
2394 $this->cond_reglement_label = $obj->cond_reglement_libelle;
2395 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2396 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2397 $this->fk_facture_source = $obj->fk_facture_source;
2398 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2399 $this->note = $obj->note_private;
2400 $this->note_private = $obj->note_private;
2401 $this->note_public = $obj->note_public;
2402 $this->user_creation_id = $obj->fk_user_author;
2403 $this->user_validation_id = $obj->fk_user_valid;
2404 $this->user_modification_id = $obj->fk_user_modif;
2405 $this->fk_user_author = $obj->fk_user_author;
2406 $this->fk_user_valid = $obj->fk_user_valid;
2407 $this->fk_user_modif = $obj->fk_user_modif;
2408 $this->model_pdf = $obj->model_pdf;
2409 $this->last_main_doc = $obj->last_main_doc;
2410 $this->demand_reason_id = $obj->fk_input_reason;
2411 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2412 $this->situation_counter = $obj->situation_counter;
2413 $this->situation_final = $obj->situation_final;
2414 $this->retained_warranty = $obj->retained_warranty;
2415 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2416 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2418 $this->payment_reference = $obj->payment_reference;
2419 $this->dispute_status = $obj->dispute_status;
2421 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2424 $this->fk_incoterms = $obj->fk_incoterms;
2425 $this->location_incoterms = $obj->location_incoterms;
2426 $this->label_incoterms = $obj->label_incoterms;
2428 $this->module_source = $obj->module_source;
2429 $this->pos_source = $obj->pos_source;
2430 $this->pos_print_counter = (int) $obj->pos_print_counter;
2431 $this->email_sent_counter = $obj->email_sent_counter;
2434 $this->fk_multicurrency = $obj->fk_multicurrency;
2435 $this->multicurrency_code = $obj->multicurrency_code;
2436 $this->multicurrency_tx = $obj->multicurrency_tx;
2437 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2438 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2439 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2442 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2443 $this->array_options = array();
2445 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2446 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2447 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2450 if ($type !==
'separate') {
2451 $rawval = $obj->$key;
2454 if (in_array($type, array(
'date',
'datetime'))) {
2455 $this->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2456 } elseif ($type ==
'password') {
2457 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2458 $this->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2460 $this->array_options[
'options_' . $key] = $rawval;
2463 $this->array_options[
'options_' . $key] = $rawval;
2469 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2470 if (!empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
2471 if (empty(
$conf->disable_compute)) {
2472 global $objectoffield;
2473 $objectoffield = $this;
2474 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
2480 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2484 if (!$doFetchInOneSqlRequest) {
2491 $this->lines = array();
2495 $this->error = $this->db->error();
2499 $this->db->free($resql);
2503 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2505 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2509 $this->error = $this->db->lasterror();
2523 public function fetch_lines($only_type_product =
'', $loadalsotranslation = 0)
2525 global
$conf, $extrafields;
2528 $this->lines = array();
2530 $extraFieldsCheck =
false;
2531 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2533 if ($doFetchInOneSqlRequest) {
2535 if (!isset($extrafields) || !is_object($extrafields)) {
2536 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2541 if (empty($extrafields->attributes[$this->table_element_line][
'loaded'])) {
2542 $extrafields->fetch_name_optionals_label($this->table_element_line);
2545 $extraFieldsCheck = (
2546 !empty($extrafields->attributes[$this->table_element_line][
'label'])
2547 && is_array($extrafields->attributes[$this->table_element_line][
'label'])
2548 && count($extrafields->attributes[$this->table_element_line][
'label']) > 0
2552 $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,';
2553 $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,';
2554 $sql .=
' l.situation_percent, l.fk_prev_id,';
2555 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2556 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2557 $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,';
2558 $sql .=
' l.fk_unit, l.extraparams,';
2559 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2560 $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';
2562 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2563 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2564 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2565 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2568 if ($type !==
'separate') {
2569 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2570 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2572 $sql .=
", ef.".$this->db->sanitize($key);
2578 $sql .=
' FROM '.$this->db->prefix().
'facturedet as l';
2581 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2583 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element_line.
'_extrafields as ef ON l.rowid = ef.fk_object';
2586 $sql .=
' LEFT JOIN '.$this->db->prefix().
'product as p ON l.fk_product = p.rowid';
2587 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2588 if (is_int($only_type_product)) {
2589 $sql .=
" AND p.fk_product_type = ".((int) $only_type_product);
2591 $sql .=
' ORDER BY l.rang, l.rowid';
2593 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2594 $result = $this->db->query($sql);
2596 $num = $this->db->num_rows($result);
2599 $objp = $this->db->fetch_object($result);
2602 $line->id = $objp->rowid;
2603 $line->rowid = $objp->rowid;
2604 $line->fk_facture = $objp->fk_facture;
2605 $line->label = $objp->custom_label;
2606 $line->desc = $objp->description;
2607 $line->description = $objp->description;
2608 $line->product_type = $objp->product_type;
2609 $line->ref = $objp->product_ref;
2610 $line->product_ref = $objp->product_ref;
2611 $line->libelle = $objp->product_label;
2612 $line->product_label = $objp->product_label;
2613 $line->product_barcode = $objp->product_barcode;
2614 $line->product_desc = $objp->product_desc;
2615 $line->fk_product_type = $objp->fk_product_type;
2616 $line->qty = $objp->qty;
2617 $line->subprice = $objp->subprice;
2618 $line->ref_ext = $objp->ref_ext;
2620 $line->vat_src_code = $objp->vat_src_code;
2621 $line->tva_tx = $objp->tva_tx;
2622 $line->localtax1_tx = $objp->localtax1_tx;
2623 $line->localtax2_tx = $objp->localtax2_tx;
2624 $line->localtax1_type = $objp->localtax1_type;
2625 $line->localtax2_type = $objp->localtax2_type;
2626 $line->remise_percent = $objp->remise_percent;
2627 $line->fk_remise_except = $objp->fk_remise_except;
2628 $line->fk_product = $objp->fk_product;
2629 $line->date_start = $this->db->jdate($objp->date_start);
2630 $line->date_end = $this->db->jdate($objp->date_end);
2631 $line->info_bits = $objp->info_bits;
2632 $line->total_ht = $objp->total_ht;
2633 $line->total_tva = $objp->total_tva;
2634 $line->total_localtax1 = $objp->total_localtax1;
2635 $line->total_localtax2 = $objp->total_localtax2;
2636 $line->total_ttc = $objp->total_ttc;
2638 $line->fk_fournprice = $objp->fk_fournprice;
2639 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2640 $line->pa_ht = $marginInfos[0];
2641 $line->marge_tx = (
string) $marginInfos[1];
2642 $line->marque_tx = (
string) $marginInfos[2];
2643 $line->rang = $objp->rang;
2644 $line->special_code = $objp->special_code;
2645 $line->fk_parent_line = $objp->fk_parent_line;
2646 $line->situation_percent = $objp->situation_percent;
2647 $line->fk_prev_id = $objp->fk_prev_id;
2648 $line->fk_unit = $objp->fk_unit;
2650 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
2652 $line->batch = $objp->batch;
2653 $line->fk_warehouse = $objp->fk_warehouse;
2656 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2659 $line->fk_multicurrency = $objp->fk_multicurrency;
2660 $line->multicurrency_code = $objp->multicurrency_code;
2661 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2662 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2663 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2664 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2666 $line->array_options = array();
2667 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2668 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2669 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2670 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2673 if ($type !==
'separate') {
2674 $rawval = $objp->$key;
2677 if (in_array($type, array(
'date',
'datetime'))) {
2678 $line->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2679 } elseif ($type ==
'password') {
2680 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2681 $line->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2683 $line->array_options[
'options_' . $key] = $rawval;
2686 $line->array_options[
'options_' . $key] = $rawval;
2692 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2693 if (!empty($extrafields->attributes[$this->table_element_line][
'computed'][$key])) {
2694 if (empty(
$conf->disable_compute)) {
2695 global $objectoffield;
2696 $objectoffield = $line;
2697 $line->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element_line][
'computed'][$key], 1, 0,
'2');
2703 if (!$doFetchInOneSqlRequest) {
2705 $line->fetch_optionals();
2709 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2710 $tmpproduct =
new Product($this->db);
2711 $tmpproduct->fetch($objp->fk_product);
2712 $tmpproduct->getMultiLangs();
2714 $line->multilangs = $tmpproduct->multilangs;
2717 $this->lines[$i] = $line;
2721 $this->db->free($result);
2724 $this->error = $this->db->error();
2737 $this->tab_previous_situation_invoice = array();
2738 $this->tab_next_situation_invoice = array();
2740 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2741 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2742 $sql .=
' AND entity = '.((int) $this->entity);
2743 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2744 $sql .=
' ORDER BY situation_counter ASC';
2746 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2747 $result = $this->db->query($sql);
2748 if ($result && $this->db->num_rows($result) > 0) {
2749 while ($objp = $this->db->fetch_object($result)) {
2750 $invoice =
new Facture($this->db);
2751 if ($invoice->fetch($objp->rowid) > 0) {
2752 if ($objp->situation_counter < $this->situation_counter
2753 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2755 $this->tab_previous_situation_invoice[] = $invoice;
2757 $this->tab_next_situation_invoice[] = $invoice;
2778 if (empty($this->
type)) {
2781 if (isset($this->subtype)) {
2782 $this->subtype = (int) $this->subtype;
2784 if (isset($this->
ref)) {
2785 $this->
ref = trim($this->
ref);
2787 if (isset($this->ref_ext)) {
2788 $this->ref_ext = trim($this->ref_ext);
2790 if (!empty($this->ref_customer)) {
2791 $this->ref_customer = trim($this->ref_customer);
2793 if (isset($this->increment)) {
2794 $this->increment = trim($this->increment);
2796 if (isset($this->close_code)) {
2797 $this->close_code = trim($this->close_code);
2799 if (isset($this->close_note)) {
2800 $this->close_note = trim($this->close_note);
2802 if (isset($this->note) || isset($this->note_private)) {
2803 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2805 if (isset($this->note) || isset($this->note_private)) {
2806 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2808 if (isset($this->note_public)) {
2809 $this->note_public = trim($this->note_public);
2811 if (isset($this->model_pdf)) {
2812 $this->model_pdf = trim($this->model_pdf);
2814 if (isset($this->import_key)) {
2815 $this->import_key = trim($this->import_key);
2817 if (isset($this->retained_warranty)) {
2818 $this->retained_warranty = (float) $this->retained_warranty;
2820 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2821 $this->user_creation_id = $this->fk_user_author;
2823 if (!isset($this->user_modification_id) && !empty($user->id)) {
2824 $this->user_modification_id = $user->id;
2826 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2827 $this->user_validation_id = $this->fk_user_valid;
2832 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2833 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2834 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2835 $sql .=
" type=".(isset($this->
type) ? ((int) $this->
type) :
"null").
",";
2836 $sql .=
" subtype=".(isset($this->subtype) ? (int) $this->subtype :
"null").
",";
2837 $sql .=
" ref_client=".(!empty($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2838 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2839 $sql .=
" fk_soc=".(isset($this->socid) ? ((int) $this->socid) :
"null").
",";
2840 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2841 $sql .=
" datef=".(strval($this->
date) !=
'' ?
"'".$this->db->idate($this->
date).
"'" :
'null').
",";
2842 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2843 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2844 $sql .=
" paye=".(isset($this->paye) ? ((int) $this->paye) : 0).
",";
2845 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2846 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2847 $sql .=
" total_tva=".((float) $this->total_tva).
",";
2848 $sql .=
" localtax1=".((float) $this->total_localtax1).
",";
2849 $sql .=
" localtax2=".((float) $this->total_localtax2).
",";
2850 $sql .=
" total_ht=".((float) $this->total_ht).
",";
2851 $sql .=
" total_ttc=".((float) $this->total_ttc).
",";
2852 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2853 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2854 $sql .=
" fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) :
"null").
",";
2855 $sql .=
" fk_user_modif=".(!empty($user->id) ? ((int) $user->id) :
"null").
",";
2856 $sql .=
" fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id :
"null").
",";
2857 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2858 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2859 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2860 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2861 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2862 $sql .=
" note_private = ".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2863 $sql .=
" note_public = ".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2864 $sql .=
" model_pdf = ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2865 $sql .=
" import_key = ".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2866 $sql .=
" module_source = ".(isset($this->module_source) ?
"'".$this->db->escape($this->module_source).
"'" :
"null").
",";
2867 $sql .=
" pos_source = ".(isset($this->pos_source) ?
"'".$this->db->escape($this->pos_source).
"'" :
"null").
",";
2868 $sql .=
" pos_print_counter = ".(int) $this->pos_print_counter.
",";
2869 $sql .=
" situation_cycle_ref = ".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2870 $sql .=
" situation_counter = ".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2871 $sql .=
" situation_final = ".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2872 $sql .=
" retained_warranty = ".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2873 $sql .=
" retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2874 $sql .=
" retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2875 $sql .=
" WHERE rowid = ".((int) $this->
id);
2879 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2880 $resql = $this->db->query($sql);
2883 $this->errors[] =
"Error ".$this->db->lasterror();
2893 if (!$error && !$notrigger) {
2895 $result = $this->call_trigger(
'BILL_MODIFY', $user);
2904 foreach ($this->errors as $errmsg) {
2905 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2906 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2908 $this->db->rollback();
2911 $this->db->commit();
2929 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2930 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2935 $result = $remise->fetch($idremise);
2938 if ($this->socid > 0 && $remise->fk_soc != $this->socid) {
2939 $this->error = $langs->trans(
"ErrorDiscountNotSameCompany");
2940 $this->db->rollback();
2943 if ($remise->fk_facture) {
2944 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2945 $this->db->rollback();
2950 $facligne->fk_facture = $this->id;
2951 $facligne->fk_remise_except = $remise->id;
2952 $facligne->desc = $remise->description;
2953 $facligne->vat_src_code = $remise->vat_src_code;
2954 $facligne->tva_tx = $remise->tva_tx;
2955 $facligne->localtax1_tx = $remise->localtax1_tx;
2956 $facligne->localtax1_type = (int) $remise->localtax1_type;
2957 $facligne->localtax2_tx = $remise->localtax2_tx;
2958 $facligne->localtax2_type = (int) $remise->localtax2_type;
2959 $facligne->subprice = -(float) $remise->total_ht;
2960 $facligne->fk_product = 0;
2962 $facligne->remise_percent = 0;
2963 $facligne->rang = -1;
2964 $facligne->info_bits = 2;
2967 $facligne->rang = 1;
2968 $linecount = count($this->lines);
2969 for ($ii = 1; $ii <= $linecount; $ii++) {
2975 if ($remise->fk_facture_source > 0) {
2976 $srcinvoice =
new Facture($this->db);
2977 $srcinvoice->fetch($remise->fk_facture_source);
2978 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2982 $srclinesofvat = array();
2983 foreach ($srcinvoice->lines as $srcline) {
2985 $srclinesofvat[] = $srcline;
2988 if (count($srclinesofvat) > 0) {
2989 $srcinvoice->lines = $srclinesofvat;
2991 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2992 $facligne->pa_ht = $arraytmp[
'pa_total'];
2993 if ((
float) $arraytmp[
'pv_total'] != 0 &&
price2num($arraytmp[
'pv_total'],
'MT') !=
price2num(abs((
float) $remise->total_ht),
'MT')) {
2994 $facligne->pa_ht = (float)
price2num($arraytmp[
'pa_total'] * abs((
float) $remise->total_ht / (
float) $arraytmp[
'pv_total']),
'MU');
2998 $facligne->total_ht = -(float) $remise->total_ht;
2999 $facligne->total_tva = -(float) $remise->total_tva;
3000 $facligne->total_ttc = -(float) $remise->total_ttc;
3001 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
3002 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
3005 $facligne->fk_multicurrency = $this->fk_multicurrency;
3006 $facligne->multicurrency_code = $this->multicurrency_code;
3007 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
3008 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
3009 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
3010 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
3012 $lineid = $facligne->insert();
3017 $result = $remise->link_to_invoice($lineid, 0);
3019 $this->error = $remise->error;
3020 $this->db->rollback();
3024 $this->db->commit();
3027 $this->error = $facligne->error;
3028 $this->db->rollback();
3032 $this->error = $facligne->error;
3033 $this->db->rollback();
3037 $this->db->rollback();
3059 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3060 if (empty($ref_client)) {
3061 $sql .=
" SET ref_client = NULL";
3063 $sql .=
" SET ref_client = '".$this->db->escape($ref_client).
"'";
3065 $sql .=
" WHERE rowid = ".((int) $this->
id);
3067 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
3068 $resql = $this->db->query($sql);
3070 $this->errors[] = $this->db->error();
3075 $this->ref_client = $ref_client;
3076 $this->ref_customer = $ref_client;
3079 if (!$notrigger && empty($error)) {
3081 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3089 $this->ref_client = $ref_client;
3090 $this->ref_customer = $ref_client;
3092 $this->db->commit();
3095 foreach ($this->errors as $errmsg) {
3096 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
3097 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
3099 $this->db->rollback();
3119 dol_syslog(__METHOD__.
' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3120 if ($this->
status >= self::STATUS_DRAFT) {
3122 $this->demand_reason_id = $inputReasonId;
3126 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3127 $sql .=
" SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId :
'null');
3128 $sql .=
" WHERE rowid = ".((int) $this->
id);
3131 $res = $this->db->query($sql);
3134 $this->error = $this->db->lasterror();
3135 $this->errors[] = $this->error;
3141 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3150 $this->db->commit();
3152 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3153 $this->db->rollback();
3154 dol_syslog(__METHOD__.
' Error : '.$this->errorsToString(), LOG_ERR);
3175 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3177 global $langs,
$conf;
3178 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3182 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
3195 if (!$error && !$notrigger) {
3197 $result = $this->call_trigger(
'BILL_DELETE', $user);
3206 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"categorie_invoice";
3207 $sql .=
" WHERE fk_invoice = ".((int) $this->
id);
3209 $result = $this->db->query($sql);
3212 $this->errors[] = $this->db->lasterror();
3221 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
3235 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
3236 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
3237 $sql .=
' AND fk_facture_line IS NULL';
3238 $resql = $this->db->query($sql);
3242 $list_rowid_det = array();
3243 foreach ($this->lines as $key => $invoiceline) {
3244 $list_rowid_det[] = $invoiceline->id;
3248 if (count($list_rowid_det)) {
3249 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3250 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
3251 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
3253 if (!$this->db->query($sql)) {
3254 $this->error = $this->db->error().
" sql=".$sql;
3255 $this->errors[] = $this->error;
3256 $this->db->rollback();
3263 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
3264 $sql .=
' SET fk_invoice = NULL';
3265 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
3267 if (!$this->db->query($sql)) {
3268 $this->error = $this->db->error().
" sql=".$sql;
3269 $this->errors[] = $this->error;
3270 $this->db->rollback();
3274 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
3275 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
3276 $sql .=
' WHERE invoice_id = '.((int) $rowid);
3278 if (!$this->db->query($sql)) {
3279 $this->error = $this->db->error().
" sql=".$sql;
3280 $this->errors[] = $this->error;
3281 $this->db->rollback();
3287 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3288 $langs->load(
"agenda");
3290 $num = count($this->lines);
3291 for ($i = 0; $i < $num; $i++) {
3292 if ($this->lines[$i]->fk_product > 0) {
3294 $mouvP->origin = &$this;
3295 $mouvP->setOrigin($this->element, $this->
id);
3297 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3298 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3300 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3307 $sql_main_table = MAIN_DB_PREFIX.
'facturedet';
3308 $sql_ef_table = $sql_main_table.
"_extrafields";
3309 $sqlef =
"DELETE FROM ".$sql_ef_table.
" WHERE fk_object IN (SELECT rowid FROM ".$sql_main_table.
" WHERE fk_facture = ".((int) $rowid).
")";
3311 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
3314 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
3316 $resql = $this->db->query($sql);
3324 if ($conf->facture->dir_output && !empty($this->
ref)) {
3325 $dir =
$conf->facture->dir_output.
"/".$ref;
3326 $file =
$conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
3327 if (file_exists($file)) {
3331 $langs->load(
"errors");
3332 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
3333 $this->errors[] = $this->error;
3334 $this->db->rollback();
3338 if (file_exists($dir)) {
3340 $langs->load(
"errors");
3341 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
3342 $this->errors[] = $this->error;
3343 $this->db->rollback();
3349 $this->db->commit();
3352 $this->error = $this->db->lasterror().
" sql=".$sql;
3353 $this->errors[] = $this->error;
3354 $this->db->rollback();
3358 $this->error = $this->db->lasterror().
" sql=".$sql;
3359 $this->errors[] = $this->error;
3360 $this->db->rollback();
3364 $this->db->rollback();
3381 public function set_paid($user, $close_code =
'', $close_note =
'')
3384 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3385 return $this->
setPaid($user, $close_code, $close_note);
3398 public function setPaid($user, $close_code =
'', $close_note =
'')
3402 if ($this->paye != 1 || $this->
status != self::STATUS_CLOSED) {
3407 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3409 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3410 $sql .=
' fk_statut = '.self::STATUS_CLOSED;
3412 $sql .=
', paye = 1';
3415 $sql .=
", close_code = '".$this->db->escape($close_code).
"'";
3418 $sql .=
", close_note = '".$this->db->escape($close_note).
"'";
3420 $sql .=
', fk_user_closing = '.((int) $user->id);
3421 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3422 $sql .=
" WHERE rowid = ".((int) $this->
id);
3424 $resql = $this->db->query($sql);
3427 $result = $this->call_trigger(
'BILL_PAYED', $user);
3434 $this->error = $this->db->lasterror();
3440 $this->db->commit();
3443 $this->db->rollback();
3466 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3484 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3485 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3486 $sql .=
' date_closing=null,';
3487 $sql .=
' fk_user_closing=null';
3488 $sql .=
" WHERE rowid = ".((int) $this->
id);
3490 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3491 $resql = $this->db->query($sql);
3494 $result = $this->call_trigger(
'BILL_UNPAYED', $user);
3501 $this->error = $this->db->error();
3506 $this->db->commit();
3509 $this->db->rollback();
3531 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3532 return $this->
setCanceled($user, $close_code, $close_note);
3545 public function setCanceled($user, $close_code =
'', $close_note =
'')
3547 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3552 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3553 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3555 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3558 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3560 $sql .=
', fk_user_closing = '.((int) $user->id);
3561 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3562 $sql .=
" WHERE rowid = ".((int) $this->
id);
3564 $resql = $this->db->query($sql);
3568 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3569 $sql .=
' SET fk_facture = NULL';
3570 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3572 $resql = $this->db->query($sql);
3575 $result = $this->call_trigger(
'BILL_CANCEL', $user);
3577 $this->db->rollback();
3582 $this->db->commit();
3585 $this->error = $this->db->error().
" sql=".$sql;
3586 $this->db->rollback();
3590 $this->error = $this->db->error().
" sql=".$sql;
3591 $this->db->rollback();
3608 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3611 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3613 $productStatic =
null;
3614 $warehouseStatic =
null;
3615 $productbatch =
null;
3616 if ($batch_rule > 0) {
3617 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3618 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3619 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3620 $productStatic =
new Product($this->db);
3621 $warehouseStatic =
new Entrepot($this->db);
3628 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3635 if ($this->
status != self::STATUS_DRAFT) {
3636 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3639 if (count($this->lines) <= 0) {
3640 $langs->load(
"errors");
3641 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3645 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3646 $this->error =
'Permission denied';
3647 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3650 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3658 if (!$last_of_type[0]) {
3665 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3666 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'TVA_INTRA',
'ACCOUNTANCY_CODE_CUSTOMER');
3667 foreach ($array_to_check as $key) {
3668 $keymin = strtolower($key);
3669 if (!property_exists($this->thirdparty, $keymin)) {
3672 $vallabel = $this->thirdparty->$keymin;
3674 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3676 if ($this->thirdparty->isACompany()) {
3678 if (
$mysoc->country_id > 0 && $this->thirdparty->country_id ==
$mysoc->country_id) {
3679 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3681 $langs->load(
"errors");
3682 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3683 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3689 if ($key ==
'EMAIL') {
3692 $langs->load(
"errors");
3693 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3694 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3698 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3700 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3701 $langs->load(
"errors");
3702 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3703 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3707 if ($key ==
'TVA_INTRA') {
3710 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3711 $langs->load(
"errors");
3712 $this->error = $langs->trans(
'ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3713 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3716 } elseif (
getDolGlobalString(
'SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3717 $langs->load(
"errors");
3718 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3719 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3728 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3729 foreach ($array_to_check as $key => $val) {
3730 $keymin = strtolower($key);
3731 $vallabel = $this->$keymin;
3734 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3736 $langs->load(
"errors");
3738 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3745 if ($this->
type == self::TYPE_REPLACEMENT) {
3747 if ($this->fk_facture_source <= 0) {
3748 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3749 $this->db->rollback();
3754 $facreplaced =
new Facture($this->db);
3755 $result = $facreplaced->fetch($this->fk_facture_source);
3757 $this->error = $langs->trans(
"ErrorBadInvoice");
3758 $this->db->rollback();
3763 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3764 if ($idreplacement && $idreplacement != $this->
id) {
3765 $facreplacement =
new Facture($this->db);
3766 $facreplacement->fetch($idreplacement);
3767 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3768 $this->db->rollback();
3772 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3774 $this->error = $facreplaced->error;
3775 $this->db->rollback();
3781 if ($force_number) {
3782 $num = $force_number;
3783 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3796 $this->oldref = $this->ref;
3804 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3805 $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).
"'";
3807 $sql .=
", datef='".$this->db->idate($this->
date).
"'";
3808 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3810 $sql .=
" WHERE rowid = ".((int) $this->
id);
3812 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3813 $resql = $this->db->query($sql);
3815 $this->error = $this->db->lasterror();
3822 $result = $this->thirdparty->setAsCustomer();
3826 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3827 $langs->load(
"agenda");
3830 $cpt = count($this->lines);
3831 for ($i = 0; $i < $cpt; $i++) {
3832 if ($this->lines[$i]->fk_product > 0) {
3834 $mouvP->origin = &$this;
3835 $mouvP->setOrigin($this->element, $this->
id);
3838 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3841 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3850 $is_batch_line =
false;
3851 if ($batch_rule > 0) {
3852 $productStatic->fetch($this->lines[$i]->fk_product);
3853 if ($productStatic->hasbatch() && is_object($productbatch)) {
3854 $is_batch_line =
true;
3855 $product_qty_remain = $this->lines[$i]->qty;
3861 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3862 $sortorder =
'ASC,ASC,ASC,ASC';
3865 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 :
null), $sortfield, $sortorder);
3866 if (!is_array($resBatchList)) {
3868 $this->error = $this->db->lasterror();
3872 $batchList = $resBatchList;
3873 if (empty($batchList)) {
3875 $langs->load(
'errors');
3876 $warehouseStatic->fetch($idwarehouse);
3877 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3878 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3881 foreach ($batchList as $batch) {
3882 if ($batch->qty <= 0) {
3887 if ($batch->qty >= $product_qty_remain) {
3888 $product_batch_qty = $product_qty_remain;
3891 $product_batch_qty = $batch->qty;
3893 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3900 $product_qty_remain -= $product_batch_qty;
3902 if ($product_qty_remain <= 0) {
3907 if (!$error && $product_qty_remain > 0) {
3910 $langs->load(
'errors');
3911 $warehouseStatic->fetch($idwarehouse);
3912 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3913 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3916 $batch = $batchList[0];
3917 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3928 if (!$is_batch_line) {
3929 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3944 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3945 $invoice_situation =
new Facture($this->db);
3946 $result = $invoice_situation->fetch($this->fk_facture_source);
3947 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3948 $invoice_situation->situation_final = 0;
3950 $result = $invoice_situation->setFinal($user, 1);
3953 $this->error = $invoice_situation->error;
3954 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3960 if (!$error && !$notrigger) {
3962 $result = $this->call_trigger(
'BILL_VALIDATE', $user);
3971 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3973 $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).
"'";
3974 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3975 $resql = $this->db->query($sql);
3978 $this->error = $this->db->lasterror();
3980 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3981 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3982 $resql = $this->db->query($sql);
3985 $this->error = $this->db->lasterror();
3992 if (!$resupdatenext) {
4002 $this->date_validation = $now;
4007 $nboflines = count($this->lines);
4008 while (($i < $nboflines) && $final) {
4009 $line = $this->lines[$i];
4010 '@phan-var-force FactureLigne $line';
4012 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
4013 $current_progress = (float) $line->situation_percent;
4014 $full_progress = $previousprogress + $current_progress;
4015 $final = ($full_progress == 100);
4017 $final = ($line->situation_percent == 100);
4023 if ($this->situation_final) {
4025 $this->situation_final = 0;
4029 if (!$this->situation_final) {
4031 $this->situation_final = 1;
4041 if (!$error && preg_match(
'/^[\(]?PROV/i', $this->oldref)) {
4045 $dirsource =
$conf->facture->dir_output.
'/'.$oldref;
4046 $dirdest =
$conf->facture->dir_output.
'/'.$newref;
4047 if (!$error && file_exists($dirsource)) {
4048 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
4050 if (@rename($dirsource, $dirdest)) {
4053 $listoffiles =
dol_dir_list(
$conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
4054 foreach ($listoffiles as $fileentry) {
4055 $dirsource = $fileentry[
'name'];
4056 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
4057 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
4058 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
4059 @rename($dirsource, $dirdest);
4066 $this->db->commit();
4069 $this->db->rollback();
4082 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4083 $is_last = $next_invoice->is_last_in_cycle();
4085 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4086 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4090 foreach ($next_invoice->lines as $line) {
4091 '@phan-var-force FactureLigne $line';
4092 $result = $next_invoice->updateline(
4097 $line->remise_percent,
4101 $line->localtax1_tx,
4102 $line->localtax2_tx,
4105 $line->product_type,
4106 $line->fk_parent_line,
4108 $line->fk_fournprice,
4111 $line->special_code,
4112 $line->array_options,
4113 $line->situation_percent,
4118 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4143 if ($this->
status == self::STATUS_DRAFT) {
4144 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
4152 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4153 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
4154 $sql .=
" WHERE rowid = ".((int) $this->
id);
4156 $result = $this->db->query($sql);
4159 $this->oldcopy = clone $this;
4164 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
4165 $langs->load(
"agenda");
4167 $num = count($this->lines);
4168 for ($i = 0; $i < $num; $i++) {
4169 if ($this->lines[$i]->fk_product > 0) {
4171 $mouvP->origin = &$this;
4172 $mouvP->setOrigin($this->element, $this->
id);
4174 if ($this->
type == self::TYPE_CREDIT_NOTE) {
4175 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->transnoentitiesnoconv(
"InvoiceBackToDraftInDolibarr", $this->ref));
4177 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->transnoentitiesnoconv(
"InvoiceBackToDraftInDolibarr", $this->ref));
4182 dol_syslog(__METHOD__.
" stock movement failed for line ".$i.
": ".$mouvP->error, LOG_ERR);
4189 $old_statut = $this->status;
4194 $result = $this->call_trigger(
'BILL_UNVALIDATE', $user);
4197 $this->statut = $old_statut;
4198 $this->
status = $old_statut;
4202 $this->db->rollback();
4207 $this->db->commit();
4210 $this->db->rollback();
4214 $this->error = $this->db->error();
4215 $this->db->rollback();
4269 $remise_percent = 0,
4272 $fk_code_ventilation = 0,
4274 $fk_remise_except = 0,
4275 $price_base_type =
'HT',
4282 $fk_parent_line = 0,
4283 $fk_fournprice =
null,
4286 $array_options = array(),
4287 $situation_percent = 100,
4292 $noupdateafterinsertline = 0
4296 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4302 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);
4304 if ($this->
status == self::STATUS_DRAFT) {
4305 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4308 if (empty($remise_percent)) {
4309 $remise_percent = 0;
4314 if (empty($info_bits)) {
4320 if (empty($fk_code_ventilation)) {
4321 $fk_code_ventilation = 0;
4323 if (empty($txtva)) {
4326 if (empty($txlocaltax1)) {
4329 if (empty($txlocaltax2)) {
4332 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4333 $fk_parent_line = 0;
4335 if (empty($fk_prev_id)) {
4336 $fk_prev_id =
'null';
4339 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4342 $situation_percent = 0;
4344 $situation_percent = 100;
4348 if (empty($ref_ext)) {
4352 $remise_percent = (float)
price2num($remise_percent);
4356 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4359 if (strpos((
string) $txtva,
'*') !==
false) {
4362 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4365 $txlocaltax1 = (float)
price2num($txlocaltax1);
4366 $txlocaltax2 = (float)
price2num($txlocaltax2);
4368 if ($price_base_type ==
'HT') {
4380 $langs->load(
"errors");
4381 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4387 $product_type = $type;
4388 if (!empty($fk_product) && $fk_product > 0) {
4389 $product =
new Product($this->db);
4390 $result = $product->fetch($fk_product);
4391 $product_type = $product->type;
4393 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4395 $productChildrenNb = 0;
4397 $productChildrenNb = $product->hasFatherOrChild(1);
4399 if ($productChildrenNb > 0) {
4401 $product_stock =
null;
4402 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4403 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4404 if ($product_stock ===
null) {
4405 $product_stock = $componentStockWarehouse->real;
4407 $product_stock = min($product_stock, $componentStockWarehouse->real);
4410 if ($product_stock ===
null) {
4414 $product_stock = $product->stock_reel;
4417 if ($product_stock < $qty) {
4418 $langs->load(
"errors");
4419 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4420 $this->db->rollback();
4426 $tmpproduct =
new Product($this->db);
4427 $result = $tmpproduct->fetch($fk_product);
4429 if ($newqty != $qty) {
4431 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4441 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4442 $vat_src_code = $reg[1];
4443 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4450 $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);
4452 $total_ht = $tabprice[0];
4453 $total_tva = $tabprice[1];
4454 $total_ttc = $tabprice[2];
4455 $total_localtax1 = $tabprice[9];
4456 $total_localtax2 = $tabprice[10];
4457 $pu_ht = $tabprice[3];
4460 $multicurrency_total_ht = $tabprice[16];
4461 $multicurrency_total_tva = $tabprice[17];
4462 $multicurrency_total_ttc = $tabprice[18];
4463 $pu_ht_devise = $tabprice[19];
4467 if (empty($ranktouse) || $ranktouse == -1) {
4468 $rangmax = $this->
line_max($fk_parent_line);
4469 $ranktouse = $rangmax + 1;
4474 $apply_abs_price_on_credit_note =
false;
4476 $apply_abs_price_on_credit_note =
true;
4482 $this->line->context = $this->context;
4484 $this->line->fk_facture = $this->id;
4485 $this->line->label = $label;
4486 $this->line->desc = $desc;
4487 $this->line->ref_ext = $ref_ext;
4489 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : (float) $qty);
4490 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4492 $this->line->vat_src_code = $vat_src_code;
4493 $this->line->tva_tx = $txtva;
4494 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4495 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4496 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4497 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4499 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4500 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4501 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4502 $this->line->total_localtax1 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax1) : (float) $total_localtax1);
4503 $this->line->total_localtax2 = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_localtax2) : (float) $total_localtax2);
4505 $this->line->fk_product = $fk_product;
4506 $this->line->product_type = $product_type;
4507 $this->line->remise_percent = $remise_percent;
4509 $this->line->date_end = $date_end;
4510 $this->line->fk_code_ventilation = $fk_code_ventilation;
4511 $this->line->rang = $ranktouse;
4512 $this->line->info_bits = $info_bits;
4513 $this->line->fk_remise_except = $fk_remise_except;
4515 $this->line->special_code = $special_code;
4516 $this->line->fk_parent_line = $fk_parent_line;
4518 $this->line->origin = $origin;
4519 $this->line->origin_id = $origin_id;
4521 $this->line->situation_percent = $situation_percent;
4522 $this->line->fk_prev_id = $fk_prev_id;
4523 $this->line->fk_unit = $fk_unit;
4526 $this->line->fk_fournprice = $fk_fournprice;
4527 $this->line->pa_ht = $pa_ht;
4530 $this->line->fk_multicurrency = $this->fk_multicurrency;
4531 $this->line->multicurrency_code = $this->multicurrency_code;
4532 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4534 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4535 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4536 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4538 if (is_array($array_options) && count($array_options) > 0) {
4539 $this->line->array_options = $array_options;
4542 $result = $this->line->insert();
4545 if (empty($noupdateafterinsertline)) {
4549 if (!isset($this->context[
'createfromclone'])) {
4550 if (!empty($fk_parent_line)) {
4553 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4555 $linecount = count($this->lines);
4556 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4561 $this->lines[] = $this->line;
4564 foreach ($this->lines as $tmpline) {
4565 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
4566 $this->line->extraparams = $tmpline->extraparams;
4567 $this->line->setExtraParameters();
4573 $this->db->commit();
4574 return $this->line->id;
4576 $this->error = $this->db->lasterror();
4577 $this->db->rollback();
4581 $this->error = $this->line->error;
4582 $this->errors = $this->line->errors;
4583 $this->db->rollback();
4587 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4588 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4624 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)
4629 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4635 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4638 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4642 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);
4644 if ($this->
status == self::STATUS_DRAFT) {
4647 if (!$this->error) {
4648 $this->error = $langs->trans(
'invoiceLineProgressError');
4655 $langs->load(
"errors");
4656 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4666 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4667 $fk_parent_line = 0;
4669 if (empty($special_code) || $special_code == 3) {
4672 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
4675 $situation_percent = 0;
4677 $situation_percent = 100;
4680 if (empty($ref_ext)) {
4684 $remise_percent = (float)
price2num($remise_percent);
4688 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4691 if (strpos((
string) $txtva,
'*') !==
false) {
4694 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4697 $txlocaltax1 = (float)
price2num($txlocaltax1);
4698 $txlocaltax2 = (float)
price2num($txlocaltax2);
4714 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4715 $vat_src_code = $reg[1];
4716 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4723 if ($tmpline->fetch($rowid) > 0) {
4725 if ($newqty != $qty) {
4727 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4732 $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);
4734 $total_ht = $tabprice[0];
4735 $total_tva = $tabprice[1];
4736 $total_ttc = $tabprice[2];
4737 $total_localtax1 = $tabprice[9];
4738 $total_localtax2 = $tabprice[10];
4739 $pu_ht = $tabprice[3];
4740 $pu_tva = $tabprice[4];
4741 $pu_ttc = $tabprice[5];
4744 $multicurrency_total_ht = $tabprice[16];
4745 $multicurrency_total_tva = $tabprice[17];
4746 $multicurrency_total_ttc = $tabprice[18];
4747 $pu_ht_devise = $tabprice[19];
4752 if ($remise_percent > 0) {
4753 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4754 $price = ((float) $pu - $remise);
4760 $line->fetch($rowid);
4761 $line->fetch_optionals();
4763 if (!empty($line->fk_product)) {
4764 $product =
new Product($this->db);
4765 $result = $product->fetch($line->fk_product);
4766 $product_type = $product->type;
4768 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4770 $productChildrenNb = 0;
4772 $productChildrenNb = $product->hasFatherOrChild(1);
4774 if ($productChildrenNb > 0) {
4776 $product_stock =
null;
4777 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4778 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4779 if ($product_stock ===
null) {
4780 $product_stock = $componentStockWarehouse->real;
4782 $product_stock = min($product_stock, $componentStockWarehouse->real);
4785 if ($product_stock ===
null) {
4789 $product_stock = $product->stock_reel;
4792 if ($product_stock < $qty) {
4793 $langs->load(
"errors");
4794 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', (
string) $product->ref);
4795 $this->db->rollback();
4801 $staticline = clone $line;
4803 $line->oldline = $staticline;
4804 $this->line = $line;
4805 $this->line->context = $this->context;
4806 $this->line->rang = $rang;
4809 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4810 $rangmax = $this->
line_max($fk_parent_line);
4811 $this->line->rang = $rangmax + 1;
4813 $apply_abs_price_on_credit_note =
false;
4815 $apply_abs_price_on_credit_note =
true;
4820 $this->line->id = $rowid;
4821 $this->line->rowid = $rowid;
4822 $this->line->label = $label;
4823 $this->line->desc = $desc;
4824 $this->line->ref_ext = $ref_ext;
4825 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4827 $this->line->vat_src_code = $vat_src_code;
4828 $this->line->tva_tx = $txtva;
4829 $this->line->localtax1_tx = $txlocaltax1;
4830 $this->line->localtax2_tx = $txlocaltax2;
4831 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4832 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4834 $this->line->remise_percent = $remise_percent;
4835 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4837 $this->line->date_end = $date_end;
4838 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4839 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4840 $this->line->total_localtax1 = (float) $total_localtax1;
4841 $this->line->total_localtax2 = (float) $total_localtax2;
4842 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4843 $this->line->info_bits = $info_bits;
4844 $this->line->special_code = $special_code;
4845 $this->line->product_type = $type;
4846 $this->line->fk_parent_line = $fk_parent_line;
4847 $this->line->skip_update_total = $skip_update_total;
4848 $this->line->situation_percent = $situation_percent;
4849 $this->line->fk_unit = $fk_unit;
4851 $this->line->fk_fournprice = $fk_fournprice;
4852 $this->line->pa_ht = $pa_ht;
4855 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4856 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4857 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4858 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4860 if (is_array($array_options) && count($array_options) > 0) {
4862 foreach ($array_options as $key => $value) {
4863 $this->line->array_options[$key] = $array_options[$key];
4867 $result = $this->line->update($user, $notrigger);
4870 if (!empty($fk_parent_line)) {
4876 $this->db->commit();
4879 $this->error = $this->line->error;
4880 $this->db->rollback();
4884 $this->error =
"Invoice statut makes operation forbidden";
4898 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4899 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4900 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4902 $result = $this->db->query($sql);
4904 $this->error = $this->db->error();
4908 $obj = $this->db->fetch_object($result);
4910 if ($obj ===
null) {
4913 return ($situation_percent < $obj->situation_percent);
4932 if (($line->info_bits & 2) == 2) {
4936 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4939 if ($percent > 100) {
4943 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4944 $current_progress = $percent - $previous_progress;
4945 $line->situation_percent = $current_progress;
4946 $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);
4948 $line->situation_percent = $percent;
4949 $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);
4951 $line->total_ht = (float) $tabprice[0];
4952 $line->total_tva = (float) $tabprice[1];
4953 $line->total_ttc = (float) $tabprice[2];
4954 $line->total_localtax1 = (float) $tabprice[9];
4955 $line->total_localtax2 = (float) $tabprice[10];
4956 $line->multicurrency_total_ht = (float) $tabprice[16];
4957 $line->multicurrency_total_tva = (float) $tabprice[17];
4958 $line->multicurrency_total_ttc = (float) $tabprice[18];
4959 $line->update($user);
4962 if ($update_price) {
4978 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4980 if ($this->
status != self::STATUS_DRAFT) {
4981 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4987 $line->context = $this->context;
4990 $result = $line->fetch($rowid);
4991 if (!($result > 0)) {
4999 if ($id > 0 && (
int) $line->fk_facture !== (
int) $id) {
5000 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
5007 $staticline = clone $line;
5008 $line->oldline = $staticline;
5010 if ($line->delete($user) > 0) {
5014 $this->db->commit();
5017 $this->db->rollback();
5018 $this->error = $this->db->lasterror();
5022 $this->db->rollback();
5023 $this->error = $line->error;
5042 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
5044 return $this->
setDiscount($user, $remise, $notrigger);
5058 if (empty($remise)) {
5062 if ($user->hasRight(
'facture',
'creer')) {
5063 $remise = (float)
price2num($remise, 2);
5069 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
5070 $sql .=
" SET remise_percent = ".((float) $remise);
5071 $sql .=
" WHERE rowid = ".((int) $this->
id);
5072 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
5075 $resql = $this->db->query($sql);
5077 $this->errors[] = $this->db->error();
5081 if (!$notrigger && empty($error)) {
5083 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5091 $this->remise_percent = $remise;
5094 $this->db->commit();
5097 foreach ($this->errors as $errmsg) {
5098 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5099 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5101 $this->db->rollback();
5122 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
5123 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5136 global
$conf, $langs;
5138 if ($this->module_source ==
'takepos') {
5139 $langs->load(
'cashdesk');
5141 $moduleName =
'takepos';
5142 $moduleSourceName =
'Takepos';
5143 $addonConstName =
'TAKEPOS_REF_ADDON';
5147 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
5152 $langs->load(
'bills');
5154 $moduleName =
'facture';
5155 $moduleSourceName =
'Invoice';
5156 $addonConstName =
'FACTURE_ADDON';
5160 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5162 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5164 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
5170 if (!empty($addon)) {
5171 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
5175 $file = $addon.
'.php';
5176 $classname = $addon;
5180 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
5181 foreach ($dirmodels as $reldir) {
5182 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
5185 if (is_file($dir.$file) && is_readable($dir.$file)) {
5186 $mybool = ((bool) include_once $dir.$file) || $mybool;
5192 $file = $addon.
'/'.$addon.
'.modules.php';
5193 $classname =
'mod_'.$moduleName.
'_'.$addon;
5194 $classname = preg_replace(
'/\-.*$/',
'', $classname);
5196 foreach (
$conf->file->dol_document_root as $dirroot) {
5197 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
5200 if (is_file($dir.$file) && is_readable($dir.$file)) {
5201 $mybool = (include_once $dir.$file) || $mybool;
5211 $obj =
new $classname();
5212 '@phan-var-force ModeleNumRefFactures $obj';
5214 $numref = $obj->getNextValue($soc, $this, $mode);
5221 if ($mode !=
'last' && !$numref) {
5222 $this->error = $obj->error;
5228 $langs->load(
'errors');
5229 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5242 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5243 $sql .=
' date_closing as dateclosing,';
5244 $sql .=
' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5245 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
5246 $sql .=
' WHERE c.rowid = '.((int) $id);
5248 $result = $this->db->query($sql);
5250 if ($this->db->num_rows($result)) {
5251 $obj = $this->db->fetch_object($result);
5253 $this->
id = $obj->rowid;
5254 $this->user_creation_id = $obj->fk_user_author;
5255 $this->user_modification_id = $obj->fk_user_modif;
5256 $this->user_validation_id = $obj->fk_user_valid;
5257 $this->user_closing_id = $obj->fk_user_closing;
5259 $this->date_creation = $this->db->jdate($obj->datec);
5260 $this->date_modification = $this->db->jdate($obj->datem);
5261 $this->date_validation = $this->db->jdate($obj->datev);
5262 $this->date_closing = $this->db->jdate($obj->dateclosing);
5264 $this->db->free($result);
5285 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
5292 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
5293 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
5294 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
5295 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5296 $sql .=
" AND f.fk_soc = s.rowid";
5298 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
5300 if (is_object($excluser)) {
5301 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
5305 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5306 $search_sale = $user->id;
5309 if ($search_sale && $search_sale !=
'-1') {
5310 if ($search_sale == -2) {
5311 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5312 } elseif ($search_sale > 0) {
5313 $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).
")";
5318 $sql .=
" AND f.fk_soc = ".((int) $socid);
5320 $sql .= $this->db->order($sortfield, $sortorder);
5321 $sql .= $this->db->plimit($limit, $offset);
5323 $result = $this->db->query($sql);
5325 $numc = $this->db->num_rows($result);
5328 while ($i < $numc) {
5329 $obj = $this->db->fetch_object($result);
5331 if ($shortlist == 1) {
5332 $ga[$obj->fid] = $obj->ref;
5333 } elseif ($shortlist == 2) {
5334 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
5336 $ga[$i][
'id'] = $obj->fid;
5337 $ga[$i][
'ref'] = $obj->ref;
5338 $ga[$i][
'name'] = $obj->name;
5367 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5368 $sql .=
" ff.rowid as rowidnext";
5370 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5371 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5372 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
5373 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
5374 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5375 $sql .=
" AND f.paye = 0";
5376 $sql .=
" AND pf.fk_paiement IS NULL";
5377 $sql .=
" AND ff.fk_statut IS NULL";
5379 $sql .=
" AND f.fk_soc = ".((int) $socid);
5382 $sql .=
" ORDER BY f.ref";
5384 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
5385 $resql = $this->db->query($sql);
5387 while ($obj = $this->db->fetch_object($resql)) {
5388 $return[$obj->rowid] = array(
5389 'id' => $obj->rowid,
5391 'status' => $obj->status,
5392 'paid' => $obj->paid,
5399 $this->error = $this->db->error();
5423 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
5424 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5425 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5426 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
5427 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5428 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5432 $sql .=
" AND ff.type IS NULL";
5433 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
5437 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
5438 $sql .=
'(SELECT MAX(fs.rowid)';
5439 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
5440 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
5441 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
5442 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5444 $sql .=
" AND fs.fk_soc = ".((int) $socid);
5446 $sql .=
" GROUP BY fs.situation_cycle_ref)";
5449 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
5453 $sql .=
" AND f.fk_soc = ".((int) $socid);
5456 if (
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5457 $sql .=
" ORDER BY CASE WHEN f.rowid = ".((int)
GETPOST(
'fac_avoir')).
" THEN 0 ELSE 1 END, f.ref";
5459 $sql .= $this->db->plimit(
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5461 $sql .=
" ORDER BY f.ref";
5464 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
5465 $resql = $this->db->query($sql);
5467 while ($obj = $this->db->fetch_object($resql)) {
5469 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5472 if ($obj->fk_statut == self::STATUS_CLOSED) {
5477 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5478 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
5484 $this->error = $this->db->error();
5500 global
$conf, $langs;
5502 $sanitizedclause =
" WHERE";
5504 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5505 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5506 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5507 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5508 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5509 $sanitizedclause =
" AND";
5511 $sql .= $sanitizedclause.
" f.paye=0";
5512 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5513 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5515 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5518 $resql = $this->db->query($sql);
5520 $langs->load(
"bills");
5523 $response->warning_delay =
getWarningDelay(
'invoice',
'client') / 60 / 60 / 24;
5524 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5525 $response->labelShort = $langs->trans(
"Unpaid");
5526 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5529 $generic_facture =
new Facture($this->db);
5531 while ($obj = $this->db->fetch_object($resql)) {
5532 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5533 $generic_facture->statut = $obj->status;
5534 $generic_facture->status = $obj->status;
5536 $response->nbtodo++;
5537 $response->total += $obj->total_ht;
5539 if ($generic_facture->hasDelay()) {
5540 $response->nbtodolate++;
5541 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5545 $this->db->free($resql);
5549 $this->error = $this->db->error();
5588 global
$conf, $langs, $user;
5592 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5597 $sql =
"SELECT rowid";
5598 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5599 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5600 $sql .= $this->db->plimit(100);
5602 $resql = $this->db->query($sql);
5604 $num_prods = $this->db->num_rows($resql);
5606 while ($i < $num_prods) {
5608 $row = $this->db->fetch_row($resql);
5609 $prodids[$i] = $row[0];
5613 if (empty($num_prods)) {
5615 $prodids[$num_prods] = 1;
5620 $this->entity =
$conf->entity;
5621 $this->
ref =
'SPECIMEN';
5622 $this->specimen = 1;
5624 $this->
date = $nownotime;
5625 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5626 $this->cond_reglement_id = 1;
5627 $this->cond_reglement_code =
'RECEP';
5629 $this->mode_reglement_id = 0;
5630 $this->mode_reglement_code =
'';
5632 $this->note_public =
'This is a comment (public)';
5633 $this->note_private =
'This is a comment (private)';
5635 $this->user_creation_id = $user->id;
5637 $this->multicurrency_tx = 1;
5638 $this->multicurrency_code =
$conf->currency;
5640 $this->fk_incoterms = 0;
5641 $this->location_incoterms =
'';
5643 $this->pos_print_counter = 0;
5644 $this->email_sent_counter = 0;
5648 if (empty($option) || $option !=
'nolines') {
5652 while ($xnbp < $nbp) {
5654 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5656 $line->subprice = 100;
5657 $line->tva_tx = 19.6;
5658 $line->localtax1_tx = 0;
5659 $line->localtax2_tx = 0;
5660 $line->remise_percent = 0;
5661 if ($xnbp == 1 && $option !=
'takepos' && $option !=
'nonegativeup') {
5662 $prodid = mt_rand(1, $num_prods);
5663 if (isset($prodids[$prodid])) {
5664 $line->fk_product = $prodids[$prodid];
5667 $line->total_ht = -100;
5668 $line->total_ttc = -119.6;
5669 $line->total_tva = -19.6;
5670 $line->multicurrency_total_ht = -200;
5671 $line->multicurrency_total_ttc = -239.2;
5672 $line->multicurrency_total_tva = -39.2;
5673 } elseif ($xnbp == 2 && $option !=
'takepos' && $option !=
'nonegativeup') {
5674 $line->subprice = -100;
5675 $line->total_ht = -100;
5676 $line->total_ttc = -119.6;
5677 $line->total_tva = -19.6;
5678 $line->remise_percent = 0;
5679 $line->multicurrency_total_ht = -200;
5680 $line->multicurrency_total_ttc = -239.2;
5681 $line->multicurrency_total_tva = -39.2;
5682 } elseif ($xnbp == 3) {
5683 $prodid = mt_rand(1, $num_prods);
5684 if (isset($prodids[$prodid])) {
5685 $line->fk_product = $prodids[$prodid];
5687 $line->total_ht = 50;
5688 $line->total_ttc = 59.8;
5689 $line->total_tva = 9.8;
5690 $line->multicurrency_total_ht = 100;
5691 $line->multicurrency_total_ttc = 119.6;
5692 $line->multicurrency_total_tva = 19.6;
5693 $line->remise_percent = 50;
5695 $prodid = mt_rand(1, $num_prods);
5696 if (isset($prodids[$prodid])) {
5697 $line->fk_product = $prodids[$prodid];
5699 $line->total_ht = 100;
5700 $line->total_ttc = 119.6;
5701 $line->total_tva = 19.6;
5702 $line->multicurrency_total_ht = 200;
5703 $line->multicurrency_total_ttc = 239.2;
5704 $line->multicurrency_total_tva = 39.2;
5705 $line->remise_percent = 0;
5708 $this->lines[$xnbp] = $line;
5711 $this->total_ht += $line->total_ht;
5712 $this->total_tva += $line->total_tva;
5713 $this->total_ttc += $line->total_ttc;
5715 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5716 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5717 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5721 $this->revenuestamp = 0;
5724 if ($option !=
'takepos') {
5726 $line->desc = $langs->trans(
"Description").
" (offered line)";
5728 $line->subprice = 100;
5729 $line->tva_tx = 19.6;
5730 $line->localtax1_tx = 0;
5731 $line->localtax2_tx = 0;
5732 $line->remise_percent = 100;
5733 $line->total_ht = 0;
5734 $line->total_ttc = 0;
5735 $line->total_tva = 0;
5736 $line->multicurrency_total_ht = 0;
5737 $line->multicurrency_total_ttc = 0;
5738 $line->multicurrency_total_tva = 0;
5739 $prodid = mt_rand(1, $num_prods);
5740 if (isset($prodids[$prodid])) {
5741 $line->fk_product = $prodids[$prodid];
5744 $this->lines[$xnbp] = $line;
5761 $this->nb = array();
5763 $sanitizedclause =
"WHERE";
5765 $sql =
"SELECT count(f.rowid) as nb";
5766 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5767 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5768 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5769 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5770 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5771 $sanitizedclause =
"AND";
5773 $sql .=
" ".$sanitizedclause.
" f.entity IN (".
getEntity(
'invoice').
")";
5775 $resql = $this->db->query($sql);
5777 while ($obj = $this->db->fetch_object($resql)) {
5778 $this->nb[
"invoices"] = $obj->nb;
5780 $this->db->free($resql);
5784 $this->error = $this->db->error();
5810 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5812 $outputlangs->loadLangs(array(
"bills",
"products"));
5816 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5818 if (!empty($this->model_pdf)) {
5819 $modele = $this->model_pdf;
5827 $modelpath =
"core/modules/facture/doc/";
5829 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5839 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5840 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5841 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5843 $resql = $this->db->query($sql);
5845 if ($this->db->num_rows($resql) > 0) {
5847 $obj = $this->db->fetch_object($resql);
5849 $ref = (int) $obj->maxsituationref;
5855 $this->db->free($resql);
5858 $this->error = $this->db->lasterror();
5859 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5873 return ($this->situation_counter == 1);
5887 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5888 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5889 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5890 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5891 $resql = $this->db->query($sql);
5893 if ($resql && $this->db->num_rows($resql) > 0) {
5894 while ($row = $this->db->fetch_object($resql)) {
5896 $situation =
new Facture($this->db);
5897 $situation->fetch($id);
5898 $res[] = $situation;
5901 $this->error = $this->db->error();
5902 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5922 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5925 $resql = $this->db->query($sql);
5927 $this->errors[] = $this->db->error();
5931 if (!$notrigger && empty($error)) {
5933 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5941 $this->db->commit();
5944 foreach ($this->errors as $errmsg) {
5945 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5946 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5948 $this->db->rollback();
5964 if (!empty($this->situation_cycle_ref)) {
5966 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5967 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5968 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5969 $resql = $this->db->query($sql);
5971 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5972 $last = $res[
'max(situation_counter)'];
5973 return ($last == $this->situation_counter);
5975 $this->error = $this->db->lasterror();
5976 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6034 $hasDelay = $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'));
6035 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
6037 $totalpaid = (float) $totalpaid;
6039 if ($totalpaid >= 0 && $retainedWarrantyAmount >= 0) {
6040 if (($totalpaid < $this->total_ttc - $retainedWarrantyAmount) && $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'))) {
6042 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now -
getWarningDelay(
'invoice',
'client'))) {
6060 return $this->situation_cycle_ref;
6073 $displayWarranty =
false;
6074 if (!empty($this->retained_warranty)) {
6075 $displayWarranty =
true;
6079 $displayWarranty =
false;
6080 if (!empty($this->situation_final)) {
6081 $displayWarranty =
true;
6084 $displayWarranty =
true;
6086 foreach ($this->lines as $i => $line) {
6087 if ($line->product_type < 2 && $line->situation_percent < 100) {
6088 $displayWarranty =
false;
6096 return $displayWarranty;
6107 if (empty($this->retained_warranty)) {
6111 $retainedWarrantyAmount = 0;
6115 $displayWarranty =
true;
6117 if (!empty($this->lines)) {
6118 foreach ($this->lines as $i => $line) {
6119 if ($line->product_type < 2 && $line->situation_percent < 100) {
6120 $displayWarranty =
false;
6126 if ($displayWarranty && !empty($this->situation_final)) {
6128 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6132 foreach ($TPreviousIncoice as &$fac) {
6133 $total2BillWT += $fac->total_ttc;
6135 $total2BillWT += $this->total_ttc;
6138 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6144 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6147 if (is_numeric($rounding) && $rounding < 0) {
6151 if (is_numeric($rounding) && $rounding > 0) {
6152 return round($retainedWarrantyAmount, $rounding);
6155 return (
float)
price2num($retainedWarrantyAmount, $rounding);
6166 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
6168 if ($this->
status >= 0) {
6169 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6170 $sql .=
" SET retained_warranty = ".((float) $value);
6171 $sql .=
' WHERE rowid='.((int) $this->
id);
6173 if ($this->db->query($sql)) {
6174 $this->retained_warranty = (float) $value;
6177 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
6178 $this->error = $this->db->error();
6182 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
6183 $this->error =
'Status of the object is incompatible '.$this->status;
6198 if (!$timestamp && $dateYmd) {
6199 $timestamp = $this->db->jdate($dateYmd);
6203 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
6204 if ($this->
status >= 0) {
6205 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6206 $sql .=
" SET retained_warranty_date_limit = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
6207 $sql .=
' WHERE rowid = '.((int) $this->
id);
6209 if ($this->db->query($sql)) {
6210 $this->retained_warranty_date_limit = $timestamp;
6213 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
6214 $this->error = $this->db->error();
6218 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6219 $this->error =
'Status of the object is incompatible '.$this->status;
6238 global
$conf, $langs, $user;
6244 $errorsMsg = array();
6246 $langs->load(
"bills");
6249 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Invoice"));
6252 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
6253 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6263 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
6264 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
6265 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
6266 $formmail =
new FormMail($this->db);
6271 $tmpinvoice =
new Facture($this->db);
6276 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
6277 if (!empty($paymentmode) && $paymentmode !=
'all') {
6278 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
6280 $sql .=
" WHERE f.paye = 0";
6281 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
6282 if ($datetouse ==
'invoicedate') {
6283 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
6285 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
6287 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
6288 if (!empty($paymentmode) && $paymentmode !=
'all') {
6289 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
6292 if ($datetouse ==
'invoicedate') {
6293 $sql .= $this->db->order(
"datef",
"ASC");
6295 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
6299 $resql = $this->db->query($sql);
6302 if ($datetouse ==
'invoicedate') {
6303 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
6305 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
6307 if (!empty($paymentmode) && $paymentmode !=
'all') {
6308 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
6310 $this->output .=
'<br>';
6313 while ($obj = $this->db->fetch_object($resql)) {
6318 $res = $tmpinvoice->fetch($obj->id);
6321 if ($tmpinvoice->getRemainToPay() <= 0 || $tmpinvoice->dispute_status == 1) {
6325 $tmpinvoice->fetch_thirdparty();
6328 if ($tmpinvoice->thirdparty->default_lang) {
6329 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6330 $outputlangs->loadLangs(array(
"main",
"bills"));
6332 $outputlangs = $langs;
6337 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : ((empty($template) || $template ==
'EmailTemplateCode') ? 0 : -2)), 1, (is_numeric($template) ?
'' : $template));
6338 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6339 $langs->load(
"errors");
6340 if (is_numeric($template)) {
6348 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
6357 $errorsMsg[] = $langs->trans(
'ErrorFailedToFindEmailTemplate', $template).
' (invoice '.$tmpinvoice->ref.
')';
6366 $tmpinvoice->totalpaid = $tmpinvoice->getSommePaiement();
6367 $tmpinvoice->totalcreditnotes = $tmpinvoice->getSumCreditNotesUsed();
6368 $tmpinvoice->totaldeposits = $tmpinvoice->getSumDepositsUsed();
6369 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $tmpinvoice);
6374 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6377 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6383 if ($forcerecipient) {
6384 $to = array($forcerecipient);
6386 $res = $tmpinvoice->fetch_thirdparty();
6387 $recipient = $tmpinvoice->thirdparty;
6389 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
6390 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6391 foreach ($tmparraycontact as $data_email) {
6392 if (!empty($data_email[
'email'])) {
6393 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
6397 if (empty($to) && !empty($recipient->email)) {
6398 $to[] = $recipient->email;
6401 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
6405 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6412 if (!empty($arraymessage->email_from)) {
6413 $email_from = (
string) $arraymessage->email_from;
6415 if (empty($email_from)) {
6416 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6420 if (!$loopError && !empty($to)) {
6421 $to = implode(
',', $to);
6422 if (!empty($arraymessage->email_to)) {
6423 $to = $to.
','.$arraymessage->email_to;
6429 $trackid =
'inv'.$tmpinvoice->id;
6430 $sendcontext =
'standard';
6433 if (!empty($arraymessage->email_tocc)) {
6434 $email_tocc = (
string) $arraymessage->email_tocc;
6438 if (!empty($arraymessage->email_tobcc)) {
6439 $email_tobcc = (
string) $arraymessage->email_tobcc;
6446 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6447 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
6448 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6449 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
6453 $cMailFile =
new CMailFile($sendTopic, $to, $email_from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
6455 $resultsendmail = $cMailFile->sendfile();
6460 if ($resultsendmail) {
6464 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6469 $actioncomm->type_code =
'AC_OTH_AUTO';
6470 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6471 $actioncomm->contact_id = 0;
6473 $actioncomm->code =
'AC_EMAIL';
6474 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
6475 $actioncomm->note_private = $sendContent;
6476 $actioncomm->fk_project = $tmpinvoice->fk_project;
6477 $actioncomm->datep =
dol_now();
6478 $actioncomm->datef = $actioncomm->datep;
6479 $actioncomm->percentage = -1;
6480 $actioncomm->authorid = $user->id;
6481 $actioncomm->userownerid = $user->id;
6483 $actioncomm->email_msgid = $cMailFile->msgid;
6484 $actioncomm->email_subject = $sendTopic;
6485 $actioncomm->email_from = $email_from;
6486 $actioncomm->email_sender =
'';
6487 $actioncomm->email_to = $to;
6491 $actioncomm->errors_to = $errors_to;
6493 $actioncomm->elementtype =
'invoice';
6494 $actioncomm->elementid = $tmpinvoice->id;
6498 $actioncomm->create($user);
6500 $errormesg = $cMailFile->error.
' : '.$to;
6504 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6509 $actioncomm->type_code =
'AC_OTH_AUTO';
6510 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6511 $actioncomm->contact_id = 0;
6513 $actioncomm->code =
'AC_EMAIL';
6514 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
6515 $actioncomm->note_private = $errormesg;
6516 $actioncomm->fk_project = $tmpinvoice->fk_project;
6517 $actioncomm->datep =
dol_now();
6518 $actioncomm->datef = $actioncomm->datep;
6519 $actioncomm->percentage = -1;
6520 $actioncomm->authorid = $user->id;
6521 $actioncomm->userownerid = $user->id;
6523 $actioncomm->email_msgid = $cMailFile->msgid;
6524 $actioncomm->email_subject = $sendTopic;
6525 $actioncomm->email_from = $email_from;
6526 $actioncomm->email_sender =
'';
6527 $actioncomm->email_to = $to;
6531 $actioncomm->errors_to = $errors_to;
6533 $actioncomm->elementtype =
'invoice';
6534 $actioncomm->elementid = $tmpinvoice->id;
6538 $actioncomm->create($user);
6541 $this->db->commit();
6545 $errorsMsg[] = $errormesg;
6548 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6552 $error += $loopError;
6559 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6561 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6565 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6567 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6582 $sql =
"SELECT datef";
6583 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6584 $sql .=
" WHERE type = " . (int) $this->
type ;
6585 $sql .=
" AND date_valid IS NOT NULL";
6586 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6587 $sql .=
" ORDER BY datef DESC LIMIT 1";
6589 $result = $this->db->query($sql);
6592 if ($this->db->num_rows($result)) {
6593 $obj = $this->db->fetch_object($result);
6594 $last_date = $this->db->jdate($obj->datef);
6595 $invoice_date = $this->date;
6597 $is_last_of_same_type = $invoice_date >= $last_date;
6598 if ($allow_validated_drafts) {
6602 return array($is_last_of_same_type, $last_date);
6625 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6627 $picto = $this->picto;
6628 if ($this->
type == self::TYPE_REPLACEMENT) {
6631 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6634 if ($this->
type == self::TYPE_DEPOSIT) {
6638 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6639 $return .=
'<div class="info-box info-box-sm">';
6640 $return .=
'<span class="info-box-icon bg-infobox-action">';
6642 $return .=
'</span>';
6643 $return .=
'<div class="info-box-content">';
6644 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6645 if ($selected >= 0) {
6646 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6648 if (!empty($arraydata[
'thirdparty'])) {
6649 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6651 if (property_exists($this,
'date')) {
6652 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->
date,
'day').
'</span>';
6654 if (property_exists($this,
'total_ht')) {
6655 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6656 $return .=
' '.$langs->trans(
"HT");
6657 $return .=
'</span>';
6659 if (method_exists($this,
'getLibStatut')) {
6660 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6661 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6663 $return .=
'</div>';
6664 $return .=
'</div>';
6665 $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.