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 $table_element =
'facture';
84 public $table_element_line =
'facturedet';
89 public $class_element_line =
'FactureLigne';
94 public $fk_element =
'fk_facture';
99 public $picto =
'bill';
105 public $restrictiononfksoc = 1;
121 public $fk_user_author;
127 public $fk_user_valid;
133 public $fk_user_modif;
143 public $delivery_date;
155 public $ref_customer;
171 public $module_source;
179 public $pos_print_counter = 0;
184 public $email_sent_counter = 0;
189 public $fk_fac_rec_source;
194 public $fk_facture_source;
204 public $lines = array();
213 public $extraparams = array();
223 public $date_pointoftax;
229 public $situation_cycle_ref;
234 public $situation_counter;
239 public $situation_final;
244 public $tab_previous_situation_invoice = array();
249 public $tab_next_situation_invoice = array();
254 public $retained_warranty;
259 public $retained_warranty_date_limit;
264 public $retained_warranty_fk_cond_reglement;
269 public $availability_id;
274 public $date_closing;
285 public $remise_percent;
290 public $online_payment_url;
327 public $fields = array(
328 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 1),
329 'ref' => array(
'type' =>
'varchar(30)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'position' => 5),
330 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 20,
'index' => 1),
331 'ref_client' => array(
'type' =>
'varchar(255)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 10),
332 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'RefExt',
'enabled' => 1,
'visible' => 0,
'position' => 12),
333 'type' => array(
'type' =>
'smallint(6)',
'label' =>
'Type',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
334 'subtype' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoiceSubtype',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
336 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 50),
337 'datef' => array(
'type' =>
'date',
'label' =>
'DateInvoice',
'enabled' => 1,
'visible' => 1,
'position' => 20),
338 'date_valid' => array(
'type' =>
'date',
'label' =>
'DateValidation',
'enabled' => 1,
'visible' => -1,
'position' => 22),
339 'date_lim_reglement' => array(
'type' =>
'date',
'label' =>
'DateDue',
'enabled' => 1,
'visible' => 1,
'position' => 25),
340 'date_closing' => array(
'type' =>
'datetime',
'label' =>
'DateClosing',
'enabled' => 1,
'visible' => -1,
'position' => 30),
341 'paye' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoicePaidCompletely',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 80),
342 'close_code' => array(
'type' =>
'varchar(16)',
'label' =>
'EarlyClosingReason',
'enabled' => 1,
'visible' => -1,
'position' => 92),
343 'close_note' => array(
'type' =>
'varchar(128)',
'label' =>
'EarlyClosingComment',
'enabled' => 1,
'visible' => -1,
'position' => 93),
344 'total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountHT',
'enabled' => 1,
'visible' => 1,
'position' => 95,
'isameasure' => 1),
345 'total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountVAT',
'enabled' => 1,
'visible' => -1,
'position' => 100,
'isameasure' => 1),
346 'localtax1' => array(
'type' =>
'double(24,8)',
'label' =>
'LT1',
'enabled' => 1,
'visible' => -1,
'position' => 110,
'isameasure' => 1),
347 'localtax2' => array(
'type' =>
'double(24,8)',
'label' =>
'LT2',
'enabled' => 1,
'visible' => -1,
'position' => 120,
'isameasure' => 1),
348 'revenuestamp' => array(
'type' =>
'double(24,8)',
'label' =>
'RevenueStamp',
'enabled' => 1,
'visible' => -1,
'position' => 115,
'isameasure' => 1),
349 'total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountTTC',
'enabled' => 1,
'visible' => 1,
'position' => 130,
'isameasure' => 1),
350 'fk_facture_source' => array(
'type' =>
'integer',
'label' =>
'SourceInvoice',
'enabled' => 1,
'visible' => -1,
'position' => 170),
351 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' => 1,
'visible' => -1,
'position' => 175),
352 'fk_account' => array(
'type' =>
'integer',
'label' =>
'Fk account',
'enabled' => 1,
'visible' => -1,
'position' => 180),
353 'fk_currency' => array(
'type' =>
'varchar(3)',
'label' =>
'CurrencyCode',
'enabled' => 1,
'visible' => -1,
'position' => 185),
354 'fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentTerm',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 190),
355 'fk_mode_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentMode',
'enabled' => 1,
'visible' => -1,
'position' => 195),
356 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 205),
357 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 210),
358 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 215),
359 'fk_input_reason' => array(
'type' =>
'integer',
'label' =>
'Source',
'enabled' => 1,
'visible' => -1,
'position' => 220),
360 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 225),
361 'situation_cycle_ref' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation cycle ref',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 230),
362 'situation_counter' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation counter',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 235),
363 'situation_final' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation final',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 240),
364 'retained_warranty' => array(
'type' =>
'double',
'label' =>
'Retained warranty',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 245),
365 'retained_warranty_date_limit' => array(
'type' =>
'date',
'label' =>
'Retained warranty date limit',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 250),
366 'retained_warranty_fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'Retained warranty fk cond reglement',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 255),
367 'fk_incoterms' => array(
'type' =>
'integer',
'label' =>
'IncotermCode',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 260),
368 'location_incoterms' => array(
'type' =>
'varchar(255)',
'label' =>
'IncotermLabel',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 265),
369 'date_pointoftax' => array(
'type' =>
'date',
'label' =>
'DatePointOfTax',
'enabled' =>
'getDolGlobalString("INVOICE_POINTOFTAX_DATE")',
'visible' => -1,
'position' => 270),
370 'fk_multicurrency' => array(
'type' =>
'integer',
'label' =>
'MulticurrencyID',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 275),
371 'multicurrency_code' => array(
'type' =>
'varchar(255)',
'label' =>
'Currency',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 280),
372 'multicurrency_tx' => array(
'type' =>
'double(24,8)',
'label' =>
'CurrencyRate',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 285,
'isameasure' => 1),
373 'multicurrency_total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountHT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 290,
'isameasure' => 1),
374 'multicurrency_total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountVAT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 291,
'isameasure' => 1),
375 'multicurrency_total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountTTC',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 292,
'isameasure' => 1),
376 'fk_fac_rec_source' => array(
'type' =>
'integer',
'label' =>
'RecurringInvoiceSource',
'enabled' => 1,
'visible' => -1,
'position' => 305),
377 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'LastMainDoc',
'enabled' => 1,
'visible' => -1,
'position' => 310),
378 'module_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSModule',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 315),
379 'pos_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSTerminal',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 320),
380 'pos_print_counter' => array(
'type' =>
'integer',
'label' =>
'PrintCount',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => 0,
'position' => 325),
381 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 500),
382 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModificationShort',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 502),
383 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'position' => 506),
384 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModification',
'enabled' => 1,
'visible' => -1,
'notnull' => -1,
'position' => 508),
385 'fk_user_valid' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserValidation',
'enabled' => 1,
'visible' => -1,
'position' => 510),
386 'fk_user_closing' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserClosing',
'enabled' => 1,
'visible' => -1,
'position' => 512),
387 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 900),
388 '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')),
467 $this->ismultientitymanaged = 1;
468 $this->isextrafieldmanaged = 1;
470 $this->fields[
'ref_ext'][
'visible'] =
getDolGlobalInt(
'MAIN_LIST_SHOW_REF_EXT');
484 public function create(
User $user, $notrigger = 0, $forceduedate = 0, $updatecurrencyrate = 0)
488 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
490 if (empty($this->
type)) {
494 $this->ref_client = trim((
string) $this->ref_client);
495 $this->ref_customer = trim((
string) $this->ref_customer);
497 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
498 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
499 $this->note_public = (isset($this->note_public) ? trim($this->note_public) :
'');
501 if (!$this->cond_reglement_id) {
502 $this->cond_reglement_id = 0;
504 if (!$this->mode_reglement_id) {
505 $this->mode_reglement_id = 0;
510 if (!empty($this->multicurrency_code)) {
512 if (empty($this->multicurrency_tx)) {
520 $this->fk_multicurrency = 0;
522 if (empty($this->fk_multicurrency)) {
523 $this->multicurrency_code =
$conf->currency;
524 $this->fk_multicurrency = 0;
525 $this->multicurrency_tx = 1;
529 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
532 if (empty($this->
date)) {
533 $this->error =
"Try to create an invoice with an empty parameter (date)";
534 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
538 $result = $soc->fetch($this->socid);
540 $this->error =
"Failed to fetch company: ".$soc->error;
541 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
546 $this->date_creation = $now;
550 $originaldatewhen =
null;
551 $nextdatewhen =
null;
552 $previousdaynextdatewhen =
null;
557 if ($this->fac_rec > 0) {
558 $this->fk_fac_rec_source = $this->fac_rec;
560 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
562 $result = $_facrec->fetch($this->fac_rec);
563 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
567 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
571 $originaldatewhen = $_facrec->date_when;
572 $nextdatewhen =
null;
573 $previousdaynextdatewhen =
null;
575 if ($originaldatewhen) {
576 if ($_facrec->rule_for_lines_dates ==
'postpaid') {
578 $originaldatewhen =
dol_time_plus_duree($originaldatewhen, -$_facrec->frequency, $_facrec->unit_frequency);
580 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, (
int) $_facrec->frequency, $_facrec->unit_frequency);
586 if (!empty($_facrec->frequency)) {
587 $this->socid = $_facrec->socid;
591 $this->entity = $_facrec->entity;
596 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
597 $this->note_public = GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
598 $this->note_private = GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
599 $this->model_pdf = GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
600 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
601 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
602 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
605 $this->total_ht = $_facrec->total_ht;
606 $this->total_ttc = $_facrec->total_ttc;
609 $this->fk_incoterms = $_facrec->fk_incoterms;
610 $this->location_incoterms = $_facrec->location_incoterms;
616 $this->ref_client = trim($this->ref_client);
617 $this->ref_customer = trim($this->ref_customer);
618 $this->note_public = trim($this->note_public);
619 $this->note_private = trim($this->note_private);
620 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
626 if (empty($this->array_options)) {
627 $this->array_options = $_facrec->array_options;
630 if (!$this->mode_reglement_id) {
631 $this->mode_reglement_id = 0;
636 $this->linked_objects = $_facrec->linkedObjectsIds;
641 if ($_facrec->frequency > 0) {
642 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
643 if (empty($_facrec->date_when)) {
644 $_facrec->date_when = $now;
646 $next_date = $_facrec->getNextDate();
648 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
651 $result = $_facrec->setNextDate($next_date, 1);
655 $outputlangs = $langs;
658 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
659 $newlang = $this->thirdparty->default_lang;
662 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
663 $newlang = $this->default_lang;
665 if (!empty($newlang)) {
667 $outputlangs->setDefaultLang($newlang);
671 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $this);
682 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
683 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
684 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
685 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
686 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
697 if (empty($forceduedate)) {
703 $this->date_lim_reglement = $duedate;
705 $this->date_lim_reglement = $forceduedate;
709 $socid = $this->socid;
711 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
720 $sql .=
", date_pointoftax";
721 $sql .=
", note_private";
722 $sql .=
", note_public";
723 $sql .=
", ref_client";
724 $sql .=
", fk_account";
725 $sql .=
", module_source, pos_source, pos_print_counter, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
726 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
727 $sql .=
", fk_input_reason";
728 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
729 $sql .=
", fk_incoterms, location_incoterms";
730 $sql .=
", fk_multicurrency";
731 $sql .=
", multicurrency_code";
732 $sql .=
", multicurrency_tx";
733 $sql .=
", retained_warranty";
734 $sql .=
", retained_warranty_date_limit";
735 $sql .=
", retained_warranty_fk_cond_reglement";
740 $sql .=
", ".(int) $this->entity;
741 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
742 $sql .=
", '".$this->db->escape((
string) $this->type).
"'";
743 $sql .=
", ".(isset($this->subtype) ? (int) $this->subtype :
"null");
744 $sql .=
", ".((int) $socid);
745 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
748 $sql .=
", '".$this->db->idate($this->
date).
"'";
749 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
750 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
751 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
752 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
753 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
754 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
755 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape((
string) $this->pos_source).
"'" :
"null");
756 $sql .=
", ".(int) $this->pos_print_counter;
757 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape((
string) $this->fk_fac_rec_source).
"'" :
"null");
758 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape((
string) $this->fk_facture_source).
"'" :
"null");
759 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
760 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
761 $sql .=
", ".((int) $this->cond_reglement_id);
762 $sql .=
", ".((int) $this->mode_reglement_id);
763 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
764 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
765 $sql .=
", ".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id :
"null");
766 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape((
string) $this->situation_cycle_ref).
"'" :
"null");
767 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape((
string) $this->situation_counter).
"'" :
"null");
768 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
769 $sql .=
", ".(int) $this->fk_incoterms;
770 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
771 $sql .=
", ".(int) $this->fk_multicurrency;
772 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
773 $sql .=
", ".(float) $this->multicurrency_tx;
774 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape((
string) $this->retained_warranty));
775 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
776 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
777 $sql .=
", ".(!empty($this->ip) ?
"'".$this->db->escape($this->ip).
"'" :
"null");
780 $resql = $this->db->query($sql);
782 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
785 $this->
ref =
'(PROV'.$this->id.
')';
786 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
788 $resql = $this->db->query($sql);
793 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
794 $this->linked_objects = $this->linkedObjectsIds;
798 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
799 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
800 if (is_array($tmp_origin_id)) {
801 foreach ($tmp_origin_id as $origin_id) {
804 $this->error = $this->db->lasterror();
809 $origin_id = $tmp_origin_id;
812 $this->error = $this->db->lasterror();
820 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && (!empty($this->origin_type) || !empty($this->origin)) && !empty($this->origin_id)) {
821 $originforcontact = empty($this->origin_type) ? $this->origin : $this->origin_type;
822 $originidforcontact = $this->origin_id;
823 if ($originforcontact ==
'shipping') {
824 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
826 $exp->fetch($this->origin_id);
827 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
828 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
829 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
830 $originforcontact =
'commande';
831 if (is_object($value)) {
832 $originidforcontact = $value->id;
834 $originidforcontact = $value;
841 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople";
842 $sqlcontact .=
" FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
843 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
845 $resqlcontact = $this->db->query($sqlcontact);
847 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
848 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
856 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
859 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
860 foreach ($this->lines as $i => $val) {
861 $newinvoiceline = $this->lines[$i];
862 '@phan-var-force FactureLigne $newinvoiceline';
864 $newinvoiceline->context = $this->context;
866 $newinvoiceline->fk_facture = $this->id;
868 $newinvoiceline->origin = $this->lines[$i]->element;
869 $newinvoiceline->origin_type = $this->lines[$i]->element;
870 $newinvoiceline->origin_id = $this->lines[$i]->id;
873 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
874 $newinvoiceline->date_start = $originaldatewhen;
876 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
877 $newinvoiceline->date_end = $previousdaynextdatewhen;
882 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
887 $vatrate = $newinvoiceline->tva_tx;
888 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
889 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
892 $newinvoiceline->fk_parent_line = $fk_parent_line;
896 $discount->fetch($newinvoiceline->fk_remise_except);
898 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
899 $newinvoiceline->fk_remise_except = $discountId;
903 $newinvoiceline->desc,
904 $newinvoiceline->subprice,
905 $newinvoiceline->qty,
907 $newinvoiceline->localtax1_tx,
908 $newinvoiceline->localtax2_tx,
909 $newinvoiceline->fk_product,
910 $newinvoiceline->remise_percent,
911 $newinvoiceline->date_start,
912 $newinvoiceline->date_end,
913 $newinvoiceline->fk_code_ventilation,
914 $newinvoiceline->info_bits,
915 $newinvoiceline->fk_remise_except,
918 $newinvoiceline->product_type,
919 $newinvoiceline->rang,
920 $newinvoiceline->special_code,
921 $newinvoiceline->element,
924 $newinvoiceline->fk_fournprice,
925 $newinvoiceline->pa_ht,
926 $newinvoiceline->label,
927 $newinvoiceline->array_options,
928 $newinvoiceline->situation_percent,
929 $newinvoiceline->fk_prev_id,
930 $newinvoiceline->fk_unit,
931 $newinvoiceline->multicurrency_subprice,
932 $newinvoiceline->ref_ext,
943 if ($result > 0 && $newinvoiceline->product_type == 9) {
944 $fk_parent_line = $result;
948 } elseif (!$error && empty($this->fac_rec)) {
951 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
953 foreach ($this->lines as $i => $val) {
954 $line = $this->lines[$i];
955 '@phan-var-force FactureLigne $line';
959 if (!is_object($line)) {
960 $line = (object) $line;
965 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
970 $vatrate = $line->tva_tx;
971 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
972 $vatrate .=
' ('.$line->vat_src_code.
')';
976 $originid = $line->origin_id;
977 $origintype = empty($line->origin_type) ? $line->origin : $line->origin_type;
979 $originid = $line->id;
980 $origintype = $this->element;
984 if (empty($line->ref_ext)) {
996 $line->remise_percent,
999 $line->fk_code_ventilation,
1001 $line->fk_remise_except,
1004 $line->product_type,
1006 $line->special_code,
1010 $line->fk_fournprice,
1013 $line->array_options,
1014 $line->situation_percent,
1017 $line->multicurrency_subprice,
1022 $this->error = $this->db->lasterror();
1024 $this->db->rollback();
1029 if ($result > 0 && $line->product_type == 9) {
1030 $fk_parent_line = $result;
1037 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1038 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1039 $fk_parent_line = 0;
1041 foreach ($_facrec->lines as $i => $val) {
1043 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1044 $fk_parent_line = 0;
1047 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1048 $tva_npr = (int) $_facrec->lines[$i]->info_bits;
1049 if (empty($tva_tx)) {
1052 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1053 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1055 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1056 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1059 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1060 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1062 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1067 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1068 $buyprice = $producttmp->cost_price;
1070 $buyprice = $producttmp->pmp;
1072 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1073 if ($producttmp->product_fourn_price_id > 0) {
1074 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1081 if ($updatecurrencyrate == 1) {
1083 } elseif ($updatecurrencyrate == 2) {
1087 $result_insert = $this->
addline(
1088 $_facrec->lines[$i]->desc,
1089 $_facrec->lines[$i]->subprice,
1090 $_facrec->lines[$i]->qty,
1094 $_facrec->lines[$i]->fk_product,
1095 $_facrec->lines[$i]->remise_percent,
1096 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1097 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1103 $_facrec->lines[$i]->product_type,
1104 $_facrec->lines[$i]->rang,
1105 $_facrec->lines[$i]->special_code,
1109 $fk_product_fournisseur_price,
1110 is_null($buyprice) ?
'' : $buyprice,
1111 $_facrec->lines[$i]->label,
1112 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1115 $_facrec->lines[$i]->fk_unit,
1116 $_facrec->lines[$i]->multicurrency_subprice,
1117 $_facrec->lines[$i]->ref_ext,
1121 foreach ($this->lines as $line) {
1122 if ($line->id == $result_insert) {
1123 $line->extraparams = $_facrec->lines[$i]->extraparams;
1124 $line->setExtraParameters();
1129 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1130 $fk_parent_line = $result_insert;
1133 if ($result_insert < 0) {
1135 $this->error = $this->db->error();
1144 $this->error = $langs->trans(
'FailedToUpdatePrice');
1145 $this->db->rollback();
1160 if (!$error && !$notrigger) {
1162 $result = $this->call_trigger(
'BILL_CREATE', $user);
1169 $this->db->commit();
1172 $this->db->rollback();
1176 $this->error = $this->db->error();
1177 $this->db->rollback();
1193 $facture =
new Facture($this->db);
1196 $facture->context[
'createfromclone'] = 1;
1202 if (!empty($this->array_options)) {
1203 $facture->array_options = $this->array_options;
1206 foreach ($this->lines as &$line) {
1207 $line->fetch_optionals();
1210 $facture->fk_facture_source = $this->fk_facture_source;
1211 $facture->type = $this->type;
1212 $facture->subtype = $this->subtype;
1213 $facture->socid = $this->socid;
1214 $facture->date = $this->date;
1215 $facture->date_pointoftax = $this->date_pointoftax;
1216 $facture->note_public = $this->note_public;
1217 $facture->note_private = $this->note_private;
1218 $facture->ref_client = $this->ref_client;
1219 $facture->ref_customer = $this->ref_customer;
1220 $facture->model_pdf = $this->model_pdf;
1221 $facture->fk_project = $this->fk_project;
1222 $facture->cond_reglement_id = $this->cond_reglement_id;
1223 $facture->mode_reglement_id = $this->mode_reglement_id;
1225 $facture->origin = $this->origin;
1226 $facture->origin_id = $this->origin_id;
1227 $facture->fk_account = $this->fk_account;
1229 $facture->lines = $this->lines;
1230 $facture->situation_counter = $this->situation_counter;
1231 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1232 $facture->situation_final = $this->situation_final;
1234 $facture->retained_warranty = $this->retained_warranty;
1235 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1236 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1238 $facture->fk_user_author = $user->id;
1239 $facture->user_creation_id = $user->id;
1243 foreach ($facture->lines as $i => $tmpline) {
1244 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1245 if ($invertdetail) {
1246 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1247 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1248 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1249 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1250 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1251 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1252 $facture->lines[$i]->ref_ext =
'';
1256 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1258 $facid = $facture->create($user);
1260 $this->error = $facture->error;
1261 $this->errors = $facture->errors;
1265 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1266 foreach ($Tfk_object as $fk_object) {
1267 $facture->add_object_linked($typeObject, $fk_object);
1271 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1288 global $hookmanager;
1308 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1309 $objsoc =
new Societe($this->db);
1311 if ($objsoc->fetch($this->socid) > 0) {
1313 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1314 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1316 $object->fk_delivery_address = 0;
1322 $object->entity = (!empty($forceentity) ? $forceentity :
$object->entity);
1330 $object->user_creation_id = $user->id;
1331 $object->user_validation_id =
null;
1332 $object->user_modification_id =
null;
1333 $object->fk_user_author = $user->id;
1334 $object->fk_user_valid =
null;
1335 $object->fk_facture_source = 0;
1336 $object->fk_fac_rec_source = 0;
1338 $object->date_modification =
'';
1339 $object->date_validation =
'';
1350 foreach (
$object->lines as $i => $line) {
1351 '@phan-var-force FactureLigne $line';
1352 if (($line->info_bits & 0x02) == 0x02) {
1359 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1371 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1372 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1376 $object->lines[$i]->date_start = $newFirst;
1377 $object->lines[$i]->date_end = $newLast;
1381 $object->lines[$i]->ref_ext =
'';
1384 $object->lines[$i]->fk_code_ventilation = 0;
1388 $object->context[
'createfromclone'] =
'createfromclone';
1389 $result =
$object->create($user);
1396 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1399 } elseif (
$object->socid == $objFrom->socid) {
1401 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1410 if (is_object($hookmanager)) {
1411 $parameters = array(
'objFrom' => $objFrom);
1413 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1421 unset(
$object->context[
'createfromclone']);
1425 $this->db->commit();
1428 $this->db->rollback();
1442 global $hookmanager;
1451 $this->context[
'createfromclone'] = 1;
1454 for ($i = 0; $i < $num; $i++) {
1456 $src_line =
$object->lines[$i];
1457 '@phan-var-force FactureLigne $src_line';
1458 $line->libelle = $src_line->libelle;
1459 $line->label = $src_line->label;
1460 $line->desc = $src_line->desc;
1461 $line->subprice = $src_line->subprice;
1462 $line->total_ht = $src_line->total_ht;
1463 $line->total_tva = $src_line->total_tva;
1464 $line->total_localtax1 = $src_line->total_localtax1;
1465 $line->total_localtax2 = $src_line->total_localtax2;
1466 $line->total_ttc = $src_line->total_ttc;
1467 $line->vat_src_code = $src_line->vat_src_code;
1468 $line->tva_tx = $src_line->tva_tx;
1469 $line->localtax1_tx = $src_line->localtax1_tx;
1470 $line->localtax2_tx = $src_line->localtax2_tx;
1471 $line->qty = $src_line->qty;
1472 $line->fk_remise_except = $src_line->fk_remise_except;
1473 $line->remise_percent = $src_line->remise_percent;
1474 $line->fk_product = $src_line->fk_product;
1475 $line->info_bits = $src_line->info_bits;
1476 $line->product_type = $src_line->product_type;
1477 $line->rang = $src_line->rang;
1478 $line->special_code = $src_line->special_code;
1479 $line->fk_parent_line = $src_line->fk_parent_line;
1480 $line->fk_unit = $src_line->fk_unit;
1481 $line->date_start = $src_line->date_start;
1482 $line->date_end = $src_line->date_end;
1485 $line->fk_multicurrency = $src_line->fk_multicurrency;
1486 $line->multicurrency_code = $src_line->multicurrency_code;
1487 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1488 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1489 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1490 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1492 $line->fk_fournprice = $src_line->fk_fournprice;
1493 $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);
1494 $line->pa_ht = $marginInfos[0];
1497 $src_line->fetch_optionals();
1498 foreach ($src_line->array_options as $options_key => $value) {
1499 $line->array_options[$options_key] = $value;
1502 $this->lines[$i] = $line;
1505 $this->socid =
$object->socid;
1506 $this->fk_project =
$object->fk_project;
1507 $this->fk_account =
$object->fk_account;
1508 $this->cond_reglement_id =
$object->cond_reglement_id;
1509 $this->mode_reglement_id =
$object->mode_reglement_id;
1510 $this->fk_incoterms =
$object->fk_incoterms;
1511 $this->location_incoterms =
$object->location_incoterms;
1512 $this->availability_id =
$object->availability_id;
1513 $this->demand_reason_id =
$object->demand_reason_id;
1514 $this->delivery_date =
$object->delivery_date;
1515 $this->fk_delivery_address =
$object->fk_delivery_address;
1516 $this->contact_id =
$object->contact_id;
1517 $this->ref_client =
$object->ref_client;
1518 $this->ref_customer =
$object->ref_client;
1521 $this->note_private =
$object->note_private;
1522 $this->note_public =
$object->note_public;
1525 $this->module_source =
$object->module_source;
1526 $this->pos_source =
$object->pos_source;
1528 $this->origin =
$object->element;
1529 $this->origin_type =
$object->element;
1530 $this->origin_id =
$object->id;
1532 $this->fk_user_author = $user->id;
1533 $this->user_creation_id = $user->id;
1537 foreach (
$object->array_options as $options_key => $value) {
1538 $this->array_options[$options_key] = $value;
1542 $this->linked_objects[$this->origin] = $this->origin_id;
1543 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1544 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1547 $ret = $this->
create($user);
1551 $hookmanager->initHooks(array(
'invoicedao'));
1553 $parameters = array(
'objFrom' =>
$object);
1555 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1564 unset($this->context[
'createfromclone']);
1583 global $hookmanager;
1591 $use_all_lines = empty($lines);
1593 for ($i = 0; $i < $num; $i++) {
1594 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1600 $line->libelle =
$object->lines[$i]->libelle;
1601 $line->label =
$object->lines[$i]->label;
1602 $line->desc =
$object->lines[$i]->desc;
1603 $line->subprice =
$object->lines[$i]->subprice;
1604 $line->total_ht =
$object->lines[$i]->total_ht;
1605 $line->total_tva =
$object->lines[$i]->total_tva;
1606 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1607 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1608 $line->total_ttc =
$object->lines[$i]->total_ttc;
1609 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1610 $line->tva_tx =
$object->lines[$i]->tva_tx;
1611 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1612 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1613 $line->qty =
$object->lines[$i]->qty;
1614 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1615 $line->remise_percent =
$object->lines[$i]->remise_percent;
1616 $line->fk_product =
$object->lines[$i]->fk_product;
1617 $line->info_bits =
$object->lines[$i]->info_bits;
1618 $line->product_type =
$object->lines[$i]->product_type;
1619 $line->rang =
$object->lines[$i]->rang;
1620 $line->special_code =
$object->lines[$i]->special_code;
1621 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1622 $line->fk_unit =
$object->lines[$i]->fk_unit;
1623 $line->date_start =
$object->lines[$i]->date_start;
1624 $line->date_end =
$object->lines[$i]->date_end;
1627 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1628 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1629 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1630 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1631 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1632 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1634 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1636 $line->pa_ht = $marginInfos[0];
1639 $object->lines[$i]->fetch_optionals();
1640 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1641 $line->array_options[$options_key] = $value;
1644 $this->lines[$i] = $line;
1647 $this->socid =
$object->socid;
1648 $this->fk_project =
$object->fk_project;
1649 $this->fk_account =
$object->fk_account;
1650 $this->cond_reglement_id =
$object->cond_reglement_id;
1651 $this->mode_reglement_id =
$object->mode_reglement_id;
1652 $this->availability_id =
$object->availability_id;
1653 $this->demand_reason_id =
$object->demand_reason_id;
1654 $this->delivery_date =
$object->delivery_date;
1655 $this->fk_delivery_address =
$object->fk_delivery_address;
1656 $this->contact_id =
$object->contact_id;
1657 $this->ref_client =
$object->ref_client;
1660 $this->note_private =
$object->note_private;
1661 $this->note_public =
$object->note_public;
1664 $this->module_source =
$object->module_source;
1665 $this->pos_source =
$object->pos_source;
1667 $this->origin =
$object->element;
1668 $this->origin_id =
$object->id;
1670 $this->fk_user_author = $user->id;
1671 $this->user_creation_id = $user->id;
1675 foreach (
$object->array_options as $options_key => $value) {
1676 $this->array_options[$options_key] = $value;
1680 $this->linked_objects[$this->origin] = $this->origin_id;
1681 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1682 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1685 $ret = $this->
create($user);
1689 $hookmanager->initHooks(array(
'invoicedao'));
1691 $parameters = array(
'objFrom' =>
$object);
1693 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1723 global
$conf, $langs, $hookmanager, $action;
1725 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1726 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1731 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1735 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1738 $origin->error =
'ErrorDateIsInFuture';
1742 if ($payment_terms_id <= 0) {
1743 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1747 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1749 if (empty($payment_conditions_deposit_percent)) {
1750 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1754 if (empty($origin->deposit_percent)) {
1755 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1759 $deposit =
new self($origin->db);
1760 $deposit->socid = $origin->socid;
1762 $deposit->fk_project = $origin->fk_project;
1763 $deposit->ref_client = $origin->ref_client;
1764 $deposit->ref_customer = $origin->ref_client;
1765 $deposit->date = $date;
1766 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1767 $deposit->cond_reglement_id = $payment_terms_id;
1768 $deposit->availability_id = $origin->availability_id;
1769 $deposit->demand_reason_id = $origin->demand_reason_id;
1770 $deposit->fk_account = $origin->fk_account;
1771 $deposit->fk_incoterms = $origin->fk_incoterms;
1772 $deposit->location_incoterms = $origin->location_incoterms;
1773 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1774 $deposit->multicurrency_code = $origin->multicurrency_code;
1775 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1776 $deposit->module_source = $origin->module_source;
1777 $deposit->pos_source = $origin->pos_source;
1778 $deposit->model_pdf =
'sponge';
1780 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1789 $deposit->note_private = $origin->note_private;
1790 $deposit->note_public = $origin->note_public;
1793 $deposit->origin = $origin->element;
1794 $deposit->origin_type = $origin->element;
1795 $deposit->origin_id = $origin->id;
1797 $origin->fetch_optionals();
1799 foreach ($origin->array_options as $extrakey => $value) {
1800 $deposit->array_options[$extrakey] = $value;
1803 $deposit->linked_objects[$deposit->origin_type] = $deposit->origin_id;
1805 foreach ($overrideFields as $key => $value) {
1806 $deposit->$key = $value;
1809 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1811 $origin->db->begin();
1814 $createReturn = $deposit->create($user, $notrigger);
1816 if ($createReturn <= 0) {
1817 $origin->db->rollback();
1818 $origin->error = $deposit->error;
1819 $origin->errors = $deposit->errors;
1823 $amount_ttc_diff = 0;
1824 $amountdeposit = array();
1825 $descriptions = array();
1832 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1834 $TTotalByTva = array();
1835 foreach ($origin->lines as &$line) {
1836 if (!empty($line->special_code)) {
1839 $key = $line->tva_tx . ($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
1840 if (!array_key_exists($key, $TTotalByTva)) {
1841 $TTotalByTva[$key] = 0;
1842 $descriptions[$key] =
'';
1844 $TTotalByTva[$key] += $line->total_ttc;
1845 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1846 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1847 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1848 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1851 foreach ($TTotalByTva as $tva => &$total) {
1852 $tva_rate_only = preg_replace(
'/\s*\(.*\)/',
'', (
string) $tva);
1853 $coef = $total / $origin->total_ttc;
1854 $am = $amount * $coef;
1855 $amount_ttc_diff += $am;
1856 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100);
1860 $lines = $origin->lines;
1861 $numlines = count($lines);
1862 for ($i = 0; $i < $numlines; $i++) {
1863 if (empty($lines[$i]->qty)) {
1866 if (!empty($lines[$i]->special_code)) {
1870 $totalamount += $lines[$i]->total_ht;
1871 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ?
' ('.$lines[$i]->vat_src_code.
')' :
'');
1872 if (!isset($amountdeposit[$tva_key])) {
1873 $amountdeposit[$tva_key] = 0;
1874 $descriptions[$tva_key] =
'';
1876 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1877 $descriptions[$tva_key] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1878 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1879 $descriptions[$tva_key] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1880 $descriptions[$tva_key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1883 if ($totalamount == 0) {
1884 $amountdeposit[0] = 0;
1887 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1890 foreach ($amountdeposit as $tva => $amount) {
1891 if (empty($amount)) {
1895 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1898 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1899 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1902 $addlineResult = $deposit->addline(
1929 if ($addlineResult < 0) {
1930 $origin->db->rollback();
1931 $origin->error = $deposit->error;
1932 $origin->errors = $deposit->errors;
1937 $diff = $deposit->total_ttc - $amount_ttc_diff;
1940 $deposit->fetch_lines();
1941 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1945 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ?
' ('.$deposit->lines[0]->vat_src_code.
')' :
'');
1946 $updatelineResult = $deposit->updateline(
1947 $deposit->lines[0]->id,
1948 $deposit->lines[0]->desc,
1950 $deposit->lines[0]->qty,
1951 $deposit->lines[0]->remise_percent,
1952 $deposit->lines[0]->date_start,
1953 $deposit->lines[0]->date_end,
1958 $deposit->lines[0]->info_bits,
1959 $deposit->lines[0]->product_type,
1963 $deposit->lines[0]->pa_ht,
1964 $deposit->lines[0]->label,
1970 if ($updatelineResult < 0) {
1971 $origin->db->rollback();
1972 $origin->error = $deposit->error;
1973 $origin->errors = $deposit->errors;
1978 $hookmanager->initHooks(array(
'invoicedao'));
1980 $parameters = array(
'objFrom' => $origin);
1981 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1984 $origin->db->rollback();
1985 $origin->error = $hookmanager->error;
1986 $origin->errors = $hookmanager->errors;
1990 if (!empty($autoValidateDeposit)) {
1991 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1993 if ($validateReturn < 0) {
1994 $origin->db->rollback();
1995 $origin->error = $deposit->error;
1996 $origin->errors = $deposit->errors;
2001 unset($deposit->context[
'createdepositfromorigin']);
2003 $origin->db->commit();
2019 $langs->load(
'bills');
2022 $moretitle = $params[
'moretitle'] ??
'';
2024 $picto = $this->picto;
2025 if ($this->
type == self::TYPE_REPLACEMENT) {
2028 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2031 if ($this->
type == self::TYPE_DEPOSIT) {
2035 if ($user->hasRight(
"facture",
"read")) {
2036 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
2038 $datas[
'picto'] .=
' '.$this->getLibType(1);
2041 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
2044 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2047 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
2050 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2051 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2054 $datas[
'picto'] .=
' - '.$moretitle;
2056 if (!empty($this->
ref)) {
2057 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2059 if (!empty($this->ref_customer)) {
2060 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
2062 if (!empty($this->
date)) {
2063 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->
date,
'day');
2065 if (!empty($this->total_ht)) {
2066 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2068 if (!empty($this->total_tva)) {
2069 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2071 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2072 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1,
$conf->currency);
2074 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2076 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1',
$mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency);
2078 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2079 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2',
$mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency);
2081 if (!empty($this->total_ttc)) {
2082 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2103 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2105 global $langs,
$conf, $user;
2107 if (!empty(
$conf->dol_no_mouse_hover)) {
2113 if ($option ==
'withdraw') {
2114 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2116 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2119 if (!$user->hasRight(
"facture",
"read")) {
2123 if ($option !==
'nolink') {
2125 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2126 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2127 $add_save_lastsearch_values = 1;
2129 if ($add_save_lastsearch_values) {
2130 $url .=
'&save_lastsearch_values=1';
2138 $picto = $this->picto;
2139 if ($this->
type == self::TYPE_REPLACEMENT) {
2142 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2145 if ($this->
type == self::TYPE_DEPOSIT) {
2151 'objecttype' => $this->element,
2152 'moretitle' => $moretitle,
2153 'option' => $option,
2155 $classfortooltip =
'classfortooltip';
2158 $classfortooltip =
'classforajaxtooltip';
2159 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2165 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2166 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2168 $label = $langs->trans(
"Invoice");
2169 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2171 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2172 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2175 $linkstart =
'<a href="'.$url.
'"';
2176 $linkstart .= $linkclose.
'>';
2179 if ($option ==
'nolink') {
2184 $result .= $linkstart;
2186 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2188 if ($withpicto != 2) {
2189 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2191 $result .= $linkend;
2193 if ($addlinktonotes) {
2194 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2196 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2197 $result .=
' <span class="note inline-block">';
2198 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dolPrintHTMLForAttribute($notetoshow).
'">';
2201 $result .=
'</span>';
2205 global $action, $hookmanager;
2206 $hookmanager->initHooks(array(
'invoicedao'));
2207 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2208 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2210 $result = $hookmanager->resPrint;
2212 $result .= $hookmanager->resPrint;
2228 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2230 global
$conf, $extrafields;
2232 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2236 $extraFieldsCheck =
false;
2237 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2239 if ($doFetchInOneSqlRequest) {
2241 if (!isset($extrafields) || !is_object($extrafields)) {
2242 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2247 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
2248 $extrafields->fetch_name_optionals_label($this->table_element);
2251 $extraFieldsCheck = (
2252 !empty($extrafields->attributes[$this->table_element][
'label'])
2253 && is_array($extrafields->attributes[$this->table_element][
'label'])
2254 && count($extrafields->attributes[$this->table_element][
'label']) > 0
2260 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2261 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2262 $sql .=
', f.datef as df, f.date_pointoftax';
2263 $sql .=
', f.date_lim_reglement as dlr';
2264 $sql .=
', f.datec as datec';
2265 $sql .=
', f.date_valid as datev';
2266 $sql .=
', f.tms as datem';
2267 $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';
2268 $sql .=
", f.fk_input_reason";
2269 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2270 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2271 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2272 $sql .=
', f.fk_account';
2273 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2274 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2275 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2276 $sql .=
', f.fk_incoterms, f.location_incoterms';
2277 $sql .=
', f.module_source, f.pos_source, f.pos_print_counter, f.email_sent_counter';
2278 $sql .=
", i.libelle as label_incoterms";
2279 $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";
2280 $sql .=
", f.payment_reference, f.dispute_status";
2282 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2283 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2284 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2285 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2288 if ($type !==
'separate') {
2289 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2290 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2292 $sql .=
", ef.".$this->db->sanitize($key);
2298 $sql .=
' FROM '.$this->db->prefix().
'facture as f';
2301 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2303 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element.
'_extrafields as ef ON f.rowid = ef.fk_object';
2306 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2307 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_paiement as p ON f.fk_mode_reglement = p.id';
2308 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2309 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2312 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2314 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2316 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2319 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2323 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2324 $resql = $this->db->query($sql);
2326 if ($this->db->num_rows($resql)) {
2327 $obj = $this->db->fetch_object($resql);
2329 $this->
id = $obj->rowid;
2330 $this->entity = $obj->entity;
2332 $this->
ref = $obj->ref;
2333 $this->ref_client = $obj->ref_client;
2334 $this->ref_customer = $obj->ref_client;
2335 $this->ref_ext = $obj->ref_ext;
2336 $this->
type = $obj->type;
2337 $this->subtype = $obj->subtype;
2338 $this->
date = $this->db->jdate($obj->df);
2339 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2340 $this->date_creation = $this->db->jdate($obj->datec);
2341 $this->date_validation = $this->db->jdate($obj->datev);
2342 $this->date_modification = $this->db->jdate($obj->datem);
2343 $this->datem = $this->db->jdate($obj->datem);
2344 $this->total_ht = $obj->total_ht;
2345 $this->total_tva = $obj->total_tva;
2346 $this->total_localtax1 = $obj->localtax1;
2347 $this->total_localtax2 = $obj->localtax2;
2348 $this->total_ttc = $obj->total_ttc;
2349 $this->revenuestamp = $obj->revenuestamp;
2350 $this->paye = $obj->paye;
2351 $this->close_code = $obj->close_code;
2352 $this->close_note = $obj->close_note;
2354 $this->socid = $obj->fk_soc;
2355 $this->thirdparty =
null;
2357 $this->fk_project = $obj->fk_project;
2358 $this->project =
null;
2360 $this->statut = $obj->status;
2361 $this->
status = $obj->status;
2363 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2364 $this->mode_reglement_id = $obj->fk_mode_reglement;
2365 $this->mode_reglement_code = $obj->mode_reglement_code;
2366 $this->mode_reglement = $obj->mode_reglement_libelle;
2367 $this->cond_reglement_id = $obj->fk_cond_reglement;
2368 $this->cond_reglement_code = $obj->cond_reglement_code;
2369 $this->cond_reglement = $obj->cond_reglement_libelle;
2370 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2371 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2372 $this->fk_facture_source = $obj->fk_facture_source;
2373 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2374 $this->note = $obj->note_private;
2375 $this->note_private = $obj->note_private;
2376 $this->note_public = $obj->note_public;
2377 $this->user_creation_id = $obj->fk_user_author;
2378 $this->user_validation_id = $obj->fk_user_valid;
2379 $this->user_modification_id = $obj->fk_user_modif;
2380 $this->fk_user_author = $obj->fk_user_author;
2381 $this->fk_user_valid = $obj->fk_user_valid;
2382 $this->fk_user_modif = $obj->fk_user_modif;
2383 $this->model_pdf = $obj->model_pdf;
2384 $this->last_main_doc = $obj->last_main_doc;
2385 $this->demand_reason_id = $obj->fk_input_reason;
2386 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2387 $this->situation_counter = $obj->situation_counter;
2388 $this->situation_final = $obj->situation_final;
2389 $this->retained_warranty = $obj->retained_warranty;
2390 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2391 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2393 $this->payment_reference = $obj->payment_reference;
2394 $this->dispute_status = $obj->dispute_status;
2396 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2399 $this->fk_incoterms = $obj->fk_incoterms;
2400 $this->location_incoterms = $obj->location_incoterms;
2401 $this->label_incoterms = $obj->label_incoterms;
2403 $this->module_source = $obj->module_source;
2404 $this->pos_source = $obj->pos_source;
2405 $this->pos_print_counter = (int) $obj->pos_print_counter;
2406 $this->email_sent_counter = $obj->email_sent_counter;
2409 $this->fk_multicurrency = $obj->fk_multicurrency;
2410 $this->multicurrency_code = $obj->multicurrency_code;
2411 $this->multicurrency_tx = $obj->multicurrency_tx;
2412 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2413 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2414 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2417 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2418 $this->array_options = array();
2420 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2421 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2422 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2425 if ($type !==
'separate') {
2426 $rawval = $obj->$key;
2429 if (in_array($type, array(
'date',
'datetime'))) {
2430 $this->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2431 } elseif ($type ==
'password') {
2432 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2433 $this->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2435 $this->array_options[
'options_' . $key] = $rawval;
2438 $this->array_options[
'options_' . $key] = $rawval;
2444 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2445 if (!empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
2446 if (empty(
$conf->disable_compute)) {
2447 global $objectoffield;
2448 $objectoffield = $this;
2449 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
2455 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2459 if (!$doFetchInOneSqlRequest) {
2466 $this->lines = array();
2470 $this->error = $this->db->error();
2474 $this->db->free($resql);
2478 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2480 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2484 $this->error = $this->db->lasterror();
2498 public function fetch_lines($only_type_product =
'', $loadalsotranslation = 0)
2500 global
$conf, $extrafields;
2503 $this->lines = array();
2505 $extraFieldsCheck =
false;
2506 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2508 if ($doFetchInOneSqlRequest) {
2510 if (!isset($extrafields) || !is_object($extrafields)) {
2511 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2516 if (empty($extrafields->attributes[$this->table_element_line][
'loaded'])) {
2517 $extrafields->fetch_name_optionals_label($this->table_element_line);
2520 $extraFieldsCheck = (
2521 !empty($extrafields->attributes[$this->table_element_line][
'label'])
2522 && is_array($extrafields->attributes[$this->table_element_line][
'label'])
2523 && count($extrafields->attributes[$this->table_element_line][
'label']) > 0
2527 $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,';
2528 $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,';
2529 $sql .=
' l.situation_percent, l.fk_prev_id,';
2530 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2531 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2532 $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,';
2533 $sql .=
' l.fk_unit, l.extraparams,';
2534 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2535 $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';
2537 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2538 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2539 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2540 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2543 if ($type !==
'separate') {
2544 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2545 $sql .=
", ST_AsWKT(ef.".$this->db->sanitize($key).
") as ".$this->db->sanitize($key);
2547 $sql .=
", ef.".$this->db->sanitize($key);
2553 $sql .=
' FROM '.$this->db->prefix().
'facturedet as l';
2556 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2558 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element_line.
'_extrafields as ef ON l.rowid = ef.fk_object';
2561 $sql .=
' LEFT JOIN '.$this->db->prefix().
'product as p ON l.fk_product = p.rowid';
2562 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2563 if (is_int($only_type_product)) {
2564 $sql .=
" AND p.fk_product_type = ".((int) $only_type_product);
2566 $sql .=
' ORDER BY l.rang, l.rowid';
2568 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2569 $result = $this->db->query($sql);
2571 $num = $this->db->num_rows($result);
2574 $objp = $this->db->fetch_object($result);
2577 $line->id = $objp->rowid;
2578 $line->rowid = $objp->rowid;
2579 $line->fk_facture = $objp->fk_facture;
2580 $line->label = $objp->custom_label;
2581 $line->desc = $objp->description;
2582 $line->description = $objp->description;
2583 $line->product_type = $objp->product_type;
2584 $line->ref = $objp->product_ref;
2585 $line->product_ref = $objp->product_ref;
2586 $line->libelle = $objp->product_label;
2587 $line->product_label = $objp->product_label;
2588 $line->product_barcode = $objp->product_barcode;
2589 $line->product_desc = $objp->product_desc;
2590 $line->fk_product_type = $objp->fk_product_type;
2591 $line->qty = $objp->qty;
2592 $line->subprice = $objp->subprice;
2593 $line->ref_ext = $objp->ref_ext;
2595 $line->vat_src_code = $objp->vat_src_code;
2596 $line->tva_tx = $objp->tva_tx;
2597 $line->localtax1_tx = $objp->localtax1_tx;
2598 $line->localtax2_tx = $objp->localtax2_tx;
2599 $line->localtax1_type = $objp->localtax1_type;
2600 $line->localtax2_type = $objp->localtax2_type;
2601 $line->remise_percent = $objp->remise_percent;
2602 $line->fk_remise_except = $objp->fk_remise_except;
2603 $line->fk_product = $objp->fk_product;
2604 $line->date_start = $this->db->jdate($objp->date_start);
2605 $line->date_end = $this->db->jdate($objp->date_end);
2606 $line->info_bits = $objp->info_bits;
2607 $line->total_ht = $objp->total_ht;
2608 $line->total_tva = $objp->total_tva;
2609 $line->total_localtax1 = $objp->total_localtax1;
2610 $line->total_localtax2 = $objp->total_localtax2;
2611 $line->total_ttc = $objp->total_ttc;
2613 $line->fk_fournprice = $objp->fk_fournprice;
2614 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2615 $line->pa_ht = $marginInfos[0];
2616 $line->marge_tx = (
string) $marginInfos[1];
2617 $line->marque_tx = (
string) $marginInfos[2];
2618 $line->rang = $objp->rang;
2619 $line->special_code = $objp->special_code;
2620 $line->fk_parent_line = $objp->fk_parent_line;
2621 $line->situation_percent = $objp->situation_percent;
2622 $line->fk_prev_id = $objp->fk_prev_id;
2623 $line->fk_unit = $objp->fk_unit;
2625 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
2627 $line->batch = $objp->batch;
2628 $line->fk_warehouse = $objp->fk_warehouse;
2631 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2634 $line->fk_multicurrency = $objp->fk_multicurrency;
2635 $line->multicurrency_code = $objp->multicurrency_code;
2636 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2637 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2638 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2639 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2641 $line->array_options = array();
2642 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2643 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2644 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2645 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2648 if ($type !==
'separate') {
2649 $rawval = $objp->$key;
2652 if (in_array($type, array(
'date',
'datetime'))) {
2653 $line->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2654 } elseif ($type ==
'password') {
2655 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2656 $line->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2658 $line->array_options[
'options_' . $key] = $rawval;
2661 $line->array_options[
'options_' . $key] = $rawval;
2667 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2668 if (!empty($extrafields->attributes[$this->table_element_line][
'computed'][$key])) {
2669 if (empty(
$conf->disable_compute)) {
2670 global $objectoffield;
2671 $objectoffield = $line;
2672 $line->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element_line][
'computed'][$key], 1, 0,
'2');
2678 if (!$doFetchInOneSqlRequest) {
2680 $line->fetch_optionals();
2684 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2685 $tmpproduct =
new Product($this->db);
2686 $tmpproduct->fetch($objp->fk_product);
2687 $tmpproduct->getMultiLangs();
2689 $line->multilangs = $tmpproduct->multilangs;
2692 $this->lines[$i] = $line;
2696 $this->db->free($result);
2699 $this->error = $this->db->error();
2712 $this->tab_previous_situation_invoice = array();
2713 $this->tab_next_situation_invoice = array();
2715 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2716 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2717 $sql .=
' AND entity = '.((int) $this->entity);
2718 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2719 $sql .=
' ORDER BY situation_counter ASC';
2721 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2722 $result = $this->db->query($sql);
2723 if ($result && $this->db->num_rows($result) > 0) {
2724 while ($objp = $this->db->fetch_object($result)) {
2725 $invoice =
new Facture($this->db);
2726 if ($invoice->fetch($objp->rowid) > 0) {
2727 if ($objp->situation_counter < $this->situation_counter
2728 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2730 $this->tab_previous_situation_invoice[] = $invoice;
2732 $this->tab_next_situation_invoice[] = $invoice;
2753 if (empty($this->
type)) {
2756 if (isset($this->subtype)) {
2757 $this->subtype = (int) $this->subtype;
2759 if (isset($this->
ref)) {
2760 $this->
ref = trim($this->
ref);
2762 if (isset($this->ref_ext)) {
2763 $this->ref_ext = trim($this->ref_ext);
2765 if (!empty($this->ref_customer)) {
2766 $this->ref_customer = trim($this->ref_customer);
2768 if (isset($this->increment)) {
2769 $this->increment = trim($this->increment);
2771 if (isset($this->close_code)) {
2772 $this->close_code = trim($this->close_code);
2774 if (isset($this->close_note)) {
2775 $this->close_note = trim($this->close_note);
2777 if (isset($this->note) || isset($this->note_private)) {
2778 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2780 if (isset($this->note) || isset($this->note_private)) {
2781 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2783 if (isset($this->note_public)) {
2784 $this->note_public = trim($this->note_public);
2786 if (isset($this->model_pdf)) {
2787 $this->model_pdf = trim($this->model_pdf);
2789 if (isset($this->import_key)) {
2790 $this->import_key = trim($this->import_key);
2792 if (isset($this->retained_warranty)) {
2793 $this->retained_warranty = (float) $this->retained_warranty;
2795 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2796 $this->user_creation_id = $this->fk_user_author;
2798 if (!isset($this->user_modification_id) && !empty($user->id)) {
2799 $this->user_modification_id = $user->id;
2801 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2802 $this->user_validation_id = $this->fk_user_valid;
2806 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2807 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2808 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2809 $sql .=
" type=".(isset($this->
type) ? $this->db->escape((
string) $this->type) :
"null").
",";
2810 $sql .=
" subtype=".(isset($this->subtype) ? (int) $this->subtype :
"null").
",";
2811 $sql .=
" ref_client=".(!empty($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2812 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2813 $sql .=
" fk_soc=".(isset($this->socid) ? $this->db->escape((
string) $this->socid) :
"null").
",";
2814 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2815 $sql .=
" datef=".(strval($this->
date) !=
'' ?
"'".$this->db->idate($this->
date).
"'" :
'null').
",";
2816 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2817 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2818 $sql .=
" paye=".(isset($this->paye) ? $this->db->escape((
string) $this->paye) : 0).
",";
2819 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2820 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2821 $sql .=
" total_tva=".((float) $this->total_tva).
",";
2822 $sql .=
" localtax1=".((float) $this->total_localtax1).
",";
2823 $sql .=
" localtax2=".((float) $this->total_localtax2).
",";
2824 $sql .=
" total_ht=".((float) $this->total_ht).
",";
2825 $sql .=
" total_ttc=".((float) $this->total_ttc).
",";
2826 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2827 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2828 $sql .=
" fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) :
"null").
",";
2829 $sql .=
" fk_user_modif=".(!empty($user->id) ? ((int) $user->id) :
"null").
",";
2830 $sql .=
" fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id :
"null").
",";
2831 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2832 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2833 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2834 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2835 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2836 $sql .=
" note_private = ".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2837 $sql .=
" note_public = ".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2838 $sql .=
" model_pdf = ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2839 $sql .=
" import_key = ".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2840 $sql .=
" module_source = ".(isset($this->module_source) ?
"'".$this->db->escape($this->module_source).
"'" :
"null").
",";
2841 $sql .=
" pos_source = ".(isset($this->pos_source) ?
"'".$this->db->escape($this->pos_source).
"'" :
"null").
",";
2842 $sql .=
" pos_print_counter = ".(int) $this->pos_print_counter.
",";
2843 $sql .=
" situation_cycle_ref = ".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2844 $sql .=
" situation_counter = ".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2845 $sql .=
" situation_final = ".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2846 $sql .=
" retained_warranty = ".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2847 $sql .=
" retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2848 $sql .=
" retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2849 $sql .=
" WHERE rowid = ".((int) $this->
id);
2853 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2854 $resql = $this->db->query($sql);
2857 $this->errors[] =
"Error ".$this->db->lasterror();
2867 if (!$error && !$notrigger) {
2869 $result = $this->call_trigger(
'BILL_MODIFY', $user);
2878 foreach ($this->errors as $errmsg) {
2879 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2880 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2882 $this->db->rollback();
2885 $this->db->commit();
2903 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2904 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2909 $result = $remise->fetch($idremise);
2912 if ($remise->fk_facture) {
2913 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2914 $this->db->rollback();
2919 $facligne->fk_facture = $this->id;
2920 $facligne->fk_remise_except = $remise->id;
2921 $facligne->desc = $remise->description;
2922 $facligne->vat_src_code = $remise->vat_src_code;
2923 $facligne->tva_tx = $remise->tva_tx;
2924 $facligne->localtax1_tx = $remise->localtax1_tx;
2925 $facligne->localtax1_type = (int) $remise->localtax1_type;
2926 $facligne->localtax2_tx = $remise->localtax1_tx;
2927 $facligne->localtax2_type = (int) $remise->localtax1_type;
2928 $facligne->subprice = -(float) $remise->total_ht;
2929 $facligne->fk_product = 0;
2931 $facligne->remise_percent = 0;
2932 $facligne->rang = -1;
2933 $facligne->info_bits = 2;
2936 $facligne->rang = 1;
2937 $linecount = count($this->lines);
2938 for ($ii = 1; $ii <= $linecount; $ii++) {
2944 if ($remise->fk_facture_source > 0) {
2945 $srcinvoice =
new Facture($this->db);
2946 $srcinvoice->fetch($remise->fk_facture_source);
2947 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2949 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2950 $facligne->pa_ht = $arraytmp[
'pa_total'];
2953 $facligne->total_ht = -(float) $remise->total_ht;
2954 $facligne->total_tva = -(float) $remise->total_tva;
2955 $facligne->total_ttc = -(float) $remise->total_ttc;
2956 $facligne->total_localtax1 = -(float) $remise->total_localtax1;
2957 $facligne->total_localtax2 = -(float) $remise->total_localtax2;
2959 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2960 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_total_ht;
2961 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_total_tva;
2962 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_total_ttc;
2964 $lineid = $facligne->insert();
2969 $result = $remise->link_to_invoice($lineid, 0);
2971 $this->error = $remise->error;
2972 $this->db->rollback();
2976 $this->db->commit();
2979 $this->error = $facligne->error;
2980 $this->db->rollback();
2984 $this->error = $facligne->error;
2985 $this->db->rollback();
2989 $this->db->rollback();
3011 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3012 if (empty($ref_client)) {
3013 $sql .=
" SET ref_client = NULL";
3015 $sql .=
" SET ref_client = '".$this->db->escape($ref_client).
"'";
3017 $sql .=
" WHERE rowid = ".((int) $this->
id);
3019 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
3020 $resql = $this->db->query($sql);
3022 $this->errors[] = $this->db->error();
3027 $this->ref_client = $ref_client;
3028 $this->ref_customer = $ref_client;
3031 if (!$notrigger && empty($error)) {
3033 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3041 $this->ref_client = $ref_client;
3042 $this->ref_customer = $ref_client;
3044 $this->db->commit();
3047 foreach ($this->errors as $errmsg) {
3048 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
3049 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
3051 $this->db->rollback();
3071 dol_syslog(__METHOD__.
' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3072 if ($this->
status >= self::STATUS_DRAFT) {
3074 $this->demand_reason_id = $inputReasonId;
3078 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3079 $sql .=
" SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId :
'null');
3080 $sql .=
" WHERE rowid = ".((int) $this->
id);
3083 $res = $this->db->query($sql);
3086 $this->error = $this->db->lasterror();
3087 $this->errors[] = $this->error;
3093 $result = $this->call_trigger(
'BILL_MODIFY', $user);
3102 $this->db->commit();
3104 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3105 $this->db->rollback();
3106 dol_syslog(__METHOD__.
' Error : '.$this->errorsToString(), LOG_ERR);
3127 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3129 global $langs,
$conf;
3130 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3134 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
3147 if (!$error && !$notrigger) {
3149 $result = $this->call_trigger(
'BILL_DELETE', $user);
3158 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"categorie_invoice";
3159 $sql .=
" WHERE fk_invoice = ".((int) $this->
id);
3161 $result = $this->db->query($sql);
3164 $this->errors[] = $this->db->lasterror();
3173 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
3187 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
3188 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
3189 $sql .=
' AND fk_facture_line IS NULL';
3190 $resql = $this->db->query($sql);
3194 $list_rowid_det = array();
3195 foreach ($this->lines as $key => $invoiceline) {
3196 $list_rowid_det[] = $invoiceline->id;
3200 if (count($list_rowid_det)) {
3201 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3202 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
3203 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
3205 if (!$this->db->query($sql)) {
3206 $this->error = $this->db->error().
" sql=".$sql;
3207 $this->errors[] = $this->error;
3208 $this->db->rollback();
3215 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
3216 $sql .=
' SET fk_invoice = NULL';
3217 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
3219 if (!$this->db->query($sql)) {
3220 $this->error = $this->db->error().
" sql=".$sql;
3221 $this->errors[] = $this->error;
3222 $this->db->rollback();
3226 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
3227 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
3228 $sql .=
' WHERE invoice_id = '.((int) $rowid);
3230 if (!$this->db->query($sql)) {
3231 $this->error = $this->db->error().
" sql=".$sql;
3232 $this->errors[] = $this->error;
3233 $this->db->rollback();
3239 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3240 $langs->load(
"agenda");
3242 $num = count($this->lines);
3243 for ($i = 0; $i < $num; $i++) {
3244 if ($this->lines[$i]->fk_product > 0) {
3246 $mouvP->origin = &$this;
3247 $mouvP->setOrigin($this->element, $this->
id);
3249 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3250 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3252 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3259 $main = MAIN_DB_PREFIX.
'facturedet';
3260 $ef = $main.
"_extrafields";
3261 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
3263 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
3266 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
3268 $resql = $this->db->query($sql);
3276 if ($conf->facture->dir_output && !empty($this->
ref)) {
3277 $dir =
$conf->facture->dir_output.
"/".$ref;
3278 $file =
$conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
3279 if (file_exists($file)) {
3283 $langs->load(
"errors");
3284 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
3285 $this->errors[] = $this->error;
3286 $this->db->rollback();
3290 if (file_exists($dir)) {
3292 $langs->load(
"errors");
3293 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
3294 $this->errors[] = $this->error;
3295 $this->db->rollback();
3301 $this->db->commit();
3304 $this->error = $this->db->lasterror().
" sql=".$sql;
3305 $this->errors[] = $this->error;
3306 $this->db->rollback();
3310 $this->error = $this->db->lasterror().
" sql=".$sql;
3311 $this->errors[] = $this->error;
3312 $this->db->rollback();
3316 $this->db->rollback();
3333 public function set_paid($user, $close_code =
'', $close_note =
'')
3336 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3337 return $this->
setPaid($user, $close_code, $close_note);
3350 public function setPaid($user, $close_code =
'', $close_note =
'')
3354 if ($this->paye != 1 || $this->
status != self::STATUS_CLOSED) {
3359 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3361 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3362 $sql .=
' fk_statut = '.self::STATUS_CLOSED;
3364 $sql .=
', paye = 1';
3367 $sql .=
", close_code = '".$this->db->escape($close_code).
"'";
3370 $sql .=
", close_note = '".$this->db->escape($close_note).
"'";
3372 $sql .=
', fk_user_closing = '.((int) $user->id);
3373 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3374 $sql .=
" WHERE rowid = ".((int) $this->
id);
3376 $resql = $this->db->query($sql);
3379 $result = $this->call_trigger(
'BILL_PAYED', $user);
3386 $this->error = $this->db->lasterror();
3392 $this->db->commit();
3395 $this->db->rollback();
3418 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3436 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3437 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3438 $sql .=
' date_closing=null,';
3439 $sql .=
' fk_user_closing=null';
3440 $sql .=
" WHERE rowid = ".((int) $this->
id);
3442 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3443 $resql = $this->db->query($sql);
3446 $result = $this->call_trigger(
'BILL_UNPAYED', $user);
3453 $this->error = $this->db->error();
3458 $this->db->commit();
3461 $this->db->rollback();
3483 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3484 return $this->
setCanceled($user, $close_code, $close_note);
3497 public function setCanceled($user, $close_code =
'', $close_note =
'')
3499 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3504 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3505 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3507 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3510 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3512 $sql .=
', fk_user_closing = '.((int) $user->id);
3513 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3514 $sql .=
" WHERE rowid = ".((int) $this->
id);
3516 $resql = $this->db->query($sql);
3520 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3521 $sql .=
' SET fk_facture = NULL';
3522 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3524 $resql = $this->db->query($sql);
3527 $result = $this->call_trigger(
'BILL_CANCEL', $user);
3529 $this->db->rollback();
3534 $this->db->commit();
3537 $this->error = $this->db->error().
" sql=".$sql;
3538 $this->db->rollback();
3542 $this->error = $this->db->error().
" sql=".$sql;
3543 $this->db->rollback();
3560 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3563 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3565 $productStatic =
null;
3566 $warehouseStatic =
null;
3567 $productbatch =
null;
3568 if ($batch_rule > 0) {
3569 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3570 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3571 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3572 $productStatic =
new Product($this->db);
3573 $warehouseStatic =
new Entrepot($this->db);
3580 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3587 if ($this->
status != self::STATUS_DRAFT) {
3588 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3591 if (count($this->lines) <= 0) {
3592 $langs->load(
"errors");
3593 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3597 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3598 $this->error =
'Permission denied';
3599 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3602 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3610 if (!$last_of_type[0]) {
3617 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3618 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'TVA_INTRA',
'ACCOUNTANCY_CODE_CUSTOMER');
3619 foreach ($array_to_check as $key) {
3620 $keymin = strtolower($key);
3621 if (!property_exists($this->thirdparty, $keymin)) {
3624 $vallabel = $this->thirdparty->$keymin;
3626 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3628 if ($this->thirdparty->isACompany()) {
3630 if (
$mysoc->country_id > 0 && $this->thirdparty->country_id ==
$mysoc->country_id) {
3631 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3633 $langs->load(
"errors");
3634 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3635 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3641 if ($key ==
'EMAIL') {
3644 $langs->load(
"errors");
3645 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3646 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3650 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3652 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3653 $langs->load(
"errors");
3654 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3655 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3659 if ($key ==
'TVA_INTRA') {
3662 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3663 $langs->load(
"errors");
3664 $this->error = $langs->trans(
'ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3665 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3668 } elseif (
getDolGlobalString(
'SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3669 $langs->load(
"errors");
3670 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3671 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3680 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3681 foreach ($array_to_check as $key => $val) {
3682 $keymin = strtolower($key);
3683 $vallabel = $this->$keymin;
3686 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3688 $langs->load(
"errors");
3690 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3697 if ($this->
type == self::TYPE_REPLACEMENT) {
3699 if ($this->fk_facture_source <= 0) {
3700 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3701 $this->db->rollback();
3706 $facreplaced =
new Facture($this->db);
3707 $result = $facreplaced->fetch($this->fk_facture_source);
3709 $this->error = $langs->trans(
"ErrorBadInvoice");
3710 $this->db->rollback();
3715 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3716 if ($idreplacement && $idreplacement != $this->
id) {
3717 $facreplacement =
new Facture($this->db);
3718 $facreplacement->fetch($idreplacement);
3719 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3720 $this->db->rollback();
3724 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3726 $this->error = $facreplaced->error;
3727 $this->db->rollback();
3733 if ($force_number) {
3734 $num = $force_number;
3735 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3748 $this->oldref = $this->ref;
3756 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3757 $sql .=
" SET ref = '".$this->db->escape($num).
"', fk_statut = ".self::STATUS_VALIDATED.
", fk_user_valid = ".($user->id > 0 ? $user->id :
"null").
", date_valid = '".$this->db->idate($now).
"'";
3759 $sql .=
", datef='".$this->db->idate($this->
date).
"'";
3760 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3762 $sql .=
" WHERE rowid = ".((int) $this->
id);
3764 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3765 $resql = $this->db->query($sql);
3767 $this->error = $this->db->lasterror();
3774 $result = $this->thirdparty->setAsCustomer();
3778 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3779 $langs->load(
"agenda");
3782 $cpt = count($this->lines);
3783 for ($i = 0; $i < $cpt; $i++) {
3784 if ($this->lines[$i]->fk_product > 0) {
3786 $mouvP->origin = &$this;
3787 $mouvP->setOrigin($this->element, $this->
id);
3790 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3793 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3802 $is_batch_line =
false;
3803 if ($batch_rule > 0) {
3804 $productStatic->fetch($this->lines[$i]->fk_product);
3805 if ($productStatic->hasbatch() && is_object($productbatch)) {
3806 $is_batch_line =
true;
3807 $product_qty_remain = $this->lines[$i]->qty;
3813 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3814 $sortorder =
'ASC,ASC,ASC,ASC';
3817 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 :
null), $sortfield, $sortorder);
3818 if (!is_array($resBatchList)) {
3820 $this->error = $this->db->lasterror();
3824 $batchList = $resBatchList;
3825 if (empty($batchList)) {
3827 $langs->load(
'errors');
3828 $warehouseStatic->fetch($idwarehouse);
3829 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3830 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3833 foreach ($batchList as $batch) {
3834 if ($batch->qty <= 0) {
3839 if ($batch->qty >= $product_qty_remain) {
3840 $product_batch_qty = $product_qty_remain;
3843 $product_batch_qty = $batch->qty;
3845 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3852 $product_qty_remain -= $product_batch_qty;
3854 if ($product_qty_remain <= 0) {
3859 if (!$error && $product_qty_remain > 0) {
3862 $langs->load(
'errors');
3863 $warehouseStatic->fetch($idwarehouse);
3864 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3865 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3868 $batch = $batchList[0];
3869 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3880 if (!$is_batch_line) {
3881 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3896 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3897 $invoice_situation =
new Facture($this->db);
3898 $result = $invoice_situation->fetch($this->fk_facture_source);
3899 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3900 $invoice_situation->situation_final = 0;
3902 $result = $invoice_situation->setFinal($user, 1);
3905 $this->error = $invoice_situation->error;
3906 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3912 if (!$error && !$notrigger) {
3914 $result = $this->call_trigger(
'BILL_VALIDATE', $user);
3923 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3925 $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).
"'";
3926 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3927 $resql = $this->db->query($sql);
3930 $this->error = $this->db->lasterror();
3932 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3933 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3934 $resql = $this->db->query($sql);
3937 $this->error = $this->db->lasterror();
3944 if (!$resupdatenext) {
3954 $this->date_validation = $now;
3959 $nboflines = count($this->lines);
3960 while (($i < $nboflines) && $final) {
3961 $line = $this->lines[$i];
3962 '@phan-var-force FactureLigne $line';
3964 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3965 $current_progress = (float) $line->situation_percent;
3966 $full_progress = $previousprogress + $current_progress;
3967 $final = ($full_progress == 100);
3969 $final = ($line->situation_percent == 100);
3975 if ($this->situation_final) {
3977 $this->situation_final = 0;
3981 if (!$this->situation_final) {
3983 $this->situation_final = 1;
3993 if (!$error && preg_match(
'/^[\(]?PROV/i', $this->oldref)) {
3997 $dirsource =
$conf->facture->dir_output.
'/'.$oldref;
3998 $dirdest =
$conf->facture->dir_output.
'/'.$newref;
3999 if (!$error && file_exists($dirsource)) {
4000 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
4002 if (@rename($dirsource, $dirdest)) {
4005 $listoffiles =
dol_dir_list(
$conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
4006 foreach ($listoffiles as $fileentry) {
4007 $dirsource = $fileentry[
'name'];
4008 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
4009 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
4010 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
4011 @rename($dirsource, $dirdest);
4018 $this->db->commit();
4021 $this->db->rollback();
4034 foreach ($this->tab_next_situation_invoice as $next_invoice) {
4035 $is_last = $next_invoice->is_last_in_cycle();
4037 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
4038 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4042 foreach ($next_invoice->lines as $line) {
4043 '@phan-var-force FactureLigne $line';
4044 $result = $next_invoice->updateline(
4049 $line->remise_percent,
4053 $line->localtax1_tx,
4054 $line->localtax2_tx,
4057 $line->product_type,
4058 $line->fk_parent_line,
4060 $line->fk_fournprice,
4063 $line->special_code,
4064 $line->array_options,
4065 $line->situation_percent,
4070 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4095 if ($this->
status == self::STATUS_DRAFT) {
4096 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
4104 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4105 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
4106 $sql .=
" WHERE rowid = ".((int) $this->
id);
4108 $result = $this->db->query($sql);
4111 $this->oldcopy = clone $this;
4116 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
4117 $langs->load(
"agenda");
4119 $num = count($this->lines);
4120 for ($i = 0; $i < $num; $i++) {
4121 if ($this->lines[$i]->fk_product > 0) {
4123 $mouvP->origin = &$this;
4124 $mouvP->setOrigin($this->element, $this->
id);
4126 if ($this->
type == self::TYPE_CREDIT_NOTE) {
4127 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
4129 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
4136 $old_statut = $this->status;
4141 $result = $this->call_trigger(
'BILL_UNVALIDATE', $user);
4144 $this->statut = $old_statut;
4145 $this->
status = $old_statut;
4149 $this->db->rollback();
4154 $this->db->commit();
4157 $this->db->rollback();
4161 $this->error = $this->db->error();
4162 $this->db->rollback();
4216 $remise_percent = 0,
4219 $fk_code_ventilation = 0,
4221 $fk_remise_except = 0,
4222 $price_base_type =
'HT',
4229 $fk_parent_line = 0,
4230 $fk_fournprice =
null,
4233 $array_options = array(),
4234 $situation_percent = 100,
4239 $noupdateafterinsertline = 0
4243 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4249 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);
4251 if ($this->
status == self::STATUS_DRAFT) {
4252 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4255 if (empty($remise_percent)) {
4256 $remise_percent = 0;
4261 if (empty($info_bits)) {
4267 if (empty($fk_code_ventilation)) {
4268 $fk_code_ventilation = 0;
4270 if (empty($txtva)) {
4273 if (empty($txlocaltax1)) {
4276 if (empty($txlocaltax2)) {
4279 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4280 $fk_parent_line = 0;
4282 if (empty($fk_prev_id)) {
4283 $fk_prev_id =
'null';
4286 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4289 $situation_percent = 0;
4291 $situation_percent = 100;
4295 if (empty($ref_ext)) {
4299 $remise_percent = (float)
price2num($remise_percent);
4303 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4306 if (strpos((
string) $txtva,
'*') !==
false) {
4309 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4312 $txlocaltax1 = (float)
price2num($txlocaltax1);
4313 $txlocaltax2 = (float)
price2num($txlocaltax2);
4315 if ($price_base_type ==
'HT') {
4327 $langs->load(
"errors");
4328 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4334 $product_type = $type;
4335 if (!empty($fk_product) && $fk_product > 0) {
4336 $product =
new Product($this->db);
4337 $result = $product->fetch($fk_product);
4338 $product_type = $product->type;
4340 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4342 $productChildrenNb = 0;
4344 $productChildrenNb = $product->hasFatherOrChild(1);
4346 if ($productChildrenNb > 0) {
4348 $product_stock =
null;
4349 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4350 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4351 if ($product_stock ===
null) {
4352 $product_stock = $componentStockWarehouse->real;
4354 $product_stock = min($product_stock, $componentStockWarehouse->real);
4357 if ($product_stock ===
null) {
4361 $product_stock = $product->stock_reel;
4364 if ($product_stock < $qty) {
4365 $langs->load(
"errors");
4366 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4367 $this->db->rollback();
4373 $tmpproduct =
new Product($this->db);
4374 $result = $tmpproduct->fetch($fk_product);
4375 if (abs((
float) $qty) < $tmpproduct->packaging) {
4376 $qty = (float) $tmpproduct->packaging;
4377 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4379 if (!empty($tmpproduct->packaging) && (
float)
price2num(fmod((
float) $qty, (
float) $tmpproduct->packaging),
'MS')) {
4380 $coeff = intval(abs((
float) $qty) / $tmpproduct->packaging) + 1;
4381 $qty =
price2num((
float) $tmpproduct->packaging * $coeff,
'MS');
4382 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'warnings');
4393 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4394 $vat_src_code = $reg[1];
4395 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4402 $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);
4404 $total_ht = $tabprice[0];
4405 $total_tva = $tabprice[1];
4406 $total_ttc = $tabprice[2];
4407 $total_localtax1 = $tabprice[9];
4408 $total_localtax2 = $tabprice[10];
4409 $pu_ht = $tabprice[3];
4412 $multicurrency_total_ht = $tabprice[16];
4413 $multicurrency_total_tva = $tabprice[17];
4414 $multicurrency_total_ttc = $tabprice[18];
4415 $pu_ht_devise = $tabprice[19];
4419 if (empty($ranktouse) || $ranktouse == -1) {
4420 $rangmax = $this->
line_max($fk_parent_line);
4421 $ranktouse = $rangmax + 1;
4427 $this->line->context = $this->context;
4429 $this->line->fk_facture = $this->id;
4430 $this->line->label = $label;
4431 $this->line->desc = $desc;
4432 $this->line->ref_ext = $ref_ext;
4434 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : (float) $qty);
4435 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs((
float) $pu_ht) : (float) $pu_ht);
4437 $this->line->vat_src_code = $vat_src_code;
4438 $this->line->tva_tx = $txtva;
4439 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4440 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4441 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4442 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4444 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4445 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4446 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4447 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_localtax1) : (float) $total_localtax1);
4448 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_localtax2) : (float) $total_localtax2);
4450 $this->line->fk_product = $fk_product;
4451 $this->line->product_type = $product_type;
4452 $this->line->remise_percent = $remise_percent;
4454 $this->line->date_end = $date_end;
4455 $this->line->fk_code_ventilation = $fk_code_ventilation;
4456 $this->line->rang = $ranktouse;
4457 $this->line->info_bits = $info_bits;
4458 $this->line->fk_remise_except = $fk_remise_except;
4460 $this->line->special_code = $special_code;
4461 $this->line->fk_parent_line = $fk_parent_line;
4463 $this->line->origin = $origin;
4464 $this->line->origin_id = $origin_id;
4466 $this->line->situation_percent = $situation_percent;
4467 $this->line->fk_prev_id = $fk_prev_id;
4468 $this->line->fk_unit = $fk_unit;
4471 $this->line->fk_fournprice = $fk_fournprice;
4472 $this->line->pa_ht = $pa_ht;
4475 $this->line->fk_multicurrency = $this->fk_multicurrency;
4476 $this->line->multicurrency_code = $this->multicurrency_code;
4477 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4479 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4480 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4481 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4483 if (is_array($array_options) && count($array_options) > 0) {
4484 $this->line->array_options = $array_options;
4487 $result = $this->line->insert();
4490 if (empty($noupdateafterinsertline)) {
4494 if (!isset($this->context[
'createfromclone'])) {
4495 if (!empty($fk_parent_line)) {
4498 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4500 $linecount = count($this->lines);
4501 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4506 $this->lines[] = $this->line;
4509 foreach ($this->lines as $tmpline) {
4510 if ($tmpline->id == $origin_id && $tmpline->element == $origin) {
4511 $this->line->extraparams = $tmpline->extraparams;
4512 $this->line->setExtraParameters();
4518 $this->db->commit();
4519 return $this->line->id;
4521 $this->error = $this->db->lasterror();
4522 $this->db->rollback();
4526 $this->error = $this->line->error;
4527 $this->errors = $this->line->errors;
4528 $this->db->rollback();
4532 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4533 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4569 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)
4575 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4578 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4582 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);
4584 if ($this->
status == self::STATUS_DRAFT) {
4587 if (!$this->error) {
4588 $this->error = $langs->trans(
'invoiceLineProgressError');
4595 $langs->load(
"errors");
4596 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4606 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4607 $fk_parent_line = 0;
4609 if (empty($special_code) || $special_code == 3) {
4612 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
4615 $situation_percent = 0;
4617 $situation_percent = 100;
4620 if (empty($ref_ext)) {
4624 $remise_percent = (float)
price2num($remise_percent);
4628 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4631 if (strpos((
string) $txtva,
'*') !==
false) {
4634 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4637 $txlocaltax1 = (float)
price2num($txlocaltax1);
4638 $txlocaltax2 = (float)
price2num($txlocaltax2);
4654 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4655 $vat_src_code = $reg[1];
4656 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4659 $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);
4661 $total_ht = $tabprice[0];
4662 $total_tva = $tabprice[1];
4663 $total_ttc = $tabprice[2];
4664 $total_localtax1 = $tabprice[9];
4665 $total_localtax2 = $tabprice[10];
4666 $pu_ht = $tabprice[3];
4667 $pu_tva = $tabprice[4];
4668 $pu_ttc = $tabprice[5];
4671 $multicurrency_total_ht = $tabprice[16];
4672 $multicurrency_total_tva = $tabprice[17];
4673 $multicurrency_total_ttc = $tabprice[18];
4674 $pu_ht_devise = $tabprice[19];
4679 if ($remise_percent > 0) {
4680 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4681 $price = ((float) $pu - $remise);
4687 $line->fetch($rowid);
4688 $line->fetch_optionals();
4690 if (!empty($line->fk_product)) {
4691 $product =
new Product($this->db);
4692 $result = $product->fetch($line->fk_product);
4693 $product_type = $product->type;
4695 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product->isStockManaged()) {
4697 $productChildrenNb = 0;
4699 $productChildrenNb = $product->hasFatherOrChild(1);
4701 if ($productChildrenNb > 0) {
4703 $product_stock =
null;
4704 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4705 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4706 if ($product_stock ===
null) {
4707 $product_stock = $componentStockWarehouse->real;
4709 $product_stock = min($product_stock, $componentStockWarehouse->real);
4712 if ($product_stock ===
null) {
4716 $product_stock = $product->stock_reel;
4719 if ($product_stock < $qty) {
4720 $langs->load(
"errors");
4721 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', (
string) $product->ref);
4722 $this->db->rollback();
4728 $staticline = clone $line;
4730 $line->oldline = $staticline;
4731 $this->line = $line;
4732 $this->line->context = $this->context;
4733 $this->line->rang = $rang;
4736 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4737 $rangmax = $this->
line_max($fk_parent_line);
4738 $this->line->rang = $rangmax + 1;
4740 $apply_abs_price_on_credit_note =
false;
4742 $apply_abs_price_on_credit_note =
true;
4747 if ($qty < $this->line->packaging) {
4748 $qty = $this->line->packaging;
4749 setEventMessage($langs->trans(
'QtyRecalculatedWithPackaging'),
'warnings');
4751 if (!empty($this->line->packaging)
4752 && is_numeric($this->line->packaging)
4753 && (
float) $this->line->packaging > 0
4754 && (
float)
price2num(fmod((
float) $qty, (
float) $this->line->packaging),
'MS')) {
4755 $coeff = intval($qty / $this->line->packaging) + 1;
4756 $qty = $this->line->packaging * $coeff;
4757 setEventMessage($langs->trans(
'QtyRecalculatedWithPackaging'),
'warnings');
4762 $this->line->id = $rowid;
4763 $this->line->rowid = $rowid;
4764 $this->line->label = $label;
4765 $this->line->desc = $desc;
4766 $this->line->ref_ext = $ref_ext;
4767 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4769 $this->line->vat_src_code = $vat_src_code;
4770 $this->line->tva_tx = $txtva;
4771 $this->line->localtax1_tx = $txlocaltax1;
4772 $this->line->localtax2_tx = $txlocaltax2;
4773 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4774 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4776 $this->line->remise_percent = $remise_percent;
4777 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4779 $this->line->date_end = $date_end;
4780 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4781 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4782 $this->line->total_localtax1 = (float) $total_localtax1;
4783 $this->line->total_localtax2 = (float) $total_localtax2;
4784 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4785 $this->line->info_bits = $info_bits;
4786 $this->line->special_code = $special_code;
4787 $this->line->product_type = $type;
4788 $this->line->fk_parent_line = $fk_parent_line;
4789 $this->line->skip_update_total = $skip_update_total;
4790 $this->line->situation_percent = $situation_percent;
4791 $this->line->fk_unit = $fk_unit;
4793 $this->line->fk_fournprice = $fk_fournprice;
4794 $this->line->pa_ht = $pa_ht;
4797 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4798 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4799 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4800 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4802 if (is_array($array_options) && count($array_options) > 0) {
4804 foreach ($array_options as $key => $value) {
4805 $this->line->array_options[$key] = $array_options[$key];
4809 $result = $this->line->update($user, $notrigger);
4812 if (!empty($fk_parent_line)) {
4818 $this->db->commit();
4821 $this->error = $this->line->error;
4822 $this->db->rollback();
4826 $this->error =
"Invoice statut makes operation forbidden";
4840 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4841 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4842 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4844 $result = $this->db->query($sql);
4846 $this->error = $this->db->error();
4850 $obj = $this->db->fetch_object($result);
4852 if ($obj ===
null) {
4855 return ($situation_percent < $obj->situation_percent);
4874 if (($line->info_bits & 2) == 2) {
4878 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4881 if ($percent > 100) {
4885 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4886 $current_progress = $percent - $previous_progress;
4887 $line->situation_percent = $current_progress;
4888 $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);
4890 $line->situation_percent = $percent;
4891 $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);
4893 $line->total_ht = (float) $tabprice[0];
4894 $line->total_tva = (float) $tabprice[1];
4895 $line->total_ttc = (float) $tabprice[2];
4896 $line->total_localtax1 = (float) $tabprice[9];
4897 $line->total_localtax2 = (float) $tabprice[10];
4898 $line->multicurrency_total_ht = (float) $tabprice[16];
4899 $line->multicurrency_total_tva = (float) $tabprice[17];
4900 $line->multicurrency_total_ttc = (float) $tabprice[18];
4901 $line->update($user);
4904 if ($update_price) {
4920 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4922 if ($this->
status != self::STATUS_DRAFT) {
4923 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4929 $line->context = $this->context;
4932 $result = $line->fetch($rowid);
4933 if (!($result > 0)) {
4938 if ($id > 0 && $line->fk_facture != $id) {
4939 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4946 $staticline = clone $line;
4947 $line->oldline = $staticline;
4949 if ($line->delete($user) > 0) {
4953 $this->db->commit();
4956 $this->db->rollback();
4957 $this->error = $this->db->lasterror();
4961 $this->db->rollback();
4962 $this->error = $line->error;
4981 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4983 return $this->
setDiscount($user, $remise, $notrigger);
4997 if (empty($remise)) {
5001 if ($user->hasRight(
'facture',
'creer')) {
5002 $remise = (float)
price2num($remise, 2);
5008 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
5009 $sql .=
" SET remise_percent = ".((float) $remise);
5010 $sql .=
" WHERE rowid = ".((int) $this->
id);
5011 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
5014 $resql = $this->db->query($sql);
5016 $this->errors[] = $this->db->error();
5020 if (!$notrigger && empty($error)) {
5022 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5030 $this->remise_percent = $remise;
5033 $this->db->commit();
5036 foreach ($this->errors as $errmsg) {
5037 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5038 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5040 $this->db->rollback();
5061 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
5062 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5075 global
$conf, $langs;
5077 if ($this->module_source ==
'takepos') {
5078 $langs->load(
'cashdesk');
5080 $moduleName =
'takepos';
5081 $moduleSourceName =
'Takepos';
5082 $addonConstName =
'TAKEPOS_REF_ADDON';
5086 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
5091 $langs->load(
'bills');
5093 $moduleName =
'facture';
5094 $moduleSourceName =
'Invoice';
5095 $addonConstName =
'FACTURE_ADDON';
5099 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5101 $conf->global->FACTURE_ADDON =
'mod_facture_mars';
5103 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
5109 if (!empty($addon)) {
5110 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
5114 $file = $addon.
'.php';
5115 $classname = $addon;
5119 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
5120 foreach ($dirmodels as $reldir) {
5121 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
5124 if (is_file($dir.$file) && is_readable($dir.$file)) {
5125 $mybool = ((bool) include_once $dir.$file) || $mybool;
5131 $file = $addon.
'/'.$addon.
'.modules.php';
5132 $classname =
'mod_'.$moduleName.
'_'.$addon;
5133 $classname = preg_replace(
'/\-.*$/',
'', $classname);
5135 foreach (
$conf->file->dol_document_root as $dirroot) {
5136 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
5139 if (is_file($dir.$file) && is_readable($dir.$file)) {
5140 $mybool = (include_once $dir.$file) || $mybool;
5150 $obj =
new $classname();
5151 '@phan-var-force ModeleNumRefFactures $obj';
5153 $numref = $obj->getNextValue($soc, $this, $mode);
5160 if ($mode !=
'last' && !$numref) {
5161 $this->error = $obj->error;
5167 $langs->load(
'errors');
5168 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5181 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5182 $sql .=
' date_closing as dateclosing,';
5183 $sql .=
' fk_user_author, fk_user_modif, fk_user_valid, fk_user_closing';
5184 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
5185 $sql .=
' WHERE c.rowid = '.((int) $id);
5187 $result = $this->db->query($sql);
5189 if ($this->db->num_rows($result)) {
5190 $obj = $this->db->fetch_object($result);
5192 $this->
id = $obj->rowid;
5193 $this->user_creation_id = $obj->fk_user_author;
5194 $this->user_modification_id = $obj->fk_user_modif;
5195 $this->user_validation_id = $obj->fk_user_valid;
5196 $this->user_closing_id = $obj->fk_user_closing;
5198 $this->date_creation = $this->db->jdate($obj->datec);
5199 $this->date_modification = $this->db->jdate($obj->datem);
5200 $this->date_validation = $this->db->jdate($obj->datev);
5201 $this->date_closing = $this->db->jdate($obj->dateclosing);
5203 $this->db->free($result);
5224 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
5231 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
5232 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
5233 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
5234 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5235 $sql .=
" AND f.fk_soc = s.rowid";
5237 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
5239 if (is_object($excluser)) {
5240 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
5244 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5245 $search_sale = $user->id;
5248 if ($search_sale && $search_sale !=
'-1') {
5249 if ($search_sale == -2) {
5250 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5251 } elseif ($search_sale > 0) {
5252 $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).
")";
5257 $sql .=
" AND f.fk_soc = ".((int) $socid);
5259 $sql .= $this->db->order($sortfield, $sortorder);
5260 $sql .= $this->db->plimit($limit, $offset);
5262 $result = $this->db->query($sql);
5264 $numc = $this->db->num_rows($result);
5267 while ($i < $numc) {
5268 $obj = $this->db->fetch_object($result);
5270 if ($shortlist == 1) {
5271 $ga[$obj->fid] = $obj->ref;
5272 } elseif ($shortlist == 2) {
5273 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
5275 $ga[$i][
'id'] = $obj->fid;
5276 $ga[$i][
'ref'] = $obj->ref;
5277 $ga[$i][
'name'] = $obj->name;
5306 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5307 $sql .=
" ff.rowid as rowidnext";
5309 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5310 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5311 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
5312 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
5313 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5314 $sql .=
" AND f.paye = 0";
5315 $sql .=
" AND pf.fk_paiement IS NULL";
5316 $sql .=
" AND ff.fk_statut IS NULL";
5318 $sql .=
" AND f.fk_soc = ".((int) $socid);
5321 $sql .=
" ORDER BY f.ref";
5323 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
5324 $resql = $this->db->query($sql);
5326 while ($obj = $this->db->fetch_object($resql)) {
5327 $return[$obj->rowid] = array(
5328 'id' => $obj->rowid,
5330 'status' => $obj->status,
5331 'paid' => $obj->paid,
5338 $this->error = $this->db->error();
5362 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
5363 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5364 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5365 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
5366 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5367 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5371 $sql .=
" AND ff.type IS NULL";
5372 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
5376 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
5377 $sql .=
'(SELECT MAX(fs.rowid)';
5378 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
5379 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
5380 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
5381 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5383 $sql .=
" AND fs.fk_soc = ".((int) $socid);
5385 $sql .=
" GROUP BY fs.situation_cycle_ref)";
5388 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
5392 $sql .=
" AND f.fk_soc = ".((int) $socid);
5395 if (
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5396 $sql .=
" ORDER BY CASE WHEN f.rowid = ".((int)
GETPOST(
'fac_avoir')).
" THEN 0 ELSE 1 END, f.ref";
5398 $sql .= $this->db->plimit(
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5400 $sql .=
" ORDER BY f.ref";
5403 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
5404 $resql = $this->db->query($sql);
5406 while ($obj = $this->db->fetch_object($resql)) {
5408 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5411 if ($obj->fk_statut == self::STATUS_CLOSED) {
5416 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5417 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
5423 $this->error = $this->db->error();
5439 global
$conf, $langs;
5441 $sanitizedclause =
" WHERE";
5443 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5444 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5445 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5446 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5447 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5448 $sanitizedclause =
" AND";
5450 $sql .= $sanitizedclause.
" f.paye=0";
5451 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5452 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5454 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5457 $resql = $this->db->query($sql);
5459 $langs->load(
"bills");
5462 $response->warning_delay =
getWarningDelay(
'invoice',
'client') / 60 / 60 / 24;
5463 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5464 $response->labelShort = $langs->trans(
"Unpaid");
5465 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5468 $generic_facture =
new Facture($this->db);
5470 while ($obj = $this->db->fetch_object($resql)) {
5471 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5472 $generic_facture->statut = $obj->status;
5473 $generic_facture->status = $obj->status;
5475 $response->nbtodo++;
5476 $response->total += $obj->total_ht;
5478 if ($generic_facture->hasDelay()) {
5479 $response->nbtodolate++;
5480 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5484 $this->db->free($resql);
5488 $this->error = $this->db->error();
5527 global
$conf, $langs, $user;
5531 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5536 $sql =
"SELECT rowid";
5537 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5538 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5539 $sql .= $this->db->plimit(100);
5541 $resql = $this->db->query($sql);
5543 $num_prods = $this->db->num_rows($resql);
5545 while ($i < $num_prods) {
5547 $row = $this->db->fetch_row($resql);
5548 $prodids[$i] = $row[0];
5552 if (empty($num_prods)) {
5554 $prodids[$num_prods] = 1;
5559 $this->entity =
$conf->entity;
5560 $this->
ref =
'SPECIMEN';
5561 $this->specimen = 1;
5563 $this->
date = $nownotime;
5564 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5565 $this->cond_reglement_id = 1;
5566 $this->cond_reglement_code =
'RECEP';
5568 $this->mode_reglement_id = 0;
5569 $this->mode_reglement_code =
'';
5571 $this->note_public =
'This is a comment (public)';
5572 $this->note_private =
'This is a comment (private)';
5574 $this->user_creation_id = $user->id;
5576 $this->multicurrency_tx = 1;
5577 $this->multicurrency_code =
$conf->currency;
5579 $this->fk_incoterms = 0;
5580 $this->location_incoterms =
'';
5582 $this->pos_print_counter = 0;
5583 $this->email_sent_counter = 0;
5587 if (empty($option) || $option !=
'nolines') {
5591 while ($xnbp < $nbp) {
5593 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5595 $line->subprice = 100;
5596 $line->tva_tx = 19.6;
5597 $line->localtax1_tx = 0;
5598 $line->localtax2_tx = 0;
5599 $line->remise_percent = 0;
5600 if ($xnbp == 1 && $option !=
'takepos' && $option !=
'nonegativeup') {
5601 $prodid = mt_rand(1, $num_prods);
5602 if (isset($prodids[$prodid])) {
5603 $line->fk_product = $prodids[$prodid];
5606 $line->total_ht = -100;
5607 $line->total_ttc = -119.6;
5608 $line->total_tva = -19.6;
5609 $line->multicurrency_total_ht = -200;
5610 $line->multicurrency_total_ttc = -239.2;
5611 $line->multicurrency_total_tva = -39.2;
5612 } elseif ($xnbp == 2 && $option !=
'takepos' && $option !=
'nonegativeup') {
5613 $line->subprice = -100;
5614 $line->total_ht = -100;
5615 $line->total_ttc = -119.6;
5616 $line->total_tva = -19.6;
5617 $line->remise_percent = 0;
5618 $line->multicurrency_total_ht = -200;
5619 $line->multicurrency_total_ttc = -239.2;
5620 $line->multicurrency_total_tva = -39.2;
5621 } elseif ($xnbp == 3) {
5622 $prodid = mt_rand(1, $num_prods);
5623 if (isset($prodids[$prodid])) {
5624 $line->fk_product = $prodids[$prodid];
5626 $line->total_ht = 50;
5627 $line->total_ttc = 59.8;
5628 $line->total_tva = 9.8;
5629 $line->multicurrency_total_ht = 100;
5630 $line->multicurrency_total_ttc = 119.6;
5631 $line->multicurrency_total_tva = 19.6;
5632 $line->remise_percent = 50;
5634 $prodid = mt_rand(1, $num_prods);
5635 if (isset($prodids[$prodid])) {
5636 $line->fk_product = $prodids[$prodid];
5638 $line->total_ht = 100;
5639 $line->total_ttc = 119.6;
5640 $line->total_tva = 19.6;
5641 $line->multicurrency_total_ht = 200;
5642 $line->multicurrency_total_ttc = 239.2;
5643 $line->multicurrency_total_tva = 39.2;
5644 $line->remise_percent = 0;
5647 $this->lines[$xnbp] = $line;
5650 $this->total_ht += $line->total_ht;
5651 $this->total_tva += $line->total_tva;
5652 $this->total_ttc += $line->total_ttc;
5654 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5655 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5656 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5660 $this->revenuestamp = 0;
5663 if ($option !=
'takepos') {
5665 $line->desc = $langs->trans(
"Description").
" (offered line)";
5667 $line->subprice = 100;
5668 $line->tva_tx = 19.6;
5669 $line->localtax1_tx = 0;
5670 $line->localtax2_tx = 0;
5671 $line->remise_percent = 100;
5672 $line->total_ht = 0;
5673 $line->total_ttc = 0;
5674 $line->total_tva = 0;
5675 $line->multicurrency_total_ht = 0;
5676 $line->multicurrency_total_ttc = 0;
5677 $line->multicurrency_total_tva = 0;
5678 $prodid = mt_rand(1, $num_prods);
5679 if (isset($prodids[$prodid])) {
5680 $line->fk_product = $prodids[$prodid];
5683 $this->lines[$xnbp] = $line;
5700 $this->nb = array();
5702 $sanitizedclause =
"WHERE";
5704 $sql =
"SELECT count(f.rowid) as nb";
5705 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5706 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5707 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5708 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5709 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5710 $sanitizedclause =
"AND";
5712 $sql .=
" ".$sanitizedclause.
" f.entity IN (".
getEntity(
'invoice').
")";
5714 $resql = $this->db->query($sql);
5716 while ($obj = $this->db->fetch_object($resql)) {
5717 $this->nb[
"invoices"] = $obj->nb;
5719 $this->db->free($resql);
5723 $this->error = $this->db->error();
5749 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5751 $outputlangs->loadLangs(array(
"bills",
"products"));
5755 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5757 if (!empty($this->model_pdf)) {
5758 $modele = $this->model_pdf;
5766 $modelpath =
"core/modules/facture/doc/";
5768 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5778 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5779 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5780 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5782 $resql = $this->db->query($sql);
5784 if ($this->db->num_rows($resql) > 0) {
5786 $obj = $this->db->fetch_object($resql);
5788 $ref = (int) $obj->maxsituationref;
5794 $this->db->free($resql);
5797 $this->error = $this->db->lasterror();
5798 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5812 return ($this->situation_counter == 1);
5826 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5827 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5828 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5829 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5830 $resql = $this->db->query($sql);
5832 if ($resql && $this->db->num_rows($resql) > 0) {
5833 while ($row = $this->db->fetch_object($resql)) {
5835 $situation =
new Facture($this->db);
5836 $situation->fetch($id);
5837 $res[] = $situation;
5840 $this->error = $this->db->error();
5841 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5861 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5864 $resql = $this->db->query($sql);
5866 $this->errors[] = $this->db->error();
5870 if (!$notrigger && empty($error)) {
5872 $result = $this->call_trigger(
'BILL_MODIFY', $user);
5880 $this->db->commit();
5883 foreach ($this->errors as $errmsg) {
5884 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5885 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5887 $this->db->rollback();
5903 if (!empty($this->situation_cycle_ref)) {
5905 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5906 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5907 $sql .=
' AND entity = '.($this->entity > 0 ? ((int) $this->entity) : ((int)
$conf->entity));
5908 $resql = $this->db->query($sql);
5910 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5911 $last = $res[
'max(situation_counter)'];
5912 return ($last == $this->situation_counter);
5914 $this->error = $this->db->lasterror();
5915 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5973 $hasDelay = $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'));
5974 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5976 $totalpaid = (float) $totalpaid;
5978 if ($totalpaid >= 0 && $retainedWarrantyAmount >= 0) {
5979 if (($totalpaid < $this->total_ttc - $retainedWarrantyAmount) && $this->date_lim_reglement < ($now -
getWarningDelay(
'invoice',
'client'))) {
5981 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now -
getWarningDelay(
'invoice',
'client'))) {
5999 return $this->situation_cycle_ref;
6012 $displayWarranty =
false;
6013 if (!empty($this->retained_warranty)) {
6014 $displayWarranty =
true;
6018 $displayWarranty =
false;
6019 if (!empty($this->situation_final)) {
6020 $displayWarranty =
true;
6023 $displayWarranty =
true;
6025 foreach ($this->lines as $i => $line) {
6026 if ($line->product_type < 2 && $line->situation_percent < 100) {
6027 $displayWarranty =
false;
6035 return $displayWarranty;
6046 if (empty($this->retained_warranty)) {
6050 $retainedWarrantyAmount = 0;
6054 $displayWarranty =
true;
6056 if (!empty($this->lines)) {
6057 foreach ($this->lines as $i => $line) {
6058 if ($line->product_type < 2 && $line->situation_percent < 100) {
6059 $displayWarranty =
false;
6065 if ($displayWarranty && !empty($this->situation_final)) {
6067 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6071 foreach ($TPreviousIncoice as &$fac) {
6072 $total2BillWT += $fac->total_ttc;
6074 $total2BillWT += $this->total_ttc;
6077 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6083 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6086 if (is_numeric($rounding) && $rounding < 0) {
6090 if (is_numeric($rounding) && $rounding > 0) {
6091 return round($retainedWarrantyAmount, $rounding);
6094 return (
float)
price2num($retainedWarrantyAmount, $rounding);
6105 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
6107 if ($this->
status >= 0) {
6108 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6109 $sql .=
" SET retained_warranty = ".((float) $value);
6110 $sql .=
' WHERE rowid='.((int) $this->
id);
6112 if ($this->db->query($sql)) {
6113 $this->retained_warranty = (float) $value;
6116 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
6117 $this->error = $this->db->error();
6121 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
6122 $this->error =
'Status of the object is incompatible '.$this->status;
6137 if (!$timestamp && $dateYmd) {
6138 $timestamp = $this->db->jdate($dateYmd);
6142 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
6143 if ($this->
status >= 0) {
6144 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6145 $sql .=
" SET retained_warranty_date_limit = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
6146 $sql .=
' WHERE rowid = '.((int) $this->
id);
6148 if ($this->db->query($sql)) {
6149 $this->retained_warranty_date_limit = $timestamp;
6152 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
6153 $this->error = $this->db->error();
6157 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6158 $this->error =
'Status of the object is incompatible '.$this->status;
6177 global
$conf, $langs, $user;
6183 $errorsMsg = array();
6185 $langs->load(
"bills");
6188 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Invoice"));
6191 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
6192 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6202 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
6203 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
6204 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
6205 $formmail =
new FormMail($this->db);
6210 $tmpinvoice =
new Facture($this->db);
6215 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
6216 if (!empty($paymentmode) && $paymentmode !=
'all') {
6217 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
6219 $sql .=
" WHERE f.paye = 0";
6220 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
6221 if ($datetouse ==
'invoicedate') {
6222 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
6224 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
6226 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
6227 if (!empty($paymentmode) && $paymentmode !=
'all') {
6228 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
6231 if ($datetouse ==
'invoicedate') {
6232 $sql .= $this->db->order(
"datef",
"ASC");
6234 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
6238 $resql = $this->db->query($sql);
6241 if ($datetouse ==
'invoicedate') {
6242 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
6244 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
6246 if (!empty($paymentmode) && $paymentmode !=
'all') {
6247 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
6249 $this->output .=
'<br>';
6252 while ($obj = $this->db->fetch_object($resql)) {
6257 $res = $tmpinvoice->fetch($obj->id);
6259 $tmpinvoice->fetch_thirdparty();
6262 if ($tmpinvoice->thirdparty->default_lang) {
6263 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6264 $outputlangs->loadLangs(array(
"main",
"bills"));
6266 $outputlangs = $langs;
6270 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
6271 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6272 $langs->load(
"errors");
6273 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
6281 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $tmpinvoice);
6286 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6289 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6295 if ($forcerecipient) {
6296 $to = array($forcerecipient);
6298 $res = $tmpinvoice->fetch_thirdparty();
6299 $recipient = $tmpinvoice->thirdparty;
6301 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
6302 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6303 foreach ($tmparraycontact as $data_email) {
6304 if (!empty($data_email[
'email'])) {
6305 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
6309 if (empty($to) && !empty($recipient->email)) {
6310 $to[] = $recipient->email;
6313 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
6317 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6324 if (!empty($arraymessage->email_from)) {
6325 $from = (
string) $arraymessage->email_from;
6328 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6332 if (!$loopError && !empty($to)) {
6333 $to = implode(
',', $to);
6334 if (!empty($arraymessage->email_to)) {
6335 $to = $to.
','.$arraymessage->email_to;
6341 $trackid =
'inv'.$tmpinvoice->id;
6342 $sendcontext =
'standard';
6345 if (!empty($arraymessage->email_tocc)) {
6346 $email_tocc = (
string) $arraymessage->email_tocc;
6350 if (!empty($arraymessage->email_tobcc)) {
6351 $email_tobcc = (
string) $arraymessage->email_tobcc;
6358 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6359 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
6360 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6361 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
6365 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
6367 $resultsendmail = $cMailFile->sendfile();
6372 if ($resultsendmail) {
6376 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6381 $actioncomm->type_code =
'AC_OTH_AUTO';
6382 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6383 $actioncomm->contact_id = 0;
6385 $actioncomm->code =
'AC_EMAIL';
6386 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
6387 $actioncomm->note_private = $sendContent;
6388 $actioncomm->fk_project = $tmpinvoice->fk_project;
6389 $actioncomm->datep =
dol_now();
6390 $actioncomm->datef = $actioncomm->datep;
6391 $actioncomm->percentage = -1;
6392 $actioncomm->authorid = $user->id;
6393 $actioncomm->userownerid = $user->id;
6395 $actioncomm->email_msgid = $cMailFile->msgid;
6396 $actioncomm->email_subject = $sendTopic;
6397 $actioncomm->email_from = $from;
6398 $actioncomm->email_sender =
'';
6399 $actioncomm->email_to = $to;
6403 $actioncomm->errors_to = $errors_to;
6405 $actioncomm->elementtype =
'invoice';
6406 $actioncomm->elementid = $tmpinvoice->id;
6410 $actioncomm->create($user);
6412 $errormesg = $cMailFile->error.
' : '.$to;
6416 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6421 $actioncomm->type_code =
'AC_OTH_AUTO';
6422 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6423 $actioncomm->contact_id = 0;
6425 $actioncomm->code =
'AC_EMAIL';
6426 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
6427 $actioncomm->note_private = $errormesg;
6428 $actioncomm->fk_project = $tmpinvoice->fk_project;
6429 $actioncomm->datep =
dol_now();
6430 $actioncomm->datef = $actioncomm->datep;
6431 $actioncomm->percentage = -1;
6432 $actioncomm->authorid = $user->id;
6433 $actioncomm->userownerid = $user->id;
6435 $actioncomm->email_msgid = $cMailFile->msgid;
6436 $actioncomm->email_subject = $sendTopic;
6437 $actioncomm->email_from = $from;
6438 $actioncomm->email_sender =
'';
6439 $actioncomm->email_to = $to;
6443 $actioncomm->errors_to = $errors_to;
6445 $actioncomm->elementtype =
'invoice';
6446 $actioncomm->elementid = $tmpinvoice->id;
6450 $actioncomm->create($user);
6453 $this->db->commit();
6457 $errorsMsg[] = $errormesg;
6460 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6464 $error += $loopError;
6471 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6473 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6477 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6479 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6494 $sql =
"SELECT datef";
6495 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6496 $sql .=
" WHERE type = " . (int) $this->
type ;
6497 $sql .=
" AND date_valid IS NOT NULL";
6498 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6499 $sql .=
" ORDER BY datef DESC LIMIT 1";
6501 $result = $this->db->query($sql);
6504 if ($this->db->num_rows($result)) {
6505 $obj = $this->db->fetch_object($result);
6506 $last_date = $this->db->jdate($obj->datef);
6507 $invoice_date = $this->date;
6509 $is_last_of_same_type = $invoice_date >= $last_date;
6510 if ($allow_validated_drafts) {
6514 return array($is_last_of_same_type, $last_date);
6537 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6539 $picto = $this->picto;
6540 if ($this->
type == self::TYPE_REPLACEMENT) {
6543 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6546 if ($this->
type == self::TYPE_DEPOSIT) {
6550 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6551 $return .=
'<div class="info-box info-box-sm">';
6552 $return .=
'<span class="info-box-icon bg-infobox-action">';
6554 $return .=
'</span>';
6555 $return .=
'<div class="info-box-content">';
6556 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6557 if ($selected >= 0) {
6558 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6560 if (!empty($arraydata[
'thirdparty'])) {
6561 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6563 if (property_exists($this,
'date')) {
6564 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->
date,
'day').
'</span>';
6566 if (property_exists($this,
'total_ht')) {
6567 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6568 $return .=
' '.$langs->trans(
"HT");
6569 $return .=
'</span>';
6571 if (method_exists($this,
'getLibStatut')) {
6572 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6573 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6575 $return .=
'</div>';
6576 $return .=
'</div>';
6577 $return .=
'</div>';
if(! $sortfield) if(! $sortorder) $object
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
getSumCreditNotesUsed($multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice.
getSumDepositsUsed($multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage invoices.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Returns the IDs of the customer shipping contacts.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
createFromClone(User $user, $fromid=0, $forceentity=null)
Load an object from its id and create a new one in database.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Replace a thirdparty id with another one.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines ...
update(User $user, $notrigger=0)
Update database.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
getIdBillingContact()
Returns the IDs of the customer billing contacts.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=self::TYPE_STANDARD, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=array(), $situation_percent=100, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a detail line.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target='')
Return clickable link of object (with eventually picto)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
fetch($rowid, $ref='', $ref_ext='', $notused=0, $fetch_situation=false)
Get object from database.
setInputReason($inputReasonId, $notrigger=0)
Update invoice input reason.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
updatePriceNextInvoice(&$langs)
Update price of next invoice.
getRetainedWarrantyAmount($rounding='MT')
Calculate the amount of the retained warranty (from the percentage).
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Replace a product id with another one.
setRetainedWarrantyDateLimit($timestamp, $dateYmd='')
Change the retained_warranty_date_limit.
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $datetouse='duedate', $forcerecipient='')
Send reminders by emails for invoices validated that are due.
info($id)
Load miscellaneous information for tab "Info".
const TYPE_PROFORMA
Proforma invoice (should not be used.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setRetainedWarranty($value)
Change the retained warranty.
get_prev_sits()
Returns an array containing the previous situations as Invoice objects.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
newCycle()
Gets the smallest reference available for a new cycle.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
isSituationInvoice()
Check if an invoice is a situation invoice.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getTooltipContentArray($params)
getTooltipContentArray
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
fetch_lines($only_type_product='', $loadalsotranslation=0)
Load all detailed lines into this->lines.
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
const STATUS_VALIDATED
Validated (need to be paid)
hasDelay()
Is the customer invoice delayed?
getLinesArray()
Create an array of invoice lines.
set_unpaid($user)
Tags the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a di...
const TYPE_DEPOSIT
Deposit invoice.
set_paid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
const STATUS_ABANDONED
Classified abandoned and no payment done.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
setPaid($user, $close_code='', $close_note='')
Tag the invoice as :
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed.
const TYPE_CREDIT_NOTE
Credit note invoice.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
create(User $user, $notrigger=0, $forceduedate=0, $updatecurrencyrate=0)
Create invoice in database.
initAsSpecimen($option='')
Initialise an instance with random values.
deleteLine($rowid, $id=0)
Delete line in database.
addline( $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $fk_code_ventilation=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=array(), $situation_percent=100, $fk_prev_id=0, $fk_unit=null, $pu_ht_devise=0, $ref_ext='', $noupdateafterinsertline=0)
Add an invoice line into database (linked to product/service or not).
setUnpaid($user)
Tag the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a dir...
const STATUS_CLOSED
Classified paid.
setCategories($categories)
Sets object to given categories.
createFromContract($object, User $user, $lines=array())
Load an object from a contract and create a new invoice into database.
Class to manage invoice lines.
Class to manage invoice templates.
Class to manage stock movements.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
Manage record for batch number management.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
dol_get_next_month($month, $year)
Return next month.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
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...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_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.
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, $remise_percent_global, $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.