47require_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
48require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/factureligne.class.php';
49require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
50require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
51require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
52require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
53require_once DOL_DOCUMENT_ROOT.
'/subtotals/class/commonsubtotal.class.php';
55if (isModEnabled(
'accounting')) {
56 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
58if (isModEnabled(
'accounting')) {
59 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
72 public $element =
'facture';
77 public $table_element =
'facture';
82 public $table_element_line =
'facturedet';
87 public $class_element_line =
'FactureLigne';
92 public $fk_element =
'fk_facture';
97 public $picto =
'bill';
103 public $restrictiononfksoc = 1;
114 public $fk_user_author;
120 public $fk_user_valid;
126 public $fk_user_modif;
136 public $delivery_date;
148 public $ref_customer;
164 public $module_source;
173 public $fk_fac_rec_source;
177 public $fk_facture_source;
179 public $linked_objects = array();
189 public $lines = array();
198 public $extraparams = array();
208 public $date_pointoftax;
214 public $situation_cycle_ref;
219 public $situation_counter;
224 public $situation_final;
229 public $tab_previous_situation_invoice = array();
234 public $tab_next_situation_invoice = array();
239 public $retained_warranty;
244 public $retained_warranty_date_limit;
249 public $retained_warranty_fk_cond_reglement;
254 public $availability_id;
259 public $date_closing;
270 public $remise_percent;
275 public $online_payment_url;
308 public $fields = array(
309 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 1),
310 'ref' => array(
'type' =>
'varchar(30)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'position' => 5),
311 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 20,
'index' => 1),
312 'ref_client' => array(
'type' =>
'varchar(255)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 10),
313 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'RefExt',
'enabled' => 1,
'visible' => 0,
'position' => 12),
314 'type' => array(
'type' =>
'smallint(6)',
'label' =>
'Type',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
315 'subtype' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoiceSubtype',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
317 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 50),
318 'datef' => array(
'type' =>
'date',
'label' =>
'DateInvoice',
'enabled' => 1,
'visible' => 1,
'position' => 20),
319 'date_valid' => array(
'type' =>
'date',
'label' =>
'DateValidation',
'enabled' => 1,
'visible' => -1,
'position' => 22),
320 'date_lim_reglement' => array(
'type' =>
'date',
'label' =>
'DateDue',
'enabled' => 1,
'visible' => 1,
'position' => 25),
321 'date_closing' => array(
'type' =>
'datetime',
'label' =>
'DateClosing',
'enabled' => 1,
'visible' => -1,
'position' => 30),
322 'paye' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoicePaidCompletely',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 80),
327 'close_code' => array(
'type' =>
'varchar(16)',
'label' =>
'EarlyClosingReason',
'enabled' => 1,
'visible' => -1,
'position' => 92),
328 'close_note' => array(
'type' =>
'varchar(128)',
'label' =>
'EarlyClosingComment',
'enabled' => 1,
'visible' => -1,
'position' => 93),
329 'total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountHT',
'enabled' => 1,
'visible' => 1,
'position' => 95,
'isameasure' => 1),
330 'total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountVAT',
'enabled' => 1,
'visible' => -1,
'position' => 100,
'isameasure' => 1),
331 'localtax1' => array(
'type' =>
'double(24,8)',
'label' =>
'LT1',
'enabled' => 1,
'visible' => -1,
'position' => 110,
'isameasure' => 1),
332 'localtax2' => array(
'type' =>
'double(24,8)',
'label' =>
'LT2',
'enabled' => 1,
'visible' => -1,
'position' => 120,
'isameasure' => 1),
333 'revenuestamp' => array(
'type' =>
'double(24,8)',
'label' =>
'RevenueStamp',
'enabled' => 1,
'visible' => -1,
'position' => 115,
'isameasure' => 1),
334 'total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountTTC',
'enabled' => 1,
'visible' => 1,
'position' => 130,
'isameasure' => 1),
335 'fk_facture_source' => array(
'type' =>
'integer',
'label' =>
'SourceInvoice',
'enabled' => 1,
'visible' => -1,
'position' => 170),
336 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' => 1,
'visible' => -1,
'position' => 175),
337 'fk_account' => array(
'type' =>
'integer',
'label' =>
'Fk account',
'enabled' => 1,
'visible' => -1,
'position' => 180),
338 'fk_currency' => array(
'type' =>
'varchar(3)',
'label' =>
'CurrencyCode',
'enabled' => 1,
'visible' => -1,
'position' => 185),
339 'fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentTerm',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 190),
340 'fk_mode_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentMode',
'enabled' => 1,
'visible' => -1,
'position' => 195),
341 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 205),
342 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 210),
343 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 215),
344 'fk_input_reason' => array(
'type' =>
'integer',
'label' =>
'Source',
'enabled' => 1,
'visible' => -1,
'position' => 220),
345 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 225),
346 'situation_cycle_ref' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation cycle ref',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 230),
347 'situation_counter' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation counter',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 235),
348 'situation_final' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation final',
'enabled' =>
'getDolGlobalInt("INVOICE_USE_SITUATION")',
'visible' => -1,
'position' => 240),
349 'retained_warranty' => array(
'type' =>
'double',
'label' =>
'Retained warranty',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 245),
350 'retained_warranty_date_limit' => array(
'type' =>
'date',
'label' =>
'Retained warranty date limit',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 250),
351 'retained_warranty_fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'Retained warranty fk cond reglement',
'enabled' =>
'getDolGlobalString("INVOICE_USE_RETAINED_WARRANTY")',
'visible' => -1,
'position' => 255),
352 'fk_incoterms' => array(
'type' =>
'integer',
'label' =>
'IncotermCode',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 260),
353 'location_incoterms' => array(
'type' =>
'varchar(255)',
'label' =>
'IncotermLabel',
'enabled' =>
'isModEnabled("incoterm")',
'visible' => -1,
'position' => 265),
354 'date_pointoftax' => array(
'type' =>
'date',
'label' =>
'DatePointOfTax',
'enabled' =>
'getDolGlobalString("INVOICE_POINTOFTAX_DATE")',
'visible' => -1,
'position' => 270),
355 'fk_multicurrency' => array(
'type' =>
'integer',
'label' =>
'MulticurrencyID',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 275),
356 'multicurrency_code' => array(
'type' =>
'varchar(255)',
'label' =>
'Currency',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 280),
357 'multicurrency_tx' => array(
'type' =>
'double(24,8)',
'label' =>
'CurrencyRate',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 285,
'isameasure' => 1),
358 'multicurrency_total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountHT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 290,
'isameasure' => 1),
359 'multicurrency_total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountVAT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 291,
'isameasure' => 1),
360 'multicurrency_total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountTTC',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 292,
'isameasure' => 1),
361 'fk_fac_rec_source' => array(
'type' =>
'integer',
'label' =>
'RecurringInvoiceSource',
'enabled' => 1,
'visible' => -1,
'position' => 305),
362 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'LastMainDoc',
'enabled' => 1,
'visible' => -1,
'position' => 310),
363 'module_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSModule',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 315),
364 'pos_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSTerminal',
'langfile' =>
'cashdesk',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 320),
365 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 500),
366 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModificationShort',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 502),
367 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'position' => 506),
368 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModification',
'enabled' => 1,
'visible' => -1,
'notnull' => -1,
'position' => 508),
369 'fk_user_valid' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserValidation',
'enabled' => 1,
'visible' => -1,
'position' => 510),
370 'fk_user_closing' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserClosing',
'enabled' => 1,
'visible' => -1,
'position' => 512),
371 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 900),
372 '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')),
444 $this->ismultientitymanaged = 1;
445 $this->isextrafieldmanaged = 1;
447 $this->fields[
'ref_ext'][
'visible'] =
getDolGlobalInt(
'MAIN_LIST_SHOW_REF_EXT');
461 public function create(
User $user, $notrigger = 0, $forceduedate = 0, $updatecurrencyrate = 0)
463 global $langs,
$conf, $mysoc;
465 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
467 if (empty($this->
type)) {
471 $this->ref_client = trim($this->ref_client);
472 $this->ref_customer = trim($this->ref_customer);
474 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
475 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
476 $this->note_public = (isset($this->note_public) ? trim($this->note_public) :
'');
478 if (!$this->cond_reglement_id) {
479 $this->cond_reglement_id = 0;
481 if (!$this->mode_reglement_id) {
482 $this->mode_reglement_id = 0;
487 if (!empty($this->multicurrency_code)) {
489 if (empty($this->multicurrency_tx)) {
497 $this->fk_multicurrency = 0;
499 if (empty($this->fk_multicurrency)) {
500 $this->multicurrency_code =
$conf->currency;
501 $this->fk_multicurrency = 0;
502 $this->multicurrency_tx = 1;
506 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
509 if (empty($this->date)) {
510 $this->error =
"Try to create an invoice with an empty parameter (date)";
511 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
515 $result = $soc->fetch($this->socid);
517 $this->error =
"Failed to fetch company: ".$soc->error;
518 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
523 $this->date_creation = $now;
527 $originaldatewhen =
null;
528 $nextdatewhen =
null;
529 $previousdaynextdatewhen =
null;
534 if ($this->fac_rec > 0) {
535 $this->fk_fac_rec_source = $this->fac_rec;
537 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
539 $result = $_facrec->fetch($this->fac_rec);
540 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
544 $origin_user_author_id = ($_facrec->user_creation_id > 0 ? $_facrec->user_creation_id : $origin_user_author_id);
548 $originaldatewhen = $_facrec->date_when;
549 $nextdatewhen =
null;
550 $previousdaynextdatewhen =
null;
552 if ($originaldatewhen) {
553 if ($_facrec->rule_for_lines_dates ==
'prepaid') {
554 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, (
int) $_facrec->frequency, $_facrec->unit_frequency);
557 if ($_facrec->rule_for_lines_dates ==
'postpaid') {
559 } elseif ($nextdatewhen) {
563 $originaldatewhen = $_facrec->rule_for_lines_dates ==
'postpaid'
569 if (!empty($_facrec->frequency)) {
570 $this->socid = $_facrec->socid;
574 $this->entity = $_facrec->entity;
579 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
580 $this->note_public = GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
581 $this->note_private = GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
582 $this->model_pdf = GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
583 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
584 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
585 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
588 $this->total_ht = $_facrec->total_ht;
589 $this->total_ttc = $_facrec->total_ttc;
594 $this->fk_incoterms = $_facrec->fk_incoterms;
595 $this->location_incoterms = $_facrec->location_incoterms;
601 $this->ref_client = trim($this->ref_client);
602 $this->ref_customer = trim($this->ref_customer);
603 $this->note_public = trim($this->note_public);
604 $this->note_private = trim($this->note_private);
605 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
607 $this->array_options = $_facrec->array_options;
609 if (!$this->mode_reglement_id) {
610 $this->mode_reglement_id = 0;
615 $this->linked_objects = $_facrec->linkedObjectsIds;
620 if ($_facrec->frequency > 0) {
621 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
622 if (empty($_facrec->date_when)) {
623 $_facrec->date_when = $now;
625 $next_date = $_facrec->getNextDate();
626 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
628 $result = $_facrec->setNextDate($next_date, 1);
632 $outputlangs = $langs;
635 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
636 $newlang = $this->thirdparty->default_lang;
639 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
640 $newlang = $this->default_lang;
642 if (!empty($newlang)) {
644 $outputlangs->setDefaultLang($newlang);
648 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $this);
650 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
653 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
656 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
659 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
660 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
661 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
662 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
663 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
674 if (empty($forceduedate)) {
680 $this->date_lim_reglement = $duedate;
682 $this->date_lim_reglement = $forceduedate;
686 $socid = $this->socid;
688 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
697 $sql .=
", date_pointoftax";
698 $sql .=
", note_private";
699 $sql .=
", note_public";
700 $sql .=
", ref_client";
701 $sql .=
", fk_account";
702 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
703 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
704 $sql .=
", fk_input_reason";
705 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
706 $sql .=
", fk_incoterms, location_incoterms";
707 $sql .=
", fk_multicurrency";
708 $sql .=
", multicurrency_code";
709 $sql .=
", multicurrency_tx";
710 $sql .=
", retained_warranty";
711 $sql .=
", retained_warranty_date_limit";
712 $sql .=
", retained_warranty_fk_cond_reglement";
716 $sql .=
", ".(int) $this->entity;
717 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
718 $sql .=
", '".$this->db->escape((
string) $this->type).
"'";
719 $sql .=
", ".($this->subtype ?
"'".$this->db->escape((
string) $this->subtype).
"'" :
"null");
720 $sql .=
", ".((int) $socid);
721 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
724 $sql .=
", '".$this->db->idate($this->date).
"'";
725 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
726 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
727 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
728 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
729 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
730 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
731 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape((
string) $this->pos_source).
"'" :
"null");
732 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape((
string) $this->fk_fac_rec_source).
"'" :
"null");
733 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape((
string) $this->fk_facture_source).
"'" :
"null");
734 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
735 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
736 $sql .=
", ".((int) $this->cond_reglement_id);
737 $sql .=
", ".((int) $this->mode_reglement_id);
738 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
739 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
740 $sql .=
", ".($this->demand_reason_id > 0 ? (int) $this->demand_reason_id :
"null");
741 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape((
string) $this->situation_cycle_ref).
"'" :
"null");
742 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape((
string) $this->situation_counter).
"'" :
"null");
743 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
744 $sql .=
", ".(int) $this->fk_incoterms;
745 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
746 $sql .=
", ".(int) $this->fk_multicurrency;
747 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
748 $sql .=
", ".(float) $this->multicurrency_tx;
749 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape((
string) $this->retained_warranty));
750 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
751 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
754 $resql = $this->db->query($sql);
756 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
759 $this->
ref =
'(PROV'.$this->id.
')';
760 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
762 $resql = $this->db->query($sql);
767 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
768 $this->linked_objects = $this->linkedObjectsIds;
772 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
773 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
774 if (is_array($tmp_origin_id)) {
775 foreach ($tmp_origin_id as $origin_id) {
778 $this->error = $this->db->lasterror();
783 $origin_id = $tmp_origin_id;
786 $this->error = $this->db->lasterror();
794 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) {
795 $originforcontact = $this->origin;
796 $originidforcontact = $this->origin_id;
797 if ($originforcontact ==
'shipping') {
798 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
800 $exp->fetch($this->origin_id);
801 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
802 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
803 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
804 $originforcontact =
'commande';
805 if (is_object($value)) {
806 $originidforcontact = $value->id;
808 $originidforcontact = $value;
815 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople";
816 $sqlcontact .=
" FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
817 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
819 $resqlcontact = $this->db->query($sqlcontact);
821 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
822 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
830 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
833 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
834 foreach ($this->lines as $i => $val) {
835 $newinvoiceline = $this->lines[$i];
836 '@phan-var-force FactureLigne $newinvoiceline';
838 $newinvoiceline->context = $this->context;
840 $newinvoiceline->fk_facture = $this->id;
842 $newinvoiceline->origin = $this->lines[$i]->element;
843 $newinvoiceline->origin_id = $this->lines[$i]->id;
846 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
847 $newinvoiceline->date_start = $originaldatewhen;
849 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
850 $newinvoiceline->date_end = $previousdaynextdatewhen;
855 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
860 $vatrate = $newinvoiceline->tva_tx;
861 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
862 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
865 $newinvoiceline->fk_parent_line = $fk_parent_line;
869 $discount->fetch($newinvoiceline->fk_remise_except);
871 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
872 $newinvoiceline->fk_remise_except = $discountId;
876 $newinvoiceline->desc,
877 $newinvoiceline->subprice,
878 $newinvoiceline->qty,
880 $newinvoiceline->localtax1_tx,
881 $newinvoiceline->localtax2_tx,
882 $newinvoiceline->fk_product,
883 $newinvoiceline->remise_percent,
884 $newinvoiceline->date_start,
885 $newinvoiceline->date_end,
886 $newinvoiceline->fk_code_ventilation,
887 $newinvoiceline->info_bits,
888 $newinvoiceline->fk_remise_except,
891 $newinvoiceline->product_type,
892 $newinvoiceline->rang,
893 $newinvoiceline->special_code,
894 $newinvoiceline->element,
897 $newinvoiceline->fk_fournprice,
898 $newinvoiceline->pa_ht,
899 $newinvoiceline->label,
900 $newinvoiceline->array_options,
901 $newinvoiceline->situation_percent,
902 $newinvoiceline->fk_prev_id,
903 $newinvoiceline->fk_unit,
904 $newinvoiceline->multicurrency_subprice,
905 $newinvoiceline->ref_ext,
910 $this->error = $newinvoiceline->error;
911 $this->errors = array_merge($this->errors, $newinvoiceline->errors);
917 if ($result > 0 && $newinvoiceline->product_type == 9) {
918 $fk_parent_line = $result;
922 } elseif (!$error && empty($this->fac_rec)) {
925 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
927 foreach ($this->lines as $i => $val) {
928 $line = $this->lines[$i];
929 '@phan-var-force FactureLigne $line';
933 if (!is_object($line)) {
934 $line = (object) $line;
939 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
944 $vatrate = $line->tva_tx;
945 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
946 $vatrate .=
' ('.$line->vat_src_code.
')';
950 $originid = $line->origin_id;
951 $origintype = $line->origin_type;
953 $originid = $line->id;
954 $origintype = $this->element;
958 if (empty($line->ref_ext)) {
970 $line->remise_percent,
973 $line->fk_code_ventilation,
975 $line->fk_remise_except,
984 $line->fk_fournprice,
987 $line->array_options,
988 $line->situation_percent,
991 $line->multicurrency_subprice,
996 $this->error = $this->db->lasterror();
998 $this->db->rollback();
1003 if ($result > 0 && $line->product_type == 9) {
1004 $fk_parent_line = $result;
1011 if (!$error && $this->fac_rec > 0 && is_object($_facrec)) {
1012 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
1013 $fk_parent_line = 0;
1015 foreach ($_facrec->lines as $i => $val) {
1017 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
1018 $fk_parent_line = 0;
1021 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1022 $tva_npr = $_facrec->lines[$i]->info_bits;
1023 if (empty($tva_tx)) {
1026 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1027 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1029 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1030 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1033 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1034 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1036 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1041 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1042 $buyprice = $producttmp->cost_price;
1044 $buyprice = $producttmp->pmp;
1046 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1047 if ($producttmp->product_fourn_price_id > 0) {
1048 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1055 if ($updatecurrencyrate == 1) {
1057 } elseif ($updatecurrencyrate == 2) {
1061 $result_insert = $this->
addline(
1062 $_facrec->lines[$i]->desc,
1063 $_facrec->lines[$i]->subprice,
1064 $_facrec->lines[$i]->qty,
1068 $_facrec->lines[$i]->fk_product,
1069 $_facrec->lines[$i]->remise_percent,
1070 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1071 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1077 $_facrec->lines[$i]->product_type,
1078 $_facrec->lines[$i]->rang,
1079 $_facrec->lines[$i]->special_code,
1083 $fk_product_fournisseur_price,
1084 is_null($buyprice) ?
'' : $buyprice,
1085 $_facrec->lines[$i]->label,
1086 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1089 $_facrec->lines[$i]->fk_unit,
1090 $_facrec->lines[$i]->multicurrency_subprice,
1091 $_facrec->lines[$i]->ref_ext,
1095 foreach ($this->lines as $line) {
1096 if ($line->id == $result_insert) {
1097 $line->extraparams = $_facrec->lines[$i]->extraparams;
1098 $line->setExtraParameters();
1103 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1104 $fk_parent_line = $result_insert;
1107 if ($result_insert < 0) {
1109 $this->error = $this->db->error();
1118 $this->error = $langs->trans(
'FailedToUpdatePrice');
1119 $this->db->rollback();
1134 if (!$error && !$notrigger) {
1143 $this->db->commit();
1146 $this->db->rollback();
1150 $this->error = $this->db->error();
1151 $this->db->rollback();
1167 $facture =
new Facture($this->db);
1170 $facture->context[
'createfromclone'] = 1;
1175 if (empty($this->array_options)) {
1179 if (!empty($this->array_options)) {
1180 $facture->array_options = $this->array_options;
1183 foreach ($this->lines as &$line) {
1184 $line->fetch_optionals();
1187 $facture->fk_facture_source = $this->fk_facture_source;
1188 $facture->type = $this->type;
1189 $facture->subtype = $this->subtype;
1190 $facture->socid = $this->socid;
1191 $facture->date = $this->date;
1192 $facture->date_pointoftax = $this->date_pointoftax;
1193 $facture->note_public = $this->note_public;
1194 $facture->note_private = $this->note_private;
1195 $facture->ref_client = $this->ref_client;
1196 $facture->ref_customer = $this->ref_customer;
1197 $facture->model_pdf = $this->model_pdf;
1198 $facture->fk_project = $this->fk_project;
1199 $facture->cond_reglement_id = $this->cond_reglement_id;
1200 $facture->mode_reglement_id = $this->mode_reglement_id;
1204 $facture->origin = $this->origin;
1205 $facture->origin_id = $this->origin_id;
1206 $facture->fk_account = $this->fk_account;
1208 $facture->lines = $this->lines;
1209 $facture->situation_counter = $this->situation_counter;
1210 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1211 $facture->situation_final = $this->situation_final;
1213 $facture->retained_warranty = $this->retained_warranty;
1214 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1215 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1217 $facture->fk_user_author = $user->id;
1218 $facture->user_creation_id = $user->id;
1222 foreach ($facture->lines as $i => $tmpline) {
1223 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1224 if ($invertdetail) {
1225 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1226 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1227 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1228 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1229 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1230 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1231 $facture->lines[$i]->ref_ext =
'';
1235 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1237 $facid = $facture->create($user);
1239 $this->error = $facture->error;
1240 $this->errors = $facture->errors;
1244 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1245 foreach ($Tfk_object as $fk_object) {
1246 $facture->add_object_linked($typeObject, $fk_object);
1250 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1267 global
$conf, $hookmanager;
1287 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1288 $objsoc =
new Societe($this->db);
1290 if ($objsoc->fetch($this->socid) > 0) {
1292 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1293 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1295 $object->fk_delivery_address = 0;
1301 $object->entity = (!empty($forceentity) ? $forceentity :
$object->entity);
1309 $object->user_creation_id = $user->id;
1310 $object->user_validation_id =
null;
1311 $object->fk_user_author = $user->id;
1312 $object->fk_user_valid =
null;
1313 $object->fk_facture_source = 0;
1314 $object->fk_fac_rec_source = 0;
1316 $object->date_modification =
'';
1317 $object->date_validation =
'';
1328 foreach (
$object->lines as $i => $line) {
1329 '@phan-var-force FactureLigne $line';
1330 if (($line->info_bits & 0x02) == 0x02) {
1337 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1349 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1350 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1354 $object->lines[$i]->date_start = $newFirst;
1355 $object->lines[$i]->date_end = $newLast;
1359 $object->lines[$i]->ref_ext =
'';
1360 $object->lines[$i]->fk_code_ventilation = 0;
1364 $object->context[
'createfromclone'] =
'createfromclone';
1365 $result =
$object->create($user);
1368 $this->error =
$object->error;
1369 $this->errors =
$object->errors;
1372 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1374 $this->error =
$object->error;
1375 $this->errors =
$object->errors;
1376 } elseif (
$object->socid == $objFrom->socid) {
1378 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1380 $this->error =
$object->error;
1381 $this->errors =
$object->errors;
1388 if (is_object($hookmanager)) {
1389 $parameters = array(
'objFrom' => $objFrom);
1391 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1399 unset(
$object->context[
'createfromclone']);
1403 $this->db->commit();
1406 $this->db->rollback();
1420 global $hookmanager;
1429 $this->context[
'createfromclone'] = 1;
1432 for ($i = 0; $i < $num; $i++) {
1434 $src_line =
$object->lines[$i];
1435 '@phan-var-force FactureLigne $src_line';
1436 $line->libelle = $src_line->libelle;
1437 $line->label = $src_line->label;
1438 $line->desc = $src_line->desc;
1439 $line->subprice = $src_line->subprice;
1440 $line->total_ht = $src_line->total_ht;
1441 $line->total_tva = $src_line->total_tva;
1442 $line->total_localtax1 = $src_line->total_localtax1;
1443 $line->total_localtax2 = $src_line->total_localtax2;
1444 $line->total_ttc = $src_line->total_ttc;
1445 $line->vat_src_code = $src_line->vat_src_code;
1446 $line->tva_tx = $src_line->tva_tx;
1447 $line->localtax1_tx = $src_line->localtax1_tx;
1448 $line->localtax2_tx = $src_line->localtax2_tx;
1449 $line->qty = $src_line->qty;
1450 $line->fk_remise_except = $src_line->fk_remise_except;
1451 $line->remise_percent = $src_line->remise_percent;
1452 $line->fk_product = $src_line->fk_product;
1453 $line->info_bits = $src_line->info_bits;
1454 $line->product_type = $src_line->product_type;
1455 $line->rang = $src_line->rang;
1456 $line->special_code = $src_line->special_code;
1457 $line->fk_parent_line = $src_line->fk_parent_line;
1458 $line->fk_unit = $src_line->fk_unit;
1459 $line->date_start = $src_line->date_start;
1460 $line->date_end = $src_line->date_end;
1463 $line->fk_multicurrency = $src_line->fk_multicurrency;
1464 $line->multicurrency_code = $src_line->multicurrency_code;
1465 $line->multicurrency_subprice = $src_line->multicurrency_subprice;
1466 $line->multicurrency_total_ht = $src_line->multicurrency_total_ht;
1467 $line->multicurrency_total_tva = $src_line->multicurrency_total_tva;
1468 $line->multicurrency_total_ttc = $src_line->multicurrency_total_ttc;
1470 $line->fk_fournprice = $src_line->fk_fournprice;
1471 $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);
1472 $line->pa_ht = $marginInfos[0];
1475 $src_line->fetch_optionals();
1476 foreach ($src_line->array_options as $options_key => $value) {
1477 $line->array_options[$options_key] = $value;
1480 $this->lines[$i] = $line;
1483 $this->socid =
$object->socid;
1484 $this->fk_project =
$object->fk_project;
1485 $this->fk_account =
$object->fk_account;
1486 $this->cond_reglement_id =
$object->cond_reglement_id;
1487 $this->mode_reglement_id =
$object->mode_reglement_id;
1488 $this->fk_incoterms =
$object->fk_incoterms;
1489 $this->location_incoterms =
$object->location_incoterms;
1490 $this->availability_id =
$object->availability_id;
1491 $this->demand_reason_id =
$object->demand_reason_id;
1492 $this->delivery_date =
$object->delivery_date;
1493 $this->fk_delivery_address =
$object->fk_delivery_address;
1494 $this->contact_id =
$object->contact_id;
1495 $this->ref_client =
$object->ref_client;
1496 $this->ref_customer =
$object->ref_client;
1499 $this->note_private =
$object->note_private;
1500 $this->note_public =
$object->note_public;
1503 $this->module_source =
$object->module_source;
1504 $this->pos_source =
$object->pos_source;
1506 $this->origin =
$object->element;
1507 $this->origin_type =
$object->element;
1508 $this->origin_id =
$object->id;
1510 $this->fk_user_author = $user->id;
1511 $this->user_creation_id = $user->id;
1515 foreach (
$object->array_options as $options_key => $value) {
1516 $this->array_options[$options_key] = $value;
1520 $this->linked_objects[$this->origin] = $this->origin_id;
1521 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1522 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1525 $ret = $this->
create($user);
1529 $hookmanager->initHooks(array(
'invoicedao'));
1531 $parameters = array(
'objFrom' =>
$object);
1533 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1559 global $hookmanager;
1567 $use_all_lines = empty($lines);
1569 for ($i = 0; $i < $num; $i++) {
1570 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1576 $line->libelle =
$object->lines[$i]->libelle;
1577 $line->label =
$object->lines[$i]->label;
1578 $line->desc =
$object->lines[$i]->desc;
1579 $line->subprice =
$object->lines[$i]->subprice;
1580 $line->total_ht =
$object->lines[$i]->total_ht;
1581 $line->total_tva =
$object->lines[$i]->total_tva;
1582 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1583 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1584 $line->total_ttc =
$object->lines[$i]->total_ttc;
1585 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1586 $line->tva_tx =
$object->lines[$i]->tva_tx;
1587 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1588 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1589 $line->qty =
$object->lines[$i]->qty;
1590 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1591 $line->remise_percent =
$object->lines[$i]->remise_percent;
1592 $line->fk_product =
$object->lines[$i]->fk_product;
1593 $line->info_bits =
$object->lines[$i]->info_bits;
1594 $line->product_type =
$object->lines[$i]->product_type;
1595 $line->rang =
$object->lines[$i]->rang;
1596 $line->special_code =
$object->lines[$i]->special_code;
1597 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1598 $line->fk_unit =
$object->lines[$i]->fk_unit;
1599 $line->date_start =
$object->lines[$i]->date_start;
1600 $line->date_end =
$object->lines[$i]->date_end;
1603 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1604 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1605 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1606 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1607 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1608 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1610 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1612 $line->pa_ht = $marginInfos[0];
1615 $object->lines[$i]->fetch_optionals();
1616 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1617 $line->array_options[$options_key] = $value;
1620 $this->lines[$i] = $line;
1623 $this->socid =
$object->socid;
1624 $this->fk_project =
$object->fk_project;
1625 $this->fk_account =
$object->fk_account;
1626 $this->cond_reglement_id =
$object->cond_reglement_id;
1627 $this->mode_reglement_id =
$object->mode_reglement_id;
1628 $this->availability_id =
$object->availability_id;
1629 $this->demand_reason_id =
$object->demand_reason_id;
1630 $this->delivery_date =
$object->delivery_date;
1631 $this->fk_delivery_address =
$object->fk_delivery_address;
1632 $this->contact_id =
$object->contact_id;
1633 $this->ref_client =
$object->ref_client;
1636 $this->note_private =
$object->note_private;
1637 $this->note_public =
$object->note_public;
1640 $this->module_source =
$object->module_source;
1641 $this->pos_source =
$object->pos_source;
1643 $this->origin =
$object->element;
1644 $this->origin_id =
$object->id;
1646 $this->fk_user_author = $user->id;
1650 foreach (
$object->array_options as $options_key => $value) {
1651 $this->array_options[$options_key] = $value;
1655 $this->linked_objects[$this->origin] = $this->origin_id;
1656 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1657 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1660 $ret = $this->
create($user);
1664 $hookmanager->initHooks(array(
'invoicedao'));
1666 $parameters = array(
'objFrom' =>
$object);
1668 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1698 global
$conf, $langs, $hookmanager, $action;
1700 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1701 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1706 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1710 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1713 $origin->error =
'ErrorDateIsInFuture';
1717 if ($payment_terms_id <= 0) {
1718 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1722 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1724 if (empty($payment_conditions_deposit_percent)) {
1725 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1729 if (empty($origin->deposit_percent)) {
1730 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1734 $deposit =
new self($origin->db);
1735 $deposit->socid = $origin->socid;
1737 $deposit->fk_project = $origin->fk_project;
1738 $deposit->ref_client = $origin->ref_client;
1739 $deposit->ref_customer = $origin->ref_client;
1740 $deposit->date = $date;
1741 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1742 $deposit->cond_reglement_id = $payment_terms_id;
1743 $deposit->availability_id = $origin->availability_id;
1744 $deposit->demand_reason_id = $origin->demand_reason_id;
1745 $deposit->fk_account = $origin->fk_account;
1746 $deposit->fk_incoterms = $origin->fk_incoterms;
1747 $deposit->location_incoterms = $origin->location_incoterms;
1748 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1749 $deposit->multicurrency_code = $origin->multicurrency_code;
1750 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1751 $deposit->module_source = $origin->module_source;
1752 $deposit->pos_source = $origin->pos_source;
1753 $deposit->model_pdf =
'crabe';
1755 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1764 $deposit->note_private = $origin->note_private;
1765 $deposit->note_public = $origin->note_public;
1768 $deposit->origin = $origin->element;
1769 $deposit->origin_id = $origin->id;
1771 $origin->fetch_optionals();
1773 foreach ($origin->array_options as $extrakey => $value) {
1774 $deposit->array_options[$extrakey] = $value;
1777 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1779 foreach ($overrideFields as $key => $value) {
1780 $deposit->$key = $value;
1783 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1785 $origin->db->begin();
1788 $createReturn = $deposit->create($user, $notrigger);
1790 if ($createReturn <= 0) {
1791 $origin->db->rollback();
1792 $origin->error = $deposit->error;
1793 $origin->errors = $deposit->errors;
1797 $amount_ttc_diff = 0;
1798 $amountdeposit = array();
1799 $descriptions = array();
1806 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1808 $TTotalByTva = array();
1809 foreach ($origin->lines as &$line) {
1810 if (!empty($line->special_code)) {
1813 $key = $line->tva_tx . ($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
1814 if (!array_key_exists($key, $TTotalByTva)) {
1815 $TTotalByTva[$key] = 0;
1816 $descriptions[$key] =
'';
1818 $TTotalByTva[$key] += $line->total_ttc;
1819 $descriptions[$key] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1820 $descriptions[$key] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1821 $descriptions[$key] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1822 $descriptions[$key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1825 foreach ($TTotalByTva as $tva => &$total) {
1826 $tva_rate_only = preg_replace(
'/\s*\(.*\)/',
'', (
string) $tva);
1827 $coef = $total / $origin->total_ttc;
1828 $am = $amount * $coef;
1829 $amount_ttc_diff += $am;
1830 $amountdeposit[$tva] += $am / (1 + ((float) $tva_rate_only) / 100);
1834 $lines = $origin->lines;
1835 $numlines = count($lines);
1836 for ($i = 0; $i < $numlines; $i++) {
1837 if (empty($lines[$i]->qty)) {
1840 if (!empty($lines[$i]->special_code)) {
1844 $totalamount += $lines[$i]->total_ht;
1845 $tva_key = $lines[$i]->tva_tx . ($lines[$i]->vat_src_code ?
' ('.$lines[$i]->vat_src_code.
')' :
'');
1846 if (!isset($amountdeposit[$tva_key])) {
1847 $amountdeposit[$tva_key] = 0;
1848 $descriptions[$tva_key] =
'';
1850 $amountdeposit[$tva_key] += ((float) $lines[$i]->total_ht * (
float) $origin->deposit_percent) / 100;
1851 $descriptions[$tva_key] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1852 $descriptions[$tva_key] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1853 $descriptions[$tva_key] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1854 $descriptions[$tva_key] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1857 if ($totalamount == 0) {
1858 $amountdeposit[0] = 0;
1861 $amount_ttc_diff = $amountdeposit[0] ?? 0;
1864 foreach ($amountdeposit as $tva => $amount) {
1865 if (empty($amount)) {
1869 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1872 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1873 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1876 $addlineResult = $deposit->addline(
1903 if ($addlineResult < 0) {
1904 $origin->db->rollback();
1905 $origin->error = $deposit->error;
1906 $origin->errors = $deposit->errors;
1911 $diff = $deposit->total_ttc - $amount_ttc_diff;
1914 $deposit->fetch_lines();
1915 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1919 $tva_tx_with_code = $deposit->lines[0]->tva_tx . ($deposit->lines[0]->vat_src_code ?
' ('.$deposit->lines[0]->vat_src_code.
')' :
'');
1920 $updatelineResult = $deposit->updateline(
1921 $deposit->lines[0]->id,
1922 $deposit->lines[0]->desc,
1924 $deposit->lines[0]->qty,
1925 $deposit->lines[0]->remise_percent,
1926 $deposit->lines[0]->date_start,
1927 $deposit->lines[0]->date_end,
1932 $deposit->lines[0]->info_bits,
1933 $deposit->lines[0]->product_type,
1937 $deposit->lines[0]->pa_ht,
1938 $deposit->lines[0]->label,
1944 if ($updatelineResult < 0) {
1945 $origin->db->rollback();
1946 $origin->error = $deposit->error;
1947 $origin->errors = $deposit->errors;
1952 $hookmanager->initHooks(array(
'invoicedao'));
1954 $parameters = array(
'objFrom' => $origin);
1955 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1958 $origin->db->rollback();
1959 $origin->error = $hookmanager->error;
1960 $origin->errors = $hookmanager->errors;
1964 if (!empty($autoValidateDeposit)) {
1965 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1967 if ($validateReturn < 0) {
1968 $origin->db->rollback();
1969 $origin->error = $deposit->error;
1970 $origin->errors = $deposit->errors;
1975 unset($deposit->context[
'createdepositfromorigin']);
1977 $origin->db->commit();
1991 global
$conf, $langs, $mysoc, $user;
1993 $langs->load(
'bills');
1996 $moretitle = $params[
'moretitle'] ??
'';
1998 $picto = $this->picto;
1999 if ($this->
type == self::TYPE_REPLACEMENT) {
2002 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2005 if ($this->
type == self::TYPE_DEPOSIT) {
2009 if ($user->hasRight(
"facture",
"read")) {
2010 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
2012 $datas[
'picto'] .=
' '.$this->getLibType(1);
2015 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
2018 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalcreditnotes)) {
2021 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totaldeposits)) {
2024 if (isset($this->
status) && isset($this->totalpaid) && isset($this->totalcreditnotes) && isset($this->totaldeposits)) {
2025 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid + $this->totalcreditnotes + $this->totaldeposits);
2028 $datas[
'picto'] .=
' - '.$moretitle;
2030 if (!empty($this->
ref)) {
2031 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
2033 if (!empty($this->ref_customer)) {
2034 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
2036 if (!empty($this->date)) {
2037 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
2039 if (!empty($this->total_ht)) {
2040 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1,
$conf->currency);
2042 if (!empty($this->total_tva)) {
2043 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1,
$conf->currency);
2045 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
2046 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1,
$conf->currency);
2048 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
2050 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency);
2052 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
2053 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency);
2055 if (!empty($this->total_ttc)) {
2056 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency);
2077 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
2079 global $langs,
$conf, $user;
2081 if (!empty(
$conf->dol_no_mouse_hover)) {
2087 if ($option ==
'withdraw') {
2088 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2090 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2093 if (!$user->hasRight(
"facture",
"read")) {
2097 if ($option !==
'nolink') {
2099 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2100 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2101 $add_save_lastsearch_values = 1;
2103 if ($add_save_lastsearch_values) {
2104 $url .=
'&save_lastsearch_values=1';
2112 $picto = $this->picto;
2113 if ($this->
type == self::TYPE_REPLACEMENT) {
2116 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2119 if ($this->
type == self::TYPE_DEPOSIT) {
2125 'objecttype' => $this->element,
2126 'moretitle' => $moretitle,
2127 'option' => $option,
2129 $classfortooltip =
'classfortooltip';
2132 $classfortooltip =
'classforajaxtooltip';
2133 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2139 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2140 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2142 $label = $langs->trans(
"Invoice");
2143 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
2145 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
2146 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2149 $linkstart =
'<a href="'.$url.
'"';
2150 $linkstart .= $linkclose.
'>';
2153 if ($option ==
'nolink') {
2158 $result .= $linkstart;
2160 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2162 if ($withpicto != 2) {
2163 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2165 $result .= $linkend;
2167 if ($addlinktonotes) {
2168 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2170 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2171 $result .=
' <span class="note inline-block">';
2172 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dolPrintHTMLForAttribute($notetoshow).
'">';
2175 $result .=
'</span>';
2179 global $action, $hookmanager;
2180 $hookmanager->initHooks(array(
'invoicedao'));
2181 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2182 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2184 $result = $hookmanager->resPrint;
2186 $result .= $hookmanager->resPrint;
2202 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2204 global
$conf, $extrafields;
2206 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2210 $extraFieldsCheck =
false;
2211 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2213 if ($doFetchInOneSqlRequest) {
2215 if (!isset($extrafields) || !is_object($extrafields)) {
2216 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2221 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
2222 $extrafields->fetch_name_optionals_label($this->table_element);
2225 $extraFieldsCheck = (
2226 !empty($extrafields->attributes[$this->table_element][
'label'])
2227 && is_array($extrafields->attributes[$this->table_element][
'label'])
2228 && count($extrafields->attributes[$this->table_element][
'label']) > 0
2234 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2235 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2236 $sql .=
', f.datef as df, f.date_pointoftax';
2237 $sql .=
', f.date_lim_reglement as dlr';
2238 $sql .=
', f.datec as datec';
2239 $sql .=
', f.date_valid as datev';
2240 $sql .=
', f.tms as datem';
2241 $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';
2242 $sql .=
", f.fk_input_reason";
2243 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2244 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2245 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2246 $sql .=
', f.fk_account';
2247 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2248 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2249 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2250 $sql .=
', f.fk_incoterms, f.location_incoterms';
2251 $sql .=
', f.module_source, f.pos_source';
2252 $sql .=
", i.libelle as label_incoterms";
2253 $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";
2255 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2256 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2257 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2258 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2261 if ($type !==
'separate') {
2262 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2263 $sql .=
", ST_AsWKT(ef.".$key.
") as ".$key;
2265 $sql .=
", ef.".$key;
2271 $sql .=
' FROM '.$this->db->prefix().
'facture as f';
2274 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2276 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element.
'_extrafields as ef ON f.rowid = ef.fk_object';
2279 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2280 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_paiement as p ON f.fk_mode_reglement = p.id';
2281 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_input_reason as dr ON dr.rowid = f.fk_input_reason";
2282 $sql .=
' LEFT JOIN '.$this->db->prefix().
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2285 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2287 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2289 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2292 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2296 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2297 $resql = $this->db->query($sql);
2299 if ($this->db->num_rows($resql)) {
2300 $obj = $this->db->fetch_object($resql);
2302 $this->
id = $obj->rowid;
2303 $this->entity = $obj->entity;
2305 $this->
ref = $obj->ref;
2306 $this->ref_client = $obj->ref_client;
2307 $this->ref_customer = $obj->ref_client;
2308 $this->ref_ext = $obj->ref_ext;
2309 $this->
type = $obj->type;
2310 $this->subtype = $obj->subtype;
2311 $this->date = $this->db->jdate($obj->df);
2312 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2313 $this->date_creation = $this->db->jdate($obj->datec);
2314 $this->date_validation = $this->db->jdate($obj->datev);
2315 $this->date_modification = $this->db->jdate($obj->datem);
2316 $this->datem = $this->db->jdate($obj->datem);
2317 $this->total_ht = $obj->total_ht;
2318 $this->total_tva = $obj->total_tva;
2319 $this->total_localtax1 = $obj->localtax1;
2320 $this->total_localtax2 = $obj->localtax2;
2321 $this->total_ttc = $obj->total_ttc;
2322 $this->revenuestamp = $obj->revenuestamp;
2323 $this->paye = $obj->paye;
2324 $this->close_code = $obj->close_code;
2325 $this->close_note = $obj->close_note;
2327 $this->socid = $obj->fk_soc;
2328 $this->thirdparty =
null;
2330 $this->fk_project = $obj->fk_project;
2331 $this->project =
null;
2333 $this->statut = $obj->status;
2334 $this->
status = $obj->status;
2336 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2337 $this->mode_reglement_id = $obj->fk_mode_reglement;
2338 $this->mode_reglement_code = $obj->mode_reglement_code;
2339 $this->mode_reglement = $obj->mode_reglement_libelle;
2340 $this->cond_reglement_id = $obj->fk_cond_reglement;
2341 $this->cond_reglement_code = $obj->cond_reglement_code;
2342 $this->cond_reglement = $obj->cond_reglement_libelle;
2343 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2344 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2345 $this->fk_facture_source = $obj->fk_facture_source;
2346 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2347 $this->note = $obj->note_private;
2348 $this->note_private = $obj->note_private;
2349 $this->note_public = $obj->note_public;
2350 $this->user_creation_id = $obj->fk_user_author;
2351 $this->user_validation_id = $obj->fk_user_valid;
2352 $this->user_modification_id = $obj->fk_user_modif;
2353 $this->fk_user_author = $obj->fk_user_author;
2354 $this->fk_user_valid = $obj->fk_user_valid;
2355 $this->fk_user_modif = $obj->fk_user_modif;
2356 $this->model_pdf = $obj->model_pdf;
2357 $this->last_main_doc = $obj->last_main_doc;
2358 $this->demand_reason_id = $obj->fk_input_reason;
2359 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2360 $this->situation_counter = $obj->situation_counter;
2361 $this->situation_final = $obj->situation_final;
2362 $this->retained_warranty = $obj->retained_warranty;
2363 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2364 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2366 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2369 $this->fk_incoterms = $obj->fk_incoterms;
2370 $this->location_incoterms = $obj->location_incoterms;
2371 $this->label_incoterms = $obj->label_incoterms;
2373 $this->module_source = $obj->module_source;
2374 $this->pos_source = $obj->pos_source;
2377 $this->fk_multicurrency = $obj->fk_multicurrency;
2378 $this->multicurrency_code = $obj->multicurrency_code;
2379 $this->multicurrency_tx = $obj->multicurrency_tx;
2380 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2381 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2382 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2385 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2386 $this->array_options = array();
2388 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2389 $type = !empty($extrafields->attributes[$this->table_element][
'type'][$key])
2390 ? $extrafields->attributes[$this->table_element][
'type'][$key]
2393 if ($type !==
'separate') {
2394 $rawval = $obj->$key;
2397 if (in_array($type, array(
'date',
'datetime'))) {
2398 $this->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2399 } elseif ($type ==
'password') {
2400 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2401 $this->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2403 $this->array_options[
'options_' . $key] = $rawval;
2406 $this->array_options[
'options_' . $key] = $rawval;
2412 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
2413 if (!empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
2414 if (empty(
$conf->disable_compute)) {
2415 global $objectoffield;
2416 $objectoffield = $this;
2417 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
2423 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2427 if (!$doFetchInOneSqlRequest) {
2434 $this->lines = array();
2438 $this->error = $this->db->error();
2442 $this->db->free($resql);
2446 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2448 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2452 $this->error = $this->db->lasterror();
2467 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2469 global
$conf, $extrafields;
2472 $this->lines = array();
2474 $extraFieldsCheck =
false;
2475 $doFetchInOneSqlRequest =
getDolGlobalInt(
'MAIN_DO_FETCH_IN_ONE_SQL_REQUEST');
2477 if ($doFetchInOneSqlRequest) {
2479 if (!isset($extrafields) || !is_object($extrafields)) {
2480 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
2485 if (empty($extrafields->attributes[$this->table_element_line][
'loaded'])) {
2486 $extrafields->fetch_name_optionals_label($this->table_element_line);
2489 $extraFieldsCheck = (
2490 !empty($extrafields->attributes[$this->table_element_line][
'label'])
2491 && is_array($extrafields->attributes[$this->table_element_line][
'label'])
2492 && count($extrafields->attributes[$this->table_element_line][
'label']) > 0
2496 $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,';
2497 $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,';
2498 $sql .=
' l.situation_percent, l.fk_prev_id,';
2499 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2500 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2501 $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,';
2502 $sql .=
' l.fk_unit, l.extraparams,';
2503 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2504 $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';
2506 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2507 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2508 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2509 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2512 if ($type !==
'separate') {
2513 if (in_array($type, array(
'point',
'multipts',
'linestrg',
'polygon'))) {
2514 $sql .=
", ST_AsWKT(ef.".$key.
") as ".$key;
2516 $sql .=
", ef.".$key;
2522 $sql .=
' FROM '.$this->db->prefix().
'facturedet as l';
2525 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2527 $sql .=
' LEFT JOIN '.$this->db->prefix().$this->table_element_line.
'_extrafields as ef ON l.rowid = ef.fk_object';
2530 $sql .=
' LEFT JOIN '.$this->db->prefix().
'product as p ON l.fk_product = p.rowid';
2531 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2532 $sql .=
' ORDER BY l.rang, l.rowid';
2534 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2535 $result = $this->db->query($sql);
2537 $num = $this->db->num_rows($result);
2540 $objp = $this->db->fetch_object($result);
2543 $line->id = $objp->rowid;
2544 $line->rowid = $objp->rowid;
2545 $line->fk_facture = $objp->fk_facture;
2546 $line->label = $objp->custom_label;
2547 $line->desc = $objp->description;
2548 $line->description = $objp->description;
2549 $line->product_type = $objp->product_type;
2550 $line->ref = $objp->product_ref;
2551 $line->product_ref = $objp->product_ref;
2552 $line->libelle = $objp->product_label;
2553 $line->product_label = $objp->product_label;
2554 $line->product_barcode = $objp->product_barcode;
2555 $line->product_desc = $objp->product_desc;
2556 $line->fk_product_type = $objp->fk_product_type;
2557 $line->qty = $objp->qty;
2558 $line->subprice = $objp->subprice;
2559 $line->ref_ext = $objp->ref_ext;
2561 $line->vat_src_code = $objp->vat_src_code;
2562 $line->tva_tx = $objp->tva_tx;
2563 $line->localtax1_tx = $objp->localtax1_tx;
2564 $line->localtax2_tx = $objp->localtax2_tx;
2565 $line->localtax1_type = $objp->localtax1_type;
2566 $line->localtax2_type = $objp->localtax2_type;
2567 $line->remise_percent = $objp->remise_percent;
2568 $line->fk_remise_except = $objp->fk_remise_except;
2569 $line->fk_product = $objp->fk_product;
2570 $line->date_start = $this->db->jdate($objp->date_start);
2571 $line->date_end = $this->db->jdate($objp->date_end);
2572 $line->info_bits = $objp->info_bits;
2573 $line->total_ht = $objp->total_ht;
2574 $line->total_tva = $objp->total_tva;
2575 $line->total_localtax1 = $objp->total_localtax1;
2576 $line->total_localtax2 = $objp->total_localtax2;
2577 $line->total_ttc = $objp->total_ttc;
2579 $line->fk_fournprice = $objp->fk_fournprice;
2580 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2581 $line->pa_ht = $marginInfos[0];
2582 $line->marge_tx = (string) $marginInfos[1];
2583 $line->marque_tx = (string) $marginInfos[2];
2584 $line->rang = $objp->rang;
2585 $line->special_code = $objp->special_code;
2586 $line->fk_parent_line = $objp->fk_parent_line;
2587 $line->situation_percent = $objp->situation_percent;
2588 $line->fk_prev_id = $objp->fk_prev_id;
2589 $line->fk_unit = $objp->fk_unit;
2591 $line->extraparams = !empty($objp->extraparams) ? (array) json_decode($objp->extraparams,
true) : array();
2593 $line->batch = $objp->batch;
2594 $line->fk_warehouse = $objp->fk_warehouse;
2597 $line->fk_code_ventilation = $objp->fk_code_ventilation;
2600 $line->fk_multicurrency = $objp->fk_multicurrency;
2601 $line->multicurrency_code = $objp->multicurrency_code;
2602 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2603 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2604 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2605 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2607 $line->array_options = array();
2608 if ($doFetchInOneSqlRequest && $extraFieldsCheck) {
2609 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2610 $type = !empty($extrafields->attributes[$this->table_element_line][
'type'][$key])
2611 ? $extrafields->attributes[$this->table_element_line][
'type'][$key]
2614 if ($type !==
'separate') {
2615 $rawval = $objp->$key;
2618 if (in_array($type, array(
'date',
'datetime'))) {
2619 $line->array_options[
'options_' . $key] = $this->db->jdate($rawval);
2620 } elseif ($type ==
'password') {
2621 if (!empty($rawval) && preg_match(
'/^dolcrypt:/', $rawval)) {
2622 $line->array_options[
'options_' . $key] =
dolDecrypt($rawval);
2624 $line->array_options[
'options_' . $key] = $rawval;
2627 $line->array_options[
'options_' . $key] = $rawval;
2633 foreach ($extrafields->attributes[$this->table_element_line][
'label'] as $key => $val) {
2634 if (!empty($extrafields->attributes[$this->table_element_line][
'computed'][$key])) {
2635 if (empty(
$conf->disable_compute)) {
2636 global $objectoffield;
2637 $objectoffield = $line;
2638 $line->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element_line][
'computed'][$key], 1, 0,
'2');
2644 if (!$doFetchInOneSqlRequest) {
2646 $line->fetch_optionals();
2650 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2651 $tmpproduct =
new Product($this->db);
2652 $tmpproduct->fetch($objp->fk_product);
2653 $tmpproduct->getMultiLangs();
2655 $line->multilangs = $tmpproduct->multilangs;
2658 $this->lines[$i] = $line;
2662 $this->db->free($result);
2665 $this->error = $this->db->error();
2680 $this->tab_previous_situation_invoice = array();
2681 $this->tab_next_situation_invoice = array();
2683 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2684 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2685 $sql .=
' AND entity = '.((int) $this->entity);
2686 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2687 $sql .=
' ORDER BY situation_counter ASC';
2689 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2690 $result = $this->db->query($sql);
2691 if ($result && $this->db->num_rows($result) > 0) {
2692 while ($objp = $this->db->fetch_object($result)) {
2693 $invoice =
new Facture($this->db);
2694 if ($invoice->fetch($objp->rowid) > 0) {
2695 if ($objp->situation_counter < $this->situation_counter
2696 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2698 $this->tab_previous_situation_invoice[] = $invoice;
2700 $this->tab_next_situation_invoice[] = $invoice;
2719 if (empty($this->
type)) {
2722 if (isset($this->subtype)) {
2723 $this->subtype = (int) trim((
string) $this->subtype);
2725 if (isset($this->
ref)) {
2726 $this->
ref = trim($this->
ref);
2728 if (isset($this->ref_ext)) {
2729 $this->ref_ext = trim($this->ref_ext);
2731 if (!empty($this->ref_customer)) {
2732 $this->ref_customer = trim($this->ref_customer);
2734 if (isset($this->increment)) {
2735 $this->increment = trim($this->increment);
2737 if (isset($this->close_code)) {
2738 $this->close_code = trim($this->close_code);
2740 if (isset($this->close_note)) {
2741 $this->close_note = trim($this->close_note);
2743 if (isset($this->note) || isset($this->note_private)) {
2744 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2746 if (isset($this->note) || isset($this->note_private)) {
2747 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2749 if (isset($this->note_public)) {
2750 $this->note_public = trim($this->note_public);
2752 if (isset($this->model_pdf)) {
2753 $this->model_pdf = trim($this->model_pdf);
2755 if (isset($this->import_key)) {
2756 $this->import_key = trim($this->import_key);
2758 if (isset($this->retained_warranty)) {
2759 $this->retained_warranty = (float) $this->retained_warranty;
2761 if (!isset($this->user_creation_id) && isset($this->fk_user_author)) {
2762 $this->user_creation_id = $this->fk_user_author;
2764 if (!isset($this->user_validation_id) && isset($this->fk_user_valid)) {
2765 $this->user_validation_id = $this->fk_user_valid;
2769 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2770 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2771 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2772 $sql .=
" type=".(isset($this->
type) ? $this->db->escape((
string) $this->type) :
"null").
",";
2773 $sql .=
" subtype=".(isset($this->subtype) ? $this->db->escape((
string) $this->subtype) :
"null").
",";
2774 $sql .=
" ref_client=".(!empty($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2775 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2776 $sql .=
" fk_soc=".(isset($this->socid) ? $this->db->escape((
string) $this->socid) :
"null").
",";
2777 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2778 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2779 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2780 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2781 $sql .=
" paye=".(isset($this->paye) ? $this->db->escape((
string) $this->paye) : 0).
",";
2782 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2783 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2784 $sql .=
" total_tva=".((float) $this->total_tva).
",";
2785 $sql .=
" localtax1=".((float) $this->total_localtax1).
",";
2786 $sql .=
" localtax2=".((float) $this->total_localtax2).
",";
2787 $sql .=
" total_ht=".((float) $this->total_ht).
",";
2788 $sql .=
" total_ttc=".((float) $this->total_ttc).
",";
2789 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2790 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2791 $sql .=
" fk_user_author=".(isset($this->user_creation_id) ? ((int) $this->user_creation_id) :
"null").
",";
2792 $sql .=
" fk_user_valid=".(isset($this->user_validation_id) ? (int) $this->user_validation_id :
"null").
",";
2793 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2794 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2795 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2796 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2797 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2798 $sql .=
" note_private = ".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2799 $sql .=
" note_public = ".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2800 $sql .=
" model_pdf = ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2801 $sql .=
" import_key = ".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2802 $sql .=
" module_source = ".(isset($this->module_source) ?
"'".$this->db->escape($this->module_source).
"'" :
"null").
",";
2803 $sql .=
" pos_source = ".(isset($this->pos_source) ?
"'".$this->db->escape($this->pos_source).
"'" :
"null").
",";
2804 $sql .=
" situation_cycle_ref = ".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2805 $sql .=
" situation_counter = ".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2806 $sql .=
" situation_final = ".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2807 $sql .=
" retained_warranty = ".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2808 $sql .=
" retained_warranty_date_limit = ".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2809 $sql .=
" retained_warranty_fk_cond_reglement = ".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2810 $sql .=
" WHERE rowid = ".((int) $this->
id);
2814 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2815 $resql = $this->db->query($sql);
2818 $this->errors[] =
"Error ".$this->db->lasterror();
2828 if (!$error && !$notrigger) {
2839 foreach ($this->errors as $errmsg) {
2840 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2841 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2843 $this->db->rollback();
2846 $this->db->commit();
2864 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2865 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2870 $result = $remise->fetch($idremise);
2873 if ($remise->fk_facture) {
2874 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2875 $this->db->rollback();
2880 $facligne->fk_facture = $this->id;
2881 $facligne->fk_remise_except = $remise->id;
2882 $facligne->desc = $remise->description;
2883 $facligne->vat_src_code = $remise->vat_src_code;
2884 $facligne->tva_tx = $remise->tva_tx;
2885 $facligne->subprice = -(float) $remise->amount_ht;
2886 $facligne->fk_product = 0;
2888 $facligne->remise_percent = 0;
2889 $facligne->rang = -1;
2890 $facligne->info_bits = 2;
2893 $facligne->rang = 1;
2894 $linecount = count($this->lines);
2895 for ($ii = 1; $ii <= $linecount; $ii++) {
2901 if ($remise->fk_facture_source > 0) {
2902 $srcinvoice =
new Facture($this->db);
2903 $srcinvoice->fetch($remise->fk_facture_source);
2904 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2906 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2907 $facligne->pa_ht = $arraytmp[
'pa_total'];
2910 $facligne->total_ht = -(float) $remise->amount_ht;
2911 $facligne->total_tva = -(float) $remise->amount_tva;
2912 $facligne->total_ttc = -(float) $remise->amount_ttc;
2914 $facligne->multicurrency_subprice = -(float) $remise->multicurrency_subprice;
2915 $facligne->multicurrency_total_ht = -(float) $remise->multicurrency_amount_ht;
2916 $facligne->multicurrency_total_tva = -(float) $remise->multicurrency_amount_tva;
2917 $facligne->multicurrency_total_ttc = -(float) $remise->multicurrency_amount_ttc;
2919 $lineid = $facligne->insert();
2924 $result = $remise->link_to_invoice($lineid, 0);
2926 $this->error = $remise->error;
2927 $this->db->rollback();
2931 $this->db->commit();
2934 $this->error = $facligne->error;
2935 $this->db->rollback();
2939 $this->error = $facligne->error;
2940 $this->db->rollback();
2944 $this->db->rollback();
2966 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
2967 if (empty($ref_client)) {
2968 $sql .=
" SET ref_client = NULL";
2970 $sql .=
" SET ref_client = '".$this->db->escape($ref_client).
"'";
2972 $sql .=
" WHERE rowid = ".((int) $this->
id);
2974 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2975 $resql = $this->db->query($sql);
2977 $this->errors[] = $this->db->error();
2982 $this->ref_client = $ref_client;
2983 $this->ref_customer = $ref_client;
2986 if (!$notrigger && empty($error)) {
2996 $this->ref_client = $ref_client;
2997 $this->ref_customer = $ref_client;
2999 $this->db->commit();
3002 foreach ($this->errors as $errmsg) {
3003 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
3004 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
3006 $this->db->rollback();
3026 dol_syslog(__METHOD__.
' : inputReasonId='.$inputReasonId, LOG_DEBUG);
3027 if ($this->
status >= self::STATUS_DRAFT) {
3029 $this->demand_reason_id = $inputReasonId;
3033 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3034 $sql .=
" SET fk_input_reason = ".($inputReasonId > 0 ? (int) $inputReasonId :
'null');
3035 $sql .=
" WHERE rowid = ".((int) $this->
id);
3038 $res = $this->db->query($sql);
3041 $this->error = $this->db->lasterror();
3042 $this->errors[] = $this->error;
3057 $this->db->commit();
3059 $this->demand_reason_id = $this->oldcopy->demand_reason_id;
3060 $this->db->rollback();
3061 dol_syslog(__METHOD__.
' Error : '.$this->errorsToString(), LOG_ERR);
3082 public function delete($user, $notrigger = 0, $idwarehouse = -1)
3084 global $langs,
$conf;
3085 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3089 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
3102 if (!$error && !$notrigger) {
3113 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"categorie_invoice";
3114 $sql .=
" WHERE fk_invoice = ".((int) $this->
id);
3116 $result = $this->db->query($sql);
3119 $this->errors[] = $this->db->lasterror();
3128 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
3142 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
3143 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
3144 $sql .=
' AND fk_facture_line IS NULL';
3145 $resql = $this->db->query($sql);
3149 $list_rowid_det = array();
3150 foreach ($this->lines as $key => $invoiceline) {
3151 $list_rowid_det[] = $invoiceline->id;
3155 if (count($list_rowid_det)) {
3156 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3157 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
3158 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
3160 if (!$this->db->query($sql)) {
3161 $this->error = $this->db->error().
" sql=".$sql;
3162 $this->errors[] = $this->error;
3163 $this->db->rollback();
3170 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
3171 $sql .=
' SET fk_invoice = NULL';
3172 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
3174 if (!$this->db->query($sql)) {
3175 $this->error = $this->db->error().
" sql=".$sql;
3176 $this->errors[] = $this->error;
3177 $this->db->rollback();
3181 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
3182 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
3183 $sql .=
' WHERE invoice_id = '.((int) $rowid);
3185 if (!$this->db->query($sql)) {
3186 $this->error = $this->db->error().
" sql=".$sql;
3187 $this->errors[] = $this->error;
3188 $this->db->rollback();
3193 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
3194 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3195 $langs->load(
"agenda");
3197 $num = count($this->lines);
3198 for ($i = 0; $i < $num; $i++) {
3199 if ($this->lines[$i]->fk_product > 0) {
3201 $mouvP->origin = &$this;
3202 $mouvP->setOrigin($this->element, $this->
id);
3204 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3205 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3207 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
3214 $main = MAIN_DB_PREFIX.
'facturedet';
3215 $ef = $main.
"_extrafields";
3216 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
3218 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
3221 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
3223 $resql = $this->db->query($sql);
3231 if ($conf->facture->dir_output && !empty($this->
ref)) {
3232 $dir =
$conf->facture->dir_output.
"/".$ref;
3233 $file =
$conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
3234 if (file_exists($file)) {
3238 $langs->load(
"errors");
3239 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
3240 $this->errors[] = $this->error;
3241 $this->db->rollback();
3245 if (file_exists($dir)) {
3247 $langs->load(
"errors");
3248 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
3249 $this->errors[] = $this->error;
3250 $this->db->rollback();
3256 $this->db->commit();
3259 $this->error = $this->db->lasterror().
" sql=".$sql;
3260 $this->errors[] = $this->error;
3261 $this->db->rollback();
3265 $this->error = $this->db->lasterror().
" sql=".$sql;
3266 $this->errors[] = $this->error;
3267 $this->db->rollback();
3271 $this->db->rollback();
3288 public function set_paid($user, $close_code =
'', $close_note =
'')
3291 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
3292 return $this->
setPaid($user, $close_code, $close_note);
3305 public function setPaid($user, $close_code =
'', $close_note =
'')
3309 if ($this->paye != 1 || $this->
status != self::STATUS_CLOSED) {
3314 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
3316 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3317 $sql .=
' fk_statut = '.self::STATUS_CLOSED;
3319 $sql .=
', paye = 1';
3322 $sql .=
", close_code = '".$this->db->escape($close_code).
"'";
3325 $sql .=
", close_note = '".$this->db->escape($close_note).
"'";
3327 $sql .=
', fk_user_closing = '.((int) $user->id);
3328 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3329 $sql .=
" WHERE rowid = ".((int) $this->
id);
3331 $resql = $this->db->query($sql);
3341 $this->error = $this->db->lasterror();
3347 $this->db->commit();
3350 $this->db->rollback();
3373 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3391 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3392 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3393 $sql .=
' date_closing=null,';
3394 $sql .=
' fk_user_closing=null';
3395 $sql .=
" WHERE rowid = ".((int) $this->
id);
3397 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3398 $resql = $this->db->query($sql);
3408 $this->error = $this->db->error();
3413 $this->db->commit();
3416 $this->db->rollback();
3438 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3439 return $this->
setCanceled($user, $close_code, $close_note);
3452 public function setCanceled($user, $close_code =
'', $close_note =
'')
3454 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3459 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3460 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3462 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3465 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3467 $sql .=
', fk_user_closing = '.((int) $user->id);
3468 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3469 $sql .=
" WHERE rowid = ".((int) $this->
id);
3471 $resql = $this->db->query($sql);
3475 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3476 $sql .=
' SET fk_facture = NULL';
3477 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3479 $resql = $this->db->query($sql);
3484 $this->db->rollback();
3489 $this->db->commit();
3492 $this->error = $this->db->error().
" sql=".$sql;
3493 $this->db->rollback();
3497 $this->error = $this->db->error().
" sql=".$sql;
3498 $this->db->rollback();
3515 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3517 global
$conf, $langs, $mysoc;
3518 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3520 $productStatic =
null;
3521 $warehouseStatic =
null;
3522 $productbatch =
null;
3523 if ($batch_rule > 0) {
3524 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3525 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3526 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3527 $productStatic =
new Product($this->db);
3528 $warehouseStatic =
new Entrepot($this->db);
3535 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3542 if ($this->
status != self::STATUS_DRAFT) {
3543 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3546 if (count($this->lines) <= 0) {
3547 $langs->load(
"errors");
3548 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3552 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3553 $this->error =
'Permission denied';
3554 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3557 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3565 if (!$last_of_type[0]) {
3566 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3572 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3573 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'TVA_INTRA',
'ACCOUNTANCY_CODE_CUSTOMER');
3574 foreach ($array_to_check as $key) {
3575 $keymin = strtolower($key);
3576 if (!property_exists($this->thirdparty, $keymin)) {
3579 $vallabel = $this->thirdparty->$keymin;
3581 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3583 if ($this->thirdparty->isACompany()) {
3585 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3586 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3588 $langs->load(
"errors");
3589 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3590 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3596 if ($key ==
'EMAIL') {
3599 $langs->load(
"errors");
3600 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3601 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3605 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3607 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta_client)) {
3608 $langs->load(
"errors");
3609 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3610 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3614 if ($key ==
'TVA_INTRA') {
3617 if (($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra) && $this->thirdparty->isInEEC()) {
3618 $langs->load(
"errors");
3619 $this->error = $langs->trans(
'ErrorProdIdIsMandatoryForEuThirdparties', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3620 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3623 } elseif (
getDolGlobalString(
'SOCIETE_VAT_INTRA_INVOICE_MANDATORY') && ($this->thirdparty->tva_assuj) && empty($this->thirdparty->tva_intra)) {
3624 $langs->load(
"errors");
3625 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transnoentitiesnoconv(
'VATIntra')).
' ('.$langs->transnoentitiesnoconv(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3626 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3635 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3636 foreach ($array_to_check as $key => $val) {
3637 $keymin = strtolower($key);
3638 $vallabel = $this->$keymin;
3641 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3643 $langs->load(
"errors");
3645 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3652 if ($this->
type == self::TYPE_REPLACEMENT) {
3654 if ($this->fk_facture_source <= 0) {
3655 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3656 $this->db->rollback();
3661 $facreplaced =
new Facture($this->db);
3662 $result = $facreplaced->fetch($this->fk_facture_source);
3664 $this->error = $langs->trans(
"ErrorBadInvoice");
3665 $this->db->rollback();
3670 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3671 if ($idreplacement && $idreplacement != $this->
id) {
3672 $facreplacement =
new Facture($this->db);
3673 $facreplacement->fetch($idreplacement);
3674 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3675 $this->db->rollback();
3679 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3681 $this->error = $facreplaced->error;
3682 $this->db->rollback();
3688 if ($force_number) {
3689 $num = $force_number;
3690 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3703 $this->oldref = $this->ref;
3711 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3712 $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).
"'";
3714 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3715 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3717 $sql .=
" WHERE rowid = ".((int) $this->
id);
3719 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3720 $resql = $this->db->query($sql);
3722 $this->error = $this->db->lasterror();
3729 $result = $this->thirdparty->setAsCustomer();
3732 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3733 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3734 $langs->load(
"agenda");
3737 $cpt = count($this->lines);
3738 for ($i = 0; $i < $cpt; $i++) {
3739 if ($this->lines[$i]->fk_product > 0) {
3741 $mouvP->origin = &$this;
3742 $mouvP->setOrigin($this->element, $this->
id);
3745 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3748 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3751 $this->error = $mouvP->error;
3752 $this->errors = array_merge($this->errors, $mouvP->errors);
3758 $is_batch_line =
false;
3759 if ($batch_rule > 0) {
3760 $productStatic->fetch($this->lines[$i]->fk_product);
3761 if ($productStatic->hasbatch() && is_object($productbatch)) {
3762 $is_batch_line =
true;
3763 $product_qty_remain = $this->lines[$i]->qty;
3769 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3770 $sortorder =
'ASC,ASC,ASC,ASC';
3773 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_DISALLOW_NEGATIVE_TRANSFER') ? 0 :
null), $sortfield, $sortorder);
3774 if (!is_array($resBatchList)) {
3776 $this->error = $this->db->lasterror();
3780 $batchList = $resBatchList;
3781 if (empty($batchList)) {
3783 $langs->load(
'errors');
3784 $warehouseStatic->fetch($idwarehouse);
3785 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3786 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3789 foreach ($batchList as $batch) {
3790 if ($batch->qty <= 0) {
3795 if ($batch->qty >= $product_qty_remain) {
3796 $product_batch_qty = $product_qty_remain;
3799 $product_batch_qty = $batch->qty;
3801 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3804 $this->error = $mouvP->error;
3805 $this->errors = array_merge($this->errors, $mouvP->errors);
3809 $product_qty_remain -= $product_batch_qty;
3811 if ($product_qty_remain <= 0) {
3816 if (!$error && $product_qty_remain > 0) {
3819 $langs->load(
'errors');
3820 $warehouseStatic->fetch($idwarehouse);
3821 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3822 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3825 $batch = $batchList[0];
3826 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3829 $this->error = $mouvP->error;
3830 $this->errors = array_merge($this->errors, $mouvP->errors);
3838 if (!$is_batch_line) {
3839 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3842 $this->error = $mouvP->error;
3843 $this->errors = array_merge($this->errors, $mouvP->errors);
3855 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3856 $invoice_situation =
new Facture($this->db);
3857 $result = $invoice_situation->fetch($this->fk_facture_source);
3858 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3859 $invoice_situation->situation_final = 0;
3861 $result = $invoice_situation->setFinal($user, 1);
3864 $this->error = $invoice_situation->error;
3865 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3871 if (!$error && !$notrigger) {
3882 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3884 $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).
"'";
3885 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3886 $resql = $this->db->query($sql);
3889 $this->error = $this->db->lasterror();
3891 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3892 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".(int)
$conf->entity;
3893 $resql = $this->db->query($sql);
3896 $this->error = $this->db->lasterror();
3912 $this->date_validation = $now;
3917 $nboflines = count($this->lines);
3918 while (($i < $nboflines) && $final) {
3919 $line = $this->lines[$i];
3920 '@phan-var-force FactureLigne $line';
3922 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3923 $current_progress = (float) $line->situation_percent;
3924 $full_progress = $previousprogress + $current_progress;
3925 $final = ($full_progress == 100);
3927 $final = ($line->situation_percent == 100);
3932 if (empty($final)) {
3933 $this->situation_final = 0;
3935 $this->situation_final = 1;
3945 if (!$error && preg_match(
'/^[\(]?PROV/i', $this->oldref)) {
3949 $dirsource =
$conf->facture->dir_output.
'/'.$oldref;
3950 $dirdest =
$conf->facture->dir_output.
'/'.$newref;
3951 if (!$error && file_exists($dirsource)) {
3952 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3954 if (@rename($dirsource, $dirdest)) {
3957 $listoffiles =
dol_dir_list(
$conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3958 foreach ($listoffiles as $fileentry) {
3959 $dirsource = $fileentry[
'name'];
3960 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3961 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3962 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3963 @rename($dirsource, $dirdest);
3970 $this->db->commit();
3973 $this->db->rollback();
3986 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3987 $is_last = $next_invoice->is_last_in_cycle();
3989 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
3990 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3994 foreach ($next_invoice->lines as $line) {
3995 '@phan-var-force FactureLigne $line';
3996 $result = $next_invoice->updateline(
4001 $line->remise_percent,
4005 $line->localtax1_tx,
4006 $line->localtax2_tx,
4009 $line->product_type,
4010 $line->fk_parent_line,
4012 $line->fk_fournprice,
4015 $line->special_code,
4016 $line->array_options,
4017 $line->situation_percent,
4022 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
4047 if ($this->
status == self::STATUS_DRAFT) {
4048 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
4056 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4057 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
4058 $sql .=
" WHERE rowid = ".((int) $this->
id);
4060 $result = $this->db->query($sql);
4063 $this->oldcopy = clone $this;
4067 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL')) {
4068 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
4069 $langs->load(
"agenda");
4071 $num = count($this->lines);
4072 for ($i = 0; $i < $num; $i++) {
4073 if ($this->lines[$i]->fk_product > 0) {
4075 $mouvP->origin = &$this;
4076 $mouvP->setOrigin($this->element, $this->
id);
4078 if ($this->
type == self::TYPE_CREDIT_NOTE) {
4079 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
4081 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
4088 $old_statut = $this->status;
4093 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
4096 $this->statut = $old_statut;
4097 $this->
status = $old_statut;
4101 $this->db->rollback();
4106 $this->db->commit();
4109 $this->db->rollback();
4113 $this->error = $this->db->error();
4114 $this->db->rollback();
4169 $remise_percent = 0,
4172 $fk_code_ventilation = 0,
4174 $fk_remise_except = 0,
4175 $price_base_type =
'HT',
4182 $fk_parent_line = 0,
4183 $fk_fournprice =
null,
4186 $array_options = array(),
4187 $situation_percent = 100,
4192 $noupdateafterinsertline = 0
4196 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4200 global $mysoc, $langs;
4202 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);
4204 if ($this->
status == self::STATUS_DRAFT) {
4205 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4208 if (empty($remise_percent)) {
4209 $remise_percent = 0;
4214 if (empty($info_bits)) {
4220 if (empty($fk_code_ventilation)) {
4221 $fk_code_ventilation = 0;
4223 if (empty($txtva)) {
4226 if (empty($txlocaltax1)) {
4229 if (empty($txlocaltax2)) {
4232 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4233 $fk_parent_line = 0;
4235 if (empty($fk_prev_id)) {
4236 $fk_prev_id =
'null';
4238 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4241 $situation_percent = 0;
4243 $situation_percent = 100;
4246 if (empty($ref_ext)) {
4250 $remise_percent = (float)
price2num($remise_percent);
4254 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4257 if (strpos((
string) $txtva,
'*') !==
false) {
4260 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4263 $txlocaltax1 = (float)
price2num($txlocaltax1);
4264 $txlocaltax2 = (float)
price2num($txlocaltax2);
4266 if ($price_base_type ==
'HT') {
4277 if ($date_start && $date_end && $date_start > $date_end) {
4278 $langs->load(
"errors");
4279 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4285 $product_type = $type;
4286 if (!empty($fk_product) && $fk_product > 0) {
4287 $product =
new Product($this->db);
4288 $result = $product->fetch($fk_product);
4289 $product_type = $product->type;
4293 $productChildrenNb = 0;
4295 $productChildrenNb = $product->hasFatherOrChild(1);
4297 if ($productChildrenNb > 0) {
4299 $product_stock =
null;
4300 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4301 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4302 if ($product_stock ===
null) {
4303 $product_stock = $componentStockWarehouse->real;
4305 $product_stock = min($product_stock, $componentStockWarehouse->real);
4308 if ($product_stock ===
null) {
4312 $product_stock = $product->stock_reel;
4315 if ($product_stock < $qty) {
4316 $langs->load(
"errors");
4317 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4318 $this->db->rollback();
4327 $tmpproduct =
new Product($this->db);
4328 $result = $tmpproduct->fetch($fk_product);
4329 if (abs($qty) < $tmpproduct->packaging) {
4330 $qty = (float) $tmpproduct->packaging;
4331 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'mesgs');
4333 if (!empty($tmpproduct->packaging) && $qty > $tmpproduct->packaging) {
4334 $coeff = intval(abs($qty) / $tmpproduct->packaging) + 1;
4335 $qty =
price2num((
float) $tmpproduct->packaging * $coeff,
'MS');
4336 setEventMessages($langs->trans(
'QtyRecalculatedWithPackaging'),
null,
'mesgs');
4344 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4345 $vat_src_code = $reg[1];
4346 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4354 $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);
4356 $total_ht = $tabprice[0];
4357 $total_tva = $tabprice[1];
4358 $total_ttc = $tabprice[2];
4359 $total_localtax1 = $tabprice[9];
4360 $total_localtax2 = $tabprice[10];
4361 $pu_ht = $tabprice[3];
4364 $multicurrency_total_ht = $tabprice[16];
4365 $multicurrency_total_tva = $tabprice[17];
4366 $multicurrency_total_ttc = $tabprice[18];
4367 $pu_ht_devise = $tabprice[19];
4371 if ($ranktouse == -1) {
4372 $rangmax = $this->
line_max($fk_parent_line);
4373 $ranktouse = $rangmax + 1;
4379 $this->line->context = $this->context;
4381 $this->line->fk_facture = $this->id;
4382 $this->line->label = $label;
4383 $this->line->desc = $desc;
4384 $this->line->ref_ext = $ref_ext;
4386 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : (float) $qty);
4387 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs((
float) $pu_ht) : (float) $pu_ht);
4389 $this->line->vat_src_code = $vat_src_code;
4390 $this->line->tva_tx = $txtva;
4391 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
4392 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
4393 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4394 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4396 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4397 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4398 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4399 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_localtax1) : (float) $total_localtax1);
4400 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $total_localtax2) : (float) $total_localtax2);
4402 $this->line->fk_product = $fk_product;
4403 $this->line->product_type = $product_type;
4404 $this->line->remise_percent = $remise_percent;
4405 $this->line->date_start = $date_start;
4406 $this->line->date_end = $date_end;
4407 $this->line->fk_code_ventilation = $fk_code_ventilation;
4408 $this->line->rang = $ranktouse;
4409 $this->line->info_bits = $info_bits;
4410 $this->line->fk_remise_except = $fk_remise_except;
4412 $this->line->special_code = $special_code;
4413 $this->line->fk_parent_line = $fk_parent_line;
4414 $this->line->origin = $origin;
4415 $this->line->origin_id = $origin_id;
4416 $this->line->situation_percent = $situation_percent;
4417 $this->line->fk_prev_id = $fk_prev_id;
4418 $this->line->fk_unit = $fk_unit;
4421 $this->line->fk_fournprice = $fk_fournprice;
4422 $this->line->pa_ht = $pa_ht;
4425 $this->line->fk_multicurrency = $this->fk_multicurrency;
4426 $this->line->multicurrency_code = $this->multicurrency_code;
4427 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4429 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4430 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4431 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4433 if (is_array($array_options) && count($array_options) > 0) {
4434 $this->line->array_options = $array_options;
4437 $result = $this->line->insert();
4440 if (empty($noupdateafterinsertline)) {
4444 if (!isset($this->context[
'createfromclone'])) {
4445 if (!empty($fk_parent_line)) {
4448 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4450 $linecount = count($this->lines);
4451 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4456 $this->lines[] = $this->line;
4458 foreach ($this->lines as $line) {
4459 if ($line->id == $origin_id) {
4460 $this->line->extraparams = $line->extraparams;
4461 $this->line->setExtraParameters();
4467 $this->db->commit();
4468 return $this->line->id;
4470 $this->error = $this->db->lasterror();
4471 $this->db->rollback();
4475 $this->error = $this->line->error;
4476 $this->errors = $this->line->errors;
4477 $this->db->rollback();
4481 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4482 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4518 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)
4524 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4527 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4529 global $mysoc, $langs;
4531 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);
4533 if ($this->
status == self::STATUS_DRAFT) {
4536 if (!$this->error) {
4537 $this->error = $langs->trans(
'invoiceLineProgressError');
4543 if ($date_start && $date_end && $date_start > $date_end) {
4544 $langs->load(
"errors");
4545 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4555 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4556 $fk_parent_line = 0;
4558 if (empty($special_code) || $special_code == 3) {
4561 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'' || $situation_percent ==
null) {
4564 $situation_percent = 0;
4566 $situation_percent = 100;
4569 if (empty($ref_ext)) {
4573 $remise_percent = (float)
price2num($remise_percent);
4577 $pu_ht_devise = (float)
price2num($pu_ht_devise);
4580 if (strpos((
string) $txtva,
'*') !==
false) {
4583 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4586 $txlocaltax1 = (float)
price2num($txlocaltax1);
4587 $txlocaltax2 = (float)
price2num($txlocaltax2);
4603 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4604 $vat_src_code = $reg[1];
4605 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4608 $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);
4610 $total_ht = $tabprice[0];
4611 $total_tva = $tabprice[1];
4612 $total_ttc = $tabprice[2];
4613 $total_localtax1 = $tabprice[9];
4614 $total_localtax2 = $tabprice[10];
4615 $pu_ht = $tabprice[3];
4616 $pu_tva = $tabprice[4];
4617 $pu_ttc = $tabprice[5];
4620 $multicurrency_total_ht = $tabprice[16];
4621 $multicurrency_total_tva = $tabprice[17];
4622 $multicurrency_total_ttc = $tabprice[18];
4623 $pu_ht_devise = $tabprice[19];
4628 if ($remise_percent > 0) {
4629 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4630 $price = ((float) $pu - $remise);
4636 $line->fetch($rowid);
4637 $line->fetch_optionals();
4639 if (!empty($line->fk_product)) {
4640 $product =
new Product($this->db);
4641 $result = $product->fetch($line->fk_product);
4642 $product_type = $product->type;
4646 $productChildrenNb = 0;
4648 $productChildrenNb = $product->hasFatherOrChild(1);
4650 if ($productChildrenNb > 0) {
4652 $product_stock =
null;
4653 $product->loadStockForVirtualProduct(
'warehouseopen', $qty);
4654 foreach ($product->stock_warehouse as $componentStockWarehouse) {
4655 if ($product_stock ===
null) {
4656 $product_stock = $componentStockWarehouse->real;
4658 $product_stock = min($product_stock, $componentStockWarehouse->real);
4661 if ($product_stock ===
null) {
4665 $product_stock = $product->stock_reel;
4668 if ($product_stock < $qty) {
4669 $langs->load(
"errors");
4670 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4671 $this->db->rollback();
4677 $staticline = clone $line;
4679 $line->oldline = $staticline;
4680 $this->line = $line;
4681 $this->line->context = $this->context;
4682 $this->line->rang = $rang;
4685 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4686 $rangmax = $this->
line_max($fk_parent_line);
4687 $this->line->rang = $rangmax + 1;
4689 $apply_abs_price_on_credit_note=
false;
4691 $apply_abs_price_on_credit_note =
true;
4696 if ($qty < $this->line->packaging) {
4697 $qty = $this->line->packaging;
4699 if (!empty($this->line->packaging)
4700 && is_numeric($this->line->packaging)
4701 && (
float) $this->line->packaging > 0
4702 && fmod((
float) $qty, (
float) $this->line->packaging) > 0) {
4703 $coeff = intval($qty / $this->line->packaging) + 1;
4704 $qty = $this->line->packaging * $coeff;
4705 setEventMessage($langs->trans(
'QtyRecalculatedWithPackaging'),
'mesgs');
4710 $this->line->id = $rowid;
4711 $this->line->rowid = $rowid;
4712 $this->line->label = $label;
4713 $this->line->desc = $desc;
4714 $this->line->ref_ext = $ref_ext;
4715 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4717 $this->line->vat_src_code = $vat_src_code;
4718 $this->line->tva_tx = $txtva;
4719 $this->line->localtax1_tx = $txlocaltax1;
4720 $this->line->localtax2_tx = $txlocaltax2;
4721 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4722 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4724 $this->line->remise_percent = $remise_percent;
4725 $this->line->subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht) : (float) $pu_ht);
4726 $this->line->date_start = $date_start;
4727 $this->line->date_end = $date_end;
4728 $this->line->total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ht) : (float) $total_ht);
4729 $this->line->total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_tva) : (float) $total_tva);
4730 $this->line->total_localtax1 = (float) $total_localtax1;
4731 $this->line->total_localtax2 = (float) $total_localtax2;
4732 $this->line->total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $total_ttc) : (float) $total_ttc);
4733 $this->line->info_bits = $info_bits;
4734 $this->line->special_code = $special_code;
4735 $this->line->product_type = $type;
4736 $this->line->fk_parent_line = $fk_parent_line;
4737 $this->line->skip_update_total = $skip_update_total;
4738 $this->line->situation_percent = $situation_percent;
4739 $this->line->fk_unit = $fk_unit;
4741 $this->line->fk_fournprice = $fk_fournprice;
4742 $this->line->pa_ht = $pa_ht;
4745 $this->line->multicurrency_subprice = ($apply_abs_price_on_credit_note ? -abs((
float) $pu_ht_devise) : (float) $pu_ht_devise);
4746 $this->line->multicurrency_total_ht = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ht) : (float) $multicurrency_total_ht);
4747 $this->line->multicurrency_total_tva = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_tva) : (float) $multicurrency_total_tva);
4748 $this->line->multicurrency_total_ttc = (($apply_abs_price_on_credit_note || $qty < 0) ? -abs((
float) $multicurrency_total_ttc) : (float) $multicurrency_total_ttc);
4750 if (is_array($array_options) && count($array_options) > 0) {
4752 foreach ($array_options as $key => $value) {
4753 $this->line->array_options[$key] = $array_options[$key];
4757 $result = $this->line->update($user, $notrigger);
4760 if (!empty($fk_parent_line)) {
4766 $this->db->commit();
4769 $this->error = $this->line->error;
4770 $this->db->rollback();
4774 $this->error =
"Invoice statut makes operation forbidden";
4788 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4789 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4790 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4792 $result = $this->db->query($sql);
4794 $this->error = $this->db->error();
4798 $obj = $this->db->fetch_object($result);
4800 if ($obj ===
null) {
4803 return ($situation_percent < $obj->situation_percent);
4819 global $mysoc, $user;
4822 if (($line->info_bits & 2) == 2) {
4826 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4829 if ($percent > 100) {
4833 $previous_progress = $line->getAllPrevProgress($line->fk_facture);
4834 $current_progress = $percent - $previous_progress;
4835 $line->situation_percent = $current_progress;
4836 $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);
4838 $line->situation_percent = $percent;
4839 $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);
4841 $line->total_ht = (float) $tabprice[0];
4842 $line->total_tva = (float) $tabprice[1];
4843 $line->total_ttc = (float) $tabprice[2];
4844 $line->total_localtax1 = (float) $tabprice[9];
4845 $line->total_localtax2 = (float) $tabprice[10];
4846 $line->multicurrency_total_ht = (float) $tabprice[16];
4847 $line->multicurrency_total_tva = (float) $tabprice[17];
4848 $line->multicurrency_total_ttc = (float) $tabprice[18];
4849 $line->update($user);
4852 if ($update_price) {
4868 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4870 if ($this->
status != self::STATUS_DRAFT) {
4871 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4877 $line->context = $this->context;
4880 $result = $line->fetch($rowid);
4881 if (!($result > 0)) {
4886 if ($id > 0 && $line->fk_facture != $id) {
4887 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4894 $staticline = clone $line;
4895 $line->oldline = $staticline;
4897 if ($line->delete($user) > 0) {
4901 $this->db->commit();
4904 $this->db->rollback();
4905 $this->error = $this->db->lasterror();
4909 $this->db->rollback();
4910 $this->error = $line->error;
4929 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4931 return $this->
setDiscount($user, $remise, $notrigger);
4945 if (empty($remise)) {
4949 if ($user->hasRight(
'facture',
'creer')) {
4950 $remise = (float)
price2num($remise, 2);
4956 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4957 $sql .=
" SET remise_percent = ".((float) $remise);
4958 $sql .=
" WHERE rowid = ".((int) $this->
id);
4959 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
4962 $resql = $this->db->query($sql);
4964 $this->errors[] = $this->db->error();
4968 if (!$notrigger && empty($error)) {
4978 $this->remise_percent = $remise;
4981 $this->db->commit();
4984 foreach ($this->errors as $errmsg) {
4985 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4986 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4988 $this->db->rollback();
5077 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
5078 return parent::setCategoriesCommon($categories, Categorie::TYPE_INVOICE);
5091 global
$conf, $langs;
5093 if ($this->module_source ==
'takepos') {
5094 $langs->load(
'cashdesk');
5096 $moduleName =
'takepos';
5097 $moduleSourceName =
'Takepos';
5098 $addonConstName =
'TAKEPOS_REF_ADDON';
5102 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
5107 $langs->load(
'bills');
5109 $moduleName =
'facture';
5110 $moduleSourceName =
'Invoice';
5111 $addonConstName =
'FACTURE_ADDON';
5115 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
5117 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
5119 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
5125 if (!empty($addon)) {
5126 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
5130 $file = $addon.
'.php';
5131 $classname = $addon;
5135 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
5136 foreach ($dirmodels as $reldir) {
5137 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
5140 if (is_file($dir.$file) && is_readable($dir.$file)) {
5141 $mybool = ((bool) include_once $dir.$file) || $mybool;
5147 $file = $addon.
'/'.$addon.
'.modules.php';
5148 $classname =
'mod_'.$moduleName.
'_'.$addon;
5149 $classname = preg_replace(
'/\-.*$/',
'', $classname);
5151 foreach (
$conf->file->dol_document_root as $dirroot) {
5152 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
5155 if (is_file($dir.$file) && is_readable($dir.$file)) {
5156 $mybool = (include_once $dir.$file) || $mybool;
5166 $obj =
new $classname();
5167 '@phan-var-force ModeleNumRefFactures $obj';
5169 $numref = $obj->getNextValue($soc, $this, $mode);
5176 if ($mode !=
'last' && !$numref) {
5177 $this->error = $obj->error;
5183 $langs->load(
'errors');
5184 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
5197 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
5198 $sql .=
' date_closing as dateclosing,';
5199 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
5200 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
5201 $sql .=
' WHERE c.rowid = '.((int) $id);
5203 $result = $this->db->query($sql);
5205 if ($this->db->num_rows($result)) {
5206 $obj = $this->db->fetch_object($result);
5208 $this->
id = $obj->rowid;
5209 $this->user_creation_id = $obj->fk_user_author;
5210 $this->user_validation_id = $obj->fk_user_valid;
5211 $this->user_closing_id = $obj->fk_user_closing;
5213 $this->date_creation = $this->db->jdate($obj->datec);
5214 $this->date_modification = $this->db->jdate($obj->datem);
5215 $this->date_validation = $this->db->jdate($obj->datev);
5216 $this->date_closing = $this->db->jdate($obj->dateclosing);
5218 $this->db->free($result);
5239 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
5246 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
5247 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
5248 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
5249 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5250 $sql .=
" AND f.fk_soc = s.rowid";
5252 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
5254 if (is_object($excluser)) {
5255 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
5259 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5260 $search_sale = $user->id;
5263 if ($search_sale && $search_sale !=
'-1') {
5264 if ($search_sale == -2) {
5265 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
5266 } elseif ($search_sale > 0) {
5267 $sql .=
" AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = ".((int) $search_sale).
")";
5272 $sql .=
" AND f.fk_soc = ".((int) $socid);
5274 $sql .= $this->db->order($sortfield, $sortorder);
5275 $sql .= $this->db->plimit($limit, $offset);
5277 $result = $this->db->query($sql);
5279 $numc = $this->db->num_rows($result);
5282 while ($i < $numc) {
5283 $obj = $this->db->fetch_object($result);
5285 if ($shortlist == 1) {
5286 $ga[$obj->fid] = $obj->ref;
5287 } elseif ($shortlist == 2) {
5288 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
5290 $ga[$i][
'id'] = $obj->fid;
5291 $ga[$i][
'ref'] = $obj->ref;
5292 $ga[$i][
'name'] = $obj->name;
5321 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
5322 $sql .=
" ff.rowid as rowidnext";
5324 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5325 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5326 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
5327 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
5328 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5329 $sql .=
" AND f.paye = 0";
5330 $sql .=
" AND pf.fk_paiement IS NULL";
5331 $sql .=
" AND ff.fk_statut IS NULL";
5333 $sql .=
" AND f.fk_soc = ".((int) $socid);
5336 $sql .=
" ORDER BY f.ref";
5338 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
5339 $resql = $this->db->query($sql);
5341 while ($obj = $this->db->fetch_object($resql)) {
5342 $return[$obj->rowid] = array(
5343 'id' => $obj->rowid,
5345 'status' => $obj->status,
5346 'paid' => $obj->paid,
5353 $this->error = $this->db->error();
5377 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
5378 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5379 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
5380 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
5381 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
5382 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5386 $sql .=
" AND ff.type IS NULL";
5387 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
5391 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
5392 $sql .=
'(SELECT MAX(fs.rowid)';
5393 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
5394 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
5395 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
5396 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
5398 $sql .=
" AND fs.fk_soc = ".((int) $socid);
5400 $sql .=
" GROUP BY fs.situation_cycle_ref)";
5403 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
5407 $sql .=
" AND f.fk_soc = ".((int) $socid);
5410 if (
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED') > 0) {
5411 $sql .=
" ORDER BY CASE WHEN f.rowid = ".((int)
GETPOST(
'fac_avoir')).
" THEN 0 ELSE 1 END, f.ref";
5413 $sql .= $this->db->plimit(
getDolGlobalInt(
'LIST_OF_QUALIFIED_INVOICES_LIMIT_DEFINED'));
5415 $sql .=
" ORDER BY f.ref";
5418 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
5419 $resql = $this->db->query($sql);
5421 while ($obj = $this->db->fetch_object($resql)) {
5423 if ($obj->fk_statut == self::STATUS_VALIDATED) {
5426 if ($obj->fk_statut == self::STATUS_CLOSED) {
5431 $paymentornot = ($obj->fk_paiement ? 1 : 0);
5432 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
5438 $this->error = $this->db->error();
5454 global
$conf, $langs;
5458 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
5459 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5460 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5461 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
5462 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5465 $sql .= $clause.
" f.paye=0";
5466 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
5467 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5469 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
5472 $resql = $this->db->query($sql);
5474 $langs->load(
"bills");
5477 $response->warning_delay =
$conf->facture->client->warning_delay / 60 / 60 / 24;
5478 $response->label = $langs->trans(
"CustomerBillsUnpaid");
5479 $response->labelShort = $langs->trans(
"Unpaid");
5480 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
5483 $generic_facture =
new Facture($this->db);
5485 while ($obj = $this->db->fetch_object($resql)) {
5486 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
5487 $generic_facture->statut = $obj->status;
5488 $generic_facture->status = $obj->status;
5490 $response->nbtodo++;
5491 $response->total += $obj->total_ht;
5493 if ($generic_facture->hasDelay()) {
5494 $response->nbtodolate++;
5495 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
5499 $this->db->free($resql);
5503 $this->error = $this->db->error();
5542 global
$conf, $langs, $user;
5546 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5551 $sql =
"SELECT rowid";
5552 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5553 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5554 $sql .= $this->db->plimit(100);
5556 $resql = $this->db->query($sql);
5558 $num_prods = $this->db->num_rows($resql);
5560 while ($i < $num_prods) {
5562 $row = $this->db->fetch_row($resql);
5563 $prodids[$i] = $row[0];
5567 if (empty($num_prods)) {
5569 $prodids[$num_prods] = 1;
5574 $this->entity =
$conf->entity;
5575 $this->
ref =
'SPECIMEN';
5576 $this->specimen = 1;
5578 $this->date = $nownotime;
5579 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5580 $this->cond_reglement_id = 1;
5581 $this->cond_reglement_code =
'RECEP';
5583 $this->mode_reglement_id = 0;
5584 $this->mode_reglement_code =
'';
5586 $this->note_public =
'This is a comment (public)';
5587 $this->note_private =
'This is a comment (private)';
5588 $this->note =
'This is a comment (private)';
5590 $this->fk_user_author = $user->id;
5592 $this->multicurrency_tx = 1;
5593 $this->multicurrency_code =
$conf->currency;
5595 $this->fk_incoterms = 0;
5596 $this->location_incoterms =
'';
5598 if (empty($option) || $option !=
'nolines') {
5602 while ($xnbp < $nbp) {
5604 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5606 $line->subprice = 100;
5607 $line->tva_tx = 19.6;
5608 $line->localtax1_tx = 0;
5609 $line->localtax2_tx = 0;
5610 $line->remise_percent = 0;
5612 $prodid = mt_rand(1, $num_prods);
5613 if (isset($prodids[$prodid])) {
5614 $line->fk_product = $prodids[$prodid];
5617 $line->total_ht = -100;
5618 $line->total_ttc = -119.6;
5619 $line->total_tva = -19.6;
5620 $line->multicurrency_total_ht = -200;
5621 $line->multicurrency_total_ttc = -239.2;
5622 $line->multicurrency_total_tva = -39.2;
5623 } elseif ($xnbp == 2) {
5624 $line->subprice = -100;
5625 $line->total_ht = -100;
5626 $line->total_ttc = -119.6;
5627 $line->total_tva = -19.6;
5628 $line->remise_percent = 0;
5629 $line->multicurrency_total_ht = -200;
5630 $line->multicurrency_total_ttc = -239.2;
5631 $line->multicurrency_total_tva = -39.2;
5632 } elseif ($xnbp == 3) {
5633 $prodid = mt_rand(1, $num_prods);
5634 if (isset($prodids[$prodid])) {
5635 $line->fk_product = $prodids[$prodid];
5637 $line->total_ht = 50;
5638 $line->total_ttc = 59.8;
5639 $line->total_tva = 9.8;
5640 $line->multicurrency_total_ht = 100;
5641 $line->multicurrency_total_ttc = 119.6;
5642 $line->multicurrency_total_tva = 19.6;
5643 $line->remise_percent = 50;
5645 $prodid = mt_rand(1, $num_prods);
5646 if (isset($prodids[$prodid])) {
5647 $line->fk_product = $prodids[$prodid];
5649 $line->total_ht = 100;
5650 $line->total_ttc = 119.6;
5651 $line->total_tva = 19.6;
5652 $line->multicurrency_total_ht = 200;
5653 $line->multicurrency_total_ttc = 239.2;
5654 $line->multicurrency_total_tva = 39.2;
5655 $line->remise_percent = 0;
5658 $this->lines[$xnbp] = $line;
5661 $this->total_ht += $line->total_ht;
5662 $this->total_tva += $line->total_tva;
5663 $this->total_ttc += $line->total_ttc;
5665 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5666 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5667 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5671 $this->revenuestamp = 0;
5675 $line->desc = $langs->trans(
"Description").
" (offered line)";
5677 $line->subprice = 100;
5678 $line->tva_tx = 19.6;
5679 $line->localtax1_tx = 0;
5680 $line->localtax2_tx = 0;
5681 $line->remise_percent = 100;
5682 $line->total_ht = 0;
5683 $line->total_ttc = 0;
5684 $line->total_tva = 0;
5685 $line->multicurrency_total_ht = 0;
5686 $line->multicurrency_total_ttc = 0;
5687 $line->multicurrency_total_tva = 0;
5688 $prodid = mt_rand(1, $num_prods);
5689 if (isset($prodids[$prodid])) {
5690 $line->fk_product = $prodids[$prodid];
5693 $this->lines[$xnbp] = $line;
5707 global
$conf, $user;
5709 $this->nb = array();
5713 $sql =
"SELECT count(f.rowid) as nb";
5714 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5715 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5716 if (empty($user->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
5717 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5718 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5721 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
5723 $resql = $this->db->query($sql);
5725 while ($obj = $this->db->fetch_object($resql)) {
5726 $this->nb[
"invoices"] = $obj->nb;
5728 $this->db->free($resql);
5732 $this->error = $this->db->error();
5758 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5760 $outputlangs->loadLangs(array(
"bills",
"products"));
5764 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5766 if (!empty($this->model_pdf)) {
5767 $modele = $this->model_pdf;
5775 $modelpath =
"core/modules/facture/doc/";
5777 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5787 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5788 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5789 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5791 $resql = $this->db->query($sql);
5793 if ($this->db->num_rows($resql) > 0) {
5795 $obj = $this->db->fetch_object($resql);
5797 $ref = $obj->maxsituationref;
5803 $this->db->free($resql);
5806 $this->error = $this->db->lasterror();
5807 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5821 return ($this->situation_counter == 1);
5835 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5836 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5837 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5838 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity :
$conf->entity);
5839 $resql = $this->db->query($sql);
5841 if ($resql && $this->db->num_rows($resql) > 0) {
5842 while ($row = $this->db->fetch_object($resql)) {
5844 $situation =
new Facture($this->db);
5845 $situation->fetch($id);
5846 $res[] = $situation;
5849 $this->error = $this->db->error();
5850 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5870 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5873 $resql = $this->db->query($sql);
5875 $this->errors[] = $this->db->error();
5879 if (!$notrigger && empty($error)) {
5889 $this->db->commit();
5892 foreach ($this->errors as $errmsg) {
5893 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5894 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5896 $this->db->rollback();
5912 if (!empty($this->situation_cycle_ref)) {
5914 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5915 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5916 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity :
$conf->entity);
5917 $resql = $this->db->query($sql);
5919 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5920 $last = $res[
'max(situation_counter)'];
5921 return ($last == $this->situation_counter);
5923 $this->error = $this->db->lasterror();
5924 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5982 $hasDelay = $this->date_lim_reglement < ($now -
$conf->facture->client->warning_delay);
5983 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5985 $totalpaid = (float) $totalpaid;
5987 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5988 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now -
$conf->facture->client->warning_delay)) {
5990 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now -
$conf->facture->client->warning_delay)) {
6008 return $this->situation_cycle_ref;
6021 $displayWarranty =
false;
6022 if (!empty($this->retained_warranty)) {
6023 $displayWarranty =
true;
6027 $displayWarranty =
false;
6028 if (!empty($this->situation_final)) {
6029 $displayWarranty =
true;
6032 $displayWarranty =
true;
6034 foreach ($this->lines as $i => $line) {
6035 if ($line->product_type < 2 && $line->situation_percent < 100) {
6036 $displayWarranty =
false;
6044 return $displayWarranty;
6053 if (empty($this->retained_warranty)) {
6057 $retainedWarrantyAmount = 0;
6061 $displayWarranty =
true;
6063 if (!empty($this->lines)) {
6064 foreach ($this->lines as $i => $line) {
6065 if ($line->product_type < 2 && $line->situation_percent < 100) {
6066 $displayWarranty =
false;
6072 if ($displayWarranty && !empty($this->situation_final)) {
6074 $TPreviousIncoice = $this->tab_previous_situation_invoice;
6077 foreach ($TPreviousIncoice as &$fac) {
6078 $total2BillWT += $fac->total_ttc;
6080 $total2BillWT += $this->total_ttc;
6082 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
6088 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
6091 if ($rounding < 0) {
6095 if ($rounding > 0) {
6096 return round($retainedWarrantyAmount, $rounding);
6099 return $retainedWarrantyAmount;
6110 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
6112 if ($this->
status >= 0) {
6113 $fieldname =
'retained_warranty';
6114 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6115 $sql .=
" SET ".$fieldname.
" = ".((float) $value);
6116 $sql .=
' WHERE rowid='.((int) $this->
id);
6118 if ($this->db->query($sql)) {
6119 $this->retained_warranty = (float) $value;
6122 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
6123 $this->error = $this->db->error();
6127 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
6128 $this->error =
'Status of the object is incompatible '.$this->status;
6143 if (!$timestamp && $dateYmd) {
6144 $timestamp = $this->db->jdate($dateYmd);
6148 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
6149 if ($this->
status >= 0) {
6150 $fieldname =
'retained_warranty_date_limit';
6151 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
6152 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
6153 $sql .=
' WHERE rowid = '.((int) $this->
id);
6155 if ($this->db->query($sql)) {
6156 $this->retained_warranty_date_limit = $timestamp;
6159 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
6160 $this->error = $this->db->error();
6164 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
6165 $this->error =
'Status of the object is incompatible '.$this->status;
6184 global
$conf, $langs, $user;
6190 $errorsMsg = array();
6192 $langs->load(
"bills");
6194 if (!isModEnabled(
'invoice')) {
6195 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Invoice"));
6198 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
6199 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
6209 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
6210 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
6211 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
6212 $formmail =
new FormMail($this->db);
6217 $tmpinvoice =
new Facture($this->db);
6222 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
6223 if (!empty($paymentmode) && $paymentmode !=
'all') {
6224 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
6226 $sql .=
" WHERE f.paye = 0";
6227 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
6228 if ($datetouse ==
'invoicedate') {
6229 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
6231 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
6233 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
6234 if (!empty($paymentmode) && $paymentmode !=
'all') {
6235 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
6238 if ($datetouse ==
'invoicedate') {
6239 $sql .= $this->db->order(
"datef",
"ASC");
6241 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
6245 $resql = $this->db->query($sql);
6248 if ($datetouse ==
'invoicedate') {
6249 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
6251 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
6253 if (!empty($paymentmode) && $paymentmode !=
'all') {
6254 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
6256 $this->output .=
'<br>';
6259 while ($obj = $this->db->fetch_object($resql)) {
6264 $res = $tmpinvoice->fetch($obj->id);
6266 $tmpinvoice->fetch_thirdparty();
6269 if ($tmpinvoice->thirdparty->default_lang) {
6270 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
6271 $outputlangs->loadLangs(array(
"main",
"bills"));
6273 $outputlangs = $langs;
6277 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
6278 if (is_numeric($arraymessage) && $arraymessage <= 0) {
6279 $langs->load(
"errors");
6280 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
6288 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null, $tmpinvoice);
6293 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
6296 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
6302 if ($forcerecipient) {
6303 $to = array($forcerecipient);
6305 $res = $tmpinvoice->fetch_thirdparty();
6306 $recipient = $tmpinvoice->thirdparty;
6308 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
6309 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
6310 foreach ($tmparraycontact as $data_email) {
6311 if (!empty($data_email[
'email'])) {
6312 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
6316 if (empty($to) && !empty($recipient->email)) {
6317 $to[] = $recipient->email;
6320 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
6324 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
6331 if (!empty($arraymessage->email_from)) {
6332 $from = (string) $arraymessage->email_from;
6335 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
6339 if (!$loopError && !empty($to)) {
6340 $to = implode(
',', $to);
6341 if (!empty($arraymessage->email_to)) {
6342 $to = $to.
','.$arraymessage->email_to;
6348 $trackid =
'inv'.$tmpinvoice->id;
6349 $sendcontext =
'standard';
6352 if (!empty($arraymessage->email_tocc)) {
6353 $email_tocc = (string) $arraymessage->email_tocc;
6357 if (!empty($arraymessage->email_tobcc)) {
6358 $email_tobcc = (string) $arraymessage->email_tobcc;
6365 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
6366 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
6367 $joinFileName[] = basename($tmpinvoice->last_main_doc);
6368 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
6372 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
6374 $resultsendmail = $cMailFile->sendfile();
6379 if ($resultsendmail) {
6383 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6388 $actioncomm->type_code =
'AC_OTH_AUTO';
6389 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6390 $actioncomm->contact_id = 0;
6392 $actioncomm->code =
'AC_EMAIL';
6393 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
6394 $actioncomm->note_private = $sendContent;
6395 $actioncomm->fk_project = $tmpinvoice->fk_project;
6396 $actioncomm->datep =
dol_now();
6397 $actioncomm->datef = $actioncomm->datep;
6398 $actioncomm->percentage = -1;
6399 $actioncomm->authorid = $user->id;
6400 $actioncomm->userownerid = $user->id;
6402 $actioncomm->email_msgid = $cMailFile->msgid;
6403 $actioncomm->email_subject = $sendTopic;
6404 $actioncomm->email_from = $from;
6405 $actioncomm->email_sender =
'';
6406 $actioncomm->email_to = $to;
6410 $actioncomm->errors_to = $errors_to;
6412 $actioncomm->elementtype =
'invoice';
6413 $actioncomm->elementid = $tmpinvoice->id;
6417 $actioncomm->create($user);
6419 $errormesg = $cMailFile->error.
' : '.$to;
6423 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
6428 $actioncomm->type_code =
'AC_OTH_AUTO';
6429 $actioncomm->socid = $tmpinvoice->thirdparty->id;
6430 $actioncomm->contact_id = 0;
6432 $actioncomm->code =
'AC_EMAIL';
6433 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
6434 $actioncomm->note_private = $errormesg;
6435 $actioncomm->fk_project = $tmpinvoice->fk_project;
6436 $actioncomm->datep =
dol_now();
6437 $actioncomm->datef = $actioncomm->datep;
6438 $actioncomm->percentage = -1;
6439 $actioncomm->authorid = $user->id;
6440 $actioncomm->userownerid = $user->id;
6442 $actioncomm->email_msgid = $cMailFile->msgid;
6443 $actioncomm->email_from = $from;
6444 $actioncomm->email_sender =
'';
6445 $actioncomm->email_to = $to;
6449 $actioncomm->errors_to = $errors_to;
6451 $actioncomm->elementtype =
'invoice';
6452 $actioncomm->elementid = $tmpinvoice->id;
6456 $actioncomm->create($user);
6459 $this->db->commit();
6463 $errorsMsg[] = $errormesg;
6466 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
6470 $error += $loopError;
6477 $this->output .=
'Nb of emails sent : '.$nbMailSend;
6479 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
6483 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
6485 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
6500 $sql =
"SELECT datef";
6501 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
6502 $sql .=
" WHERE type = " . (int) $this->
type ;
6503 $sql .=
" AND date_valid IS NOT NULL";
6504 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
6505 $sql .=
" ORDER BY datef DESC LIMIT 1";
6507 $result = $this->db->query($sql);
6510 if ($this->db->num_rows($result)) {
6511 $obj = $this->db->fetch_object($result);
6512 $last_date = $this->db->jdate($obj->datef);
6513 $invoice_date = $this->date;
6515 $is_last_of_same_type = $invoice_date >= $last_date;
6516 if ($allow_validated_drafts) {
6520 return array($is_last_of_same_type, $last_date);
6543 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6545 $picto = $this->picto;
6546 if ($this->
type == self::TYPE_REPLACEMENT) {
6549 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6552 if ($this->
type == self::TYPE_DEPOSIT) {
6556 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6557 $return .=
'<div class="info-box info-box-sm">';
6558 $return .=
'<span class="info-box-icon bg-infobox-action">';
6560 $return .=
'</span>';
6561 $return .=
'<div class="info-box-content">';
6562 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6563 if ($selected >= 0) {
6564 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6566 if (!empty($arraydata[
'thirdparty'])) {
6567 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6569 if (property_exists($this,
'date')) {
6570 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->date,
'day').
'</span>';
6572 if (property_exists($this,
'total_ht')) {
6573 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6574 $return .=
' '.$langs->trans(
"HT");
6575 $return .=
'</span>';
6577 if (method_exists($this,
'getLibStatut')) {
6578 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6579 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6581 $return .=
'</div>';
6582 $return .=
'</div>';
6583 $return .=
'</div>';
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoice classes.
getSumCreditNotesUsed($multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice.
getSumDepositsUsed($multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage invoices.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getIdShippingContact()
Retourne id des contacts clients de livraison.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
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.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this->lines.
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
getIdBillingContact()
Retourne id des contacts clients de facturation.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=self::TYPE_STANDARD, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=array(), $situation_percent=100, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a detail line.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target='')
Return clickable link of object (with eventually picto)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
fetch($rowid, $ref='', $ref_ext='', $notused=0, $fetch_situation=false)
Get object from database.
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.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Replace a product id with another one.
setRetainedWarrantyDateLimit($timestamp, $dateYmd='')
Change the retained_warranty_date_limit.
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $datetouse='duedate', $forcerecipient='')
Send reminders by emails for invoices validated that are due.
info($id)
Load miscellaneous information for tab "Info".
const TYPE_PROFORMA
Proforma invoice (should not be used.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setRetainedWarranty($value)
Change the retained warranty.
get_prev_sits()
Returns an array containing the previous situations as Facture objects.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
newCycle()
Gets the smallest reference available for a new cycle.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
isSituationInvoice()
Check if an invoice is a situation invoice.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getTooltipContentArray($params)
getTooltipContentArray
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
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.
getRetainedWarrantyAmount($rounding=-1)
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)
Set absolute discount.
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.
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_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
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($object, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.