43 include_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
44 require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobjectline.class.php';
45 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
46 require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
47 require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
48 require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
51 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
54 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
65 public $element =
'facture';
70 public $table_element =
'facture';
75 public $table_element_line =
'facturedet';
80 public $fk_element =
'fk_facture';
85 public $picto =
'bill';
91 public $ismultientitymanaged = 1;
97 public $restrictiononfksoc = 1;
120 public $fk_user_author;
125 public $fk_user_valid;
130 public $fk_user_modif;
141 public $date_livraison;
146 public $delivery_date;
158 public $ref_customer;
167 public $type = self::TYPE_STANDARD;
171 public $remise_absolue;
172 public $remise_percent;
175 public $total_localtax1;
176 public $total_localtax2;
178 public $revenuestamp;
206 public $linked_objects = array();
208 public $date_lim_reglement;
209 public $cond_reglement_code;
210 public $mode_reglement_code;
220 public $lines = array();
223 public $extraparams = array();
227 public $date_pointoftax;
233 public $fk_multicurrency;
235 public $multicurrency_code;
236 public $multicurrency_tx;
237 public $multicurrency_total_ht;
238 public $multicurrency_total_tva;
239 public $multicurrency_total_ttc;
244 public $situation_cycle_ref;
249 public $situation_counter;
254 public $situation_final;
259 public $tab_previous_situation_invoice = array();
264 public $tab_next_situation_invoice = array();
271 public $retained_warranty;
276 public $retained_warranty_date_limit;
281 public $retained_warranty_fk_cond_reglement;
312 public $fields = array(
313 'rowid' =>array(
'type'=>
'integer',
'label'=>
'TechnicalID',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>1),
314 'ref' =>array(
'type'=>
'varchar(30)',
'label'=>
'Ref',
'enabled'=>1,
'visible'=>1,
'notnull'=>1,
'showoncombobox'=>1,
'position'=>5),
315 'entity' =>array(
'type'=>
'integer',
'label'=>
'Entity',
'default'=>1,
'enabled'=>1,
'visible'=>-2,
'notnull'=>1,
'position'=>20,
'index'=>1),
316 'ref_client' =>array(
'type'=>
'varchar(255)',
'label'=>
'RefCustomer',
'enabled'=>1,
'visible'=>-1,
'position'=>10),
317 'ref_ext' =>array(
'type'=>
'varchar(255)',
'label'=>
'Ref ext',
'enabled'=>1,
'visible'=>0,
'position'=>12),
319 'type' =>array(
'type'=>
'smallint(6)',
'label'=>
'Type',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>15),
321 'fk_soc' =>array(
'type'=>
'integer:Societe:societe/class/societe.class.php',
'label'=>
'ThirdParty',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>50),
322 'datef' =>array(
'type'=>
'date',
'label'=>
'DateInvoice',
'enabled'=>1,
'visible'=>1,
'position'=>20),
323 'date_valid' =>array(
'type'=>
'date',
'label'=>
'DateValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>22),
324 'date_lim_reglement' =>array(
'type'=>
'date',
'label'=>
'DateDue',
'enabled'=>1,
'visible'=>1,
'position'=>25),
325 'date_closing' =>array(
'type'=>
'datetime',
'label'=>
'Date closing',
'enabled'=>1,
'visible'=>-1,
'position'=>30),
326 'paye' =>array(
'type'=>
'smallint(6)',
'label'=>
'InvoicePaidCompletely',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>80),
328 'remise_percent' =>array(
'type'=>
'double',
'label'=>
'RelativeDiscount',
'enabled'=>1,
'visible'=>-1,
'position'=>90),
329 'remise_absolue' =>array(
'type'=>
'double',
'label'=>
'CustomerRelativeDiscount',
'enabled'=>1,
'visible'=>-1,
'position'=>91),
331 'close_code' =>array(
'type'=>
'varchar(16)',
'label'=>
'EarlyClosingReason',
'enabled'=>1,
'visible'=>-1,
'position'=>92),
332 'close_note' =>array(
'type'=>
'varchar(128)',
'label'=>
'EarlyClosingComment',
'enabled'=>1,
'visible'=>-1,
'position'=>93),
333 'total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountHT',
'enabled'=>1,
'visible'=>1,
'position'=>95,
'isameasure'=>1),
334 'total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountVAT',
'enabled'=>1,
'visible'=>-1,
'position'=>100,
'isameasure'=>1),
335 'localtax1' =>array(
'type'=>
'double(24,8)',
'label'=>
'LT1',
'enabled'=>1,
'visible'=>-1,
'position'=>110,
'isameasure'=>1),
336 'localtax2' =>array(
'type'=>
'double(24,8)',
'label'=>
'LT2',
'enabled'=>1,
'visible'=>-1,
'position'=>120,
'isameasure'=>1),
337 'revenuestamp' =>array(
'type'=>
'double(24,8)',
'label'=>
'RevenueStamp',
'enabled'=>1,
'visible'=>-1,
'position'=>115,
'isameasure'=>1),
338 'total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountTTC',
'enabled'=>1,
'visible'=>1,
'position'=>130,
'isameasure'=>1),
339 'fk_user_author' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'enabled'=>1,
'visible'=>-1,
'position'=>165),
340 'fk_user_modif' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'enabled'=>1,
'visible'=>-2,
'notnull'=>-1,
'position'=>166),
341 'fk_user_valid' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>167),
342 'fk_user_closing' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserClosing',
'enabled'=>1,
'visible'=>-1,
'position'=>168),
343 'fk_facture_source' =>array(
'type'=>
'integer',
'label'=>
'SourceInvoice',
'enabled'=>1,
'visible'=>-1,
'position'=>170),
344 'fk_projet' =>array(
'type'=>
'integer:Project:projet/class/project.class.php:1:fk_statut=1',
'label'=>
'Project',
'enabled'=>1,
'visible'=>-1,
'position'=>175),
345 'fk_account' =>array(
'type'=>
'integer',
'label'=>
'Fk account',
'enabled'=>1,
'visible'=>-1,
'position'=>180),
346 'fk_currency' =>array(
'type'=>
'varchar(3)',
'label'=>
'CurrencyCode',
'enabled'=>1,
'visible'=>-1,
'position'=>185),
347 'fk_cond_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentTerm',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>190),
348 'fk_mode_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentMode',
'enabled'=>1,
'visible'=>-1,
'position'=>195),
349 'note_private' =>array(
'type'=>
'text',
'label'=>
'NotePrivate',
'enabled'=>1,
'visible'=>0,
'position'=>205),
350 'note_public' =>array(
'type'=>
'text',
'label'=>
'NotePublic',
'enabled'=>1,
'visible'=>0,
'position'=>210),
351 'model_pdf' =>array(
'type'=>
'varchar(255)',
'label'=>
'Model pdf',
'enabled'=>1,
'visible'=>0,
'position'=>215),
352 'extraparams' =>array(
'type'=>
'varchar(255)',
'label'=>
'Extraparams',
'enabled'=>1,
'visible'=>-1,
'position'=>225),
353 'situation_cycle_ref' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation cycle ref',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>230),
354 'situation_counter' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation counter',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>235),
355 'situation_final' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation final',
'enabled'=>
'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1',
'visible'=>-1,
'position'=>240),
356 'retained_warranty' =>array(
'type'=>
'double',
'label'=>
'Retained warranty',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>245),
357 'retained_warranty_date_limit' =>array(
'type'=>
'date',
'label'=>
'Retained warranty date limit',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>250),
358 'retained_warranty_fk_cond_reglement' =>array(
'type'=>
'integer',
'label'=>
'Retained warranty fk cond reglement',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>255),
359 'fk_incoterms' =>array(
'type'=>
'integer',
'label'=>
'IncotermCode',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>260),
360 'location_incoterms' =>array(
'type'=>
'varchar(255)',
'label'=>
'IncotermLabel',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>265),
361 'date_pointoftax' =>array(
'type'=>
'date',
'label'=>
'DatePointOfTax',
'enabled'=>
'$conf->global->INVOICE_POINTOFTAX_DATE',
'visible'=>-1,
'position'=>270),
362 'fk_multicurrency' =>array(
'type'=>
'integer',
'label'=>
'MulticurrencyID',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>275),
363 'multicurrency_code' =>array(
'type'=>
'varchar(255)',
'label'=>
'Currency',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>280),
364 'multicurrency_tx' =>array(
'type'=>
'double(24,8)',
'label'=>
'CurrencyRate',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>285,
'isameasure'=>1),
365 'multicurrency_total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountHT',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>290,
'isameasure'=>1),
366 'multicurrency_total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountVAT',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>291,
'isameasure'=>1),
367 'multicurrency_total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountTTC',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>292,
'isameasure'=>1),
368 'fk_fac_rec_source' =>array(
'type'=>
'integer',
'label'=>
'RecurringInvoiceSource',
'enabled'=>1,
'visible'=>-1,
'position'=>305),
369 'last_main_doc' =>array(
'type'=>
'varchar(255)',
'label'=>
'LastMainDoc',
'enabled'=>1,
'visible'=>-1,
'position'=>310),
370 'module_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSModule',
'enabled'=>1,
'visible'=>-1,
'position'=>315),
371 'pos_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSTerminal',
'enabled'=>1,
'visible'=>-1,
'position'=>320),
372 'datec' =>array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'enabled'=>1,
'visible'=>-1,
'position'=>500),
373 'tms' =>array(
'type'=>
'timestamp',
'label'=>
'DateModificationShort',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>500),
374 'import_key' =>array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'enabled'=>1,
'visible'=>-2,
'position'=>900),
375 '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')),
437 const CLOSECODE_DISCOUNTVAT =
'discount_vat';
438 const CLOSECODE_BADDEBT =
'badcustomer';
439 const CLOSECODE_BANKCHARGE =
'bankcharge';
440 const CLOSECODE_OTHER =
'other';
442 const CLOSECODE_ABANDONED =
'abandon';
443 const CLOSECODE_REPLACED =
'replaced';
466 public function create(
User $user, $notrigger = 0, $forceduedate = 0)
468 global $langs, $conf, $mysoc, $hookmanager;
472 if (empty($this->
type)) {
473 $this->
type = self::TYPE_STANDARD;
475 $this->ref_client = trim($this->ref_client);
476 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
477 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
478 $this->note_public = trim($this->note_public);
479 if (!$this->cond_reglement_id) {
480 $this->cond_reglement_id = 0;
482 if (!$this->mode_reglement_id) {
483 $this->mode_reglement_id = 0;
485 $this->brouillon = 1;
486 $this->status = self::STATUS_DRAFT;
487 $this->statut = self::STATUS_DRAFT;
489 if (!empty($this->multicurrency_code)) {
491 if (empty($this->multicurrency_tx)) {
499 $this->fk_multicurrency = 0;
501 if (empty($this->fk_multicurrency)) {
502 $this->multicurrency_code = $conf->currency;
503 $this->fk_multicurrency = 0;
504 $this->multicurrency_tx = 1;
507 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
510 if (empty($this->date)) {
511 $this->error =
"Try to create an invoice with an empty parameter (date)";
512 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
516 $result = $soc->fetch($this->socid);
518 $this->error =
"Failed to fetch company: ".$soc->error;
519 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
527 $originaldatewhen = null;
528 $nextdatewhen = null;
529 $previousdaynextdatewhen = null;
532 if ($this->fac_rec > 0) {
533 $this->fk_fac_rec_source = $this->fac_rec;
535 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
537 $result = $_facrec->fetch($this->fac_rec);
538 $result = $_facrec->fetchObjectLinked(null,
'', null,
'',
'OR', 1,
'sourcetype', 0);
541 $originaldatewhen = $_facrec->date_when;
542 $nextdatewhen = null; $previousdaynextdatewhen = null;
543 if ($originaldatewhen) {
544 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
548 if (!empty($_facrec->frequency)) {
549 $this->socid = $_facrec->socid;
551 $this->entity = $_facrec->entity;
554 $this->fk_project =
GETPOST(
'projectid',
'int') > 0 ? ((int)
GETPOST(
'projectid',
'int')) : $_facrec->fk_project;
555 $this->note_public =
GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
556 $this->note_private =
GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
557 $this->model_pdf =
GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
558 $this->cond_reglement_id =
GETPOST(
'cond_reglement_id',
'int') > 0 ? ((int)
GETPOST(
'cond_reglement_id',
'int')) : $_facrec->cond_reglement_id;
559 $this->mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int') > 0 ? ((int)
GETPOST(
'mode_reglement_id',
'int')) : $_facrec->mode_reglement_id;
560 $this->fk_account =
GETPOST(
'fk_account') > 0 ? ((int)
GETPOST(
'fk_account')) : $_facrec->fk_account;
563 $this->total_ht = $_facrec->total_ht;
564 $this->total_ttc = $_facrec->total_ttc;
567 $this->remise_absolue = $_facrec->remise_absolue;
568 $this->remise_percent = $_facrec->remise_percent;
569 $this->fk_incoterms = $_facrec->fk_incoterms;
570 $this->location_incoterms = $_facrec->location_incoterms;
574 $this->
type = self::TYPE_STANDARD;
576 $this->ref_client = trim($this->ref_client);
577 $this->note_public = trim($this->note_public);
578 $this->note_private = trim($this->note_private);
579 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
581 $this->array_options = $_facrec->array_options;
583 if (!$this->mode_reglement_id) {
584 $this->mode_reglement_id = 0;
586 $this->brouillon = 1;
587 $this->status = self::STATUS_DRAFT;
588 $this->statut = self::STATUS_DRAFT;
590 $this->linked_objects = $_facrec->linkedObjectsIds;
597 if ($_facrec->frequency > 0) {
598 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
599 if (empty($_facrec->date_when)) {
600 $_facrec->date_when = $now;
602 $next_date = $_facrec->getNextDate();
603 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'', null,
'date',
'', $user,
'');
605 $result = $_facrec->setNextDate($next_date, 1);
609 $outputlangs = $langs;
612 if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) {
613 $newlang = $this->thirdparty->default_lang;
615 if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) {
616 $newlang = $this->default_lang;
618 if (!empty($newlang)) {
620 $outputlangs->setDefaultLang($newlang);
626 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
629 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
632 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
635 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
636 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
637 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
638 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
639 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
650 if (empty($forceduedate)) {
656 $this->date_lim_reglement = $duedate;
658 $this->date_lim_reglement = $forceduedate;
662 $socid = $this->socid;
664 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
671 $sql .=
", remise_absolue";
672 $sql .=
", remise_percent";
674 $sql .=
", date_pointoftax";
675 $sql .=
", note_private";
676 $sql .=
", note_public";
677 $sql .=
", ref_client, ref_int";
678 $sql .=
", fk_account";
679 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
680 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
681 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
682 $sql .=
", fk_incoterms, location_incoterms";
683 $sql .=
", fk_multicurrency";
684 $sql .=
", multicurrency_code";
685 $sql .=
", multicurrency_tx";
686 $sql .=
", retained_warranty";
687 $sql .=
", retained_warranty_date_limit";
688 $sql .=
", retained_warranty_fk_cond_reglement";
692 $sql .=
", ".setEntity($this);
693 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
694 $sql .=
", '".$this->db->escape($this->
type).
"'";
695 $sql .=
", ".((int) $socid);
696 $sql .=
", '".$this->db->idate($now).
"'";
697 $sql .=
", ".($this->remise_absolue > 0 ? $this->remise_absolue :
'NULL');
698 $sql .=
", ".($this->remise_percent > 0 ? $this->remise_percent :
'NULL');
699 $sql .=
", '".$this->db->idate($this->date).
"'";
700 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
701 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
702 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
703 $sql .=
", ".($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null");
704 $sql .=
", ".($this->ref_int ?
"'".$this->db->escape($this->ref_int).
"'" :
"null");
705 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
706 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
707 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape($this->pos_source).
"'" :
"null");
708 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape($this->fk_fac_rec_source).
"'" :
"null");
709 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape($this->fk_facture_source).
"'" :
"null");
710 $sql .=
", ".($user->id > 0 ? (int) $user->id :
"null");
711 $sql .=
", ".($this->fk_project ? $this->fk_project :
"null");
712 $sql .=
", ".((int) $this->cond_reglement_id);
713 $sql .=
", ".((int) $this->mode_reglement_id);
714 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
715 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
716 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape($this->situation_cycle_ref).
"'" :
"null");
717 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape($this->situation_counter).
"'" :
"null");
718 $sql .=
", ".($this->situation_final ? $this->situation_final : 0);
719 $sql .=
", ".(int) $this->fk_incoterms;
720 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
721 $sql .=
", ".(int) $this->fk_multicurrency;
722 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
723 $sql .=
", ".(double) $this->multicurrency_tx;
724 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty));
725 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
726 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
731 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facture');
734 $this->
ref =
'(PROV'.$this->id.
')';
735 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->
db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
742 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
743 $this->linked_objects = $this->linkedObjectsIds;
747 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
748 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
749 if (is_array($tmp_origin_id)) {
750 foreach ($tmp_origin_id as $origin_id) {
753 $this->error = $this->
db->lasterror();
759 $origin_id = $tmp_origin_id;
762 $this->error = $this->
db->lasterror();
770 if (!$error && $this->
id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) {
771 $originforcontact = $this->origin;
772 $originidforcontact = $this->origin_id;
773 if ($originforcontact ==
'shipping') {
774 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
776 $exp->fetch($this->origin_id);
777 $exp->fetchObjectLinked(null,
'', null,
'',
'OR', 1,
'sourcetype', 0);
778 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
779 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
780 $originforcontact =
'commande';
781 if (is_object($value)) {
782 $originidforcontact = $value->id;
784 $originidforcontact = $value;
791 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
792 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->
db->escape($originforcontact).
"'";
794 $resqlcontact = $this->
db->query($sqlcontact);
796 while ($objcontact = $this->
db->fetch_object($resqlcontact)) {
798 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
808 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
811 dol_syslog(
"There is ".count($this->lines).
" lines that are invoice lines objects");
812 foreach ($this->lines as $i => $val) {
813 $newinvoiceline = $this->lines[$i];
815 $newinvoiceline->context = $this->context;
817 $newinvoiceline->fk_facture = $this->id;
819 $newinvoiceline->origin = $this->lines[$i]->element;
820 $newinvoiceline->origin_id = $this->lines[$i]->id;
823 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
824 $newinvoiceline->date_start = $originaldatewhen;
826 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
827 $newinvoiceline->date_end = $previousdaynextdatewhen;
832 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
837 $vatrate = $newinvoiceline->tva_tx;
838 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', $vatrate)) $vatrate.=
' ('.$newinvoiceline->vat_src_code.
')';
840 $newinvoiceline->fk_parent_line = $fk_parent_line;
844 $discount->fetch($newinvoiceline->fk_remise_except);
846 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
847 $newinvoiceline->fk_remise_except = $discountId;
851 $newinvoiceline->desc,
852 $newinvoiceline->subprice,
853 $newinvoiceline->qty,
855 $newinvoiceline->localtax1_tx,
856 $newinvoiceline->localtax2_tx,
857 $newinvoiceline->fk_product,
858 $newinvoiceline->remise_percent,
859 $newinvoiceline->date_start,
860 $newinvoiceline->date_end,
861 $newinvoiceline->fk_code_ventilation,
862 $newinvoiceline->info_bits,
863 $newinvoiceline->fk_remise_except,
866 $newinvoiceline->product_type,
867 $newinvoiceline->rang,
868 $newinvoiceline->special_code,
869 $newinvoiceline->element,
872 $newinvoiceline->fk_fournprice,
873 $newinvoiceline->pa_ht,
874 $newinvoiceline->label,
875 $newinvoiceline->array_options,
876 $newinvoiceline->situation_percent,
877 $newinvoiceline->fk_prev_id,
878 $newinvoiceline->fk_unit,
879 $newinvoiceline->multicurrency_subprice,
880 $newinvoiceline->ref_ext,
885 if ($result > 0 && $newinvoiceline->product_type == 9) {
886 $fk_parent_line = $result;
890 $this->error = $newinvoiceline->error;
891 $this->errors = $newinvoiceline->errors;
896 } elseif (!$error && empty($this->fac_rec)) {
899 dol_syslog(
"There is ".count($this->lines).
" lines that are array lines");
901 foreach ($this->lines as $i => $val) {
902 $line = $this->lines[$i];
906 if (!is_object($line)) {
907 $line = (object) $line;
912 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
917 $vatrate = $line->tva_tx;
918 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', $vatrate)) {
919 $vatrate .=
' ('.$line->vat_src_code.
')';
922 if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
923 $originid = $line->origin_id;
924 $origintype = $line->origin;
926 $originid = $line->id;
927 $origintype = $this->element;
931 if (empty($line->ref_ext)) {
943 $line->remise_percent,
946 $line->fk_code_ventilation,
948 $line->fk_remise_except,
957 $line->fk_fournprice,
960 $line->array_options,
961 $line->situation_percent,
964 $line->multicurrency_subprice,
969 $this->error = $this->
db->lasterror();
971 $this->
db->rollback();
976 if ($result > 0 && $line->product_type == 9) {
977 $fk_parent_line = $result;
986 if (!$error && $this->fac_rec > 0) {
987 foreach ($_facrec->lines as $i => $val) {
988 if ($_facrec->lines[$i]->fk_product) {
990 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
1001 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1002 $tva_npr = $_facrec->lines[$i]->info_bits;
1003 if (empty($tva_tx)) {
1006 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1007 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1009 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1010 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1013 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1014 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1016 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1021 if ($conf->global->MARGIN_TYPE ==
'costprice' && !empty($producttmp->cost_price)) {
1022 $buyprice = $producttmp->cost_price;
1023 } elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE ==
'costprice' || $conf->global->MARGIN_TYPE ==
'pmp') && !empty($producttmp->pmp)) {
1024 $buyprice = $producttmp->pmp;
1026 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1027 if ($producttmp->product_fourn_price_id > 0) {
1028 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1034 $result_insert = $this->
addline(
1035 $_facrec->lines[$i]->desc,
1036 $_facrec->lines[$i]->subprice,
1037 $_facrec->lines[$i]->qty,
1041 $_facrec->lines[$i]->fk_product,
1042 $_facrec->lines[$i]->remise_percent,
1043 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1044 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1050 $_facrec->lines[$i]->product_type,
1051 $_facrec->lines[$i]->rang,
1052 $_facrec->lines[$i]->special_code,
1056 $fk_product_fournisseur_price,
1058 $_facrec->lines[$i]->label,
1059 empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options,
1060 $_facrec->lines[$i]->situation_percent,
1062 $_facrec->lines[$i]->fk_unit,
1063 $_facrec->lines[$i]->multicurrency_subprice,
1064 $_facrec->lines[$i]->ref_ext,
1068 if ($result_insert < 0) {
1070 $this->error = $this->
db->error();
1089 if (!$error && !$notrigger) {
1099 $this->
db->commit();
1102 $this->
db->rollback();
1106 $this->error = $langs->trans(
'FailedToUpdatePrice');
1107 $this->
db->rollback();
1111 dol_syslog(get_class($this).
"::create error ".$this->error, LOG_ERR);
1112 $this->
db->rollback();
1116 $this->error = $this->
db->error();
1117 $this->
db->rollback();
1141 if (!empty($this->array_options)) {
1142 $facture->array_options = $this->array_options;
1145 foreach ($this->lines as &$line) {
1146 $line->fetch_optionals();
1150 $facture->type = $this->type;
1151 $facture->socid = $this->socid;
1152 $facture->date = $this->date;
1153 $facture->date_pointoftax = $this->date_pointoftax;
1154 $facture->note_public = $this->note_public;
1155 $facture->note_private = $this->note_private;
1156 $facture->ref_client = $this->ref_client;
1157 $facture->modelpdf = $this->model_pdf;
1158 $facture->model_pdf = $this->model_pdf;
1159 $facture->fk_project = $this->fk_project;
1160 $facture->cond_reglement_id = $this->cond_reglement_id;
1161 $facture->mode_reglement_id = $this->mode_reglement_id;
1162 $facture->remise_absolue = $this->remise_absolue;
1163 $facture->remise_percent = $this->remise_percent;
1165 $facture->origin = $this->origin;
1166 $facture->origin_id = $this->origin_id;
1168 $facture->lines = $this->lines;
1169 $facture->situation_counter = $this->situation_counter;
1170 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1171 $facture->situation_final = $this->situation_final;
1173 $facture->retained_warranty = $this->retained_warranty;
1174 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1175 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1177 $facture->fk_user_author = $user->id;
1181 foreach ($facture->lines as $i => $tmpline) {
1182 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1183 if ($invertdetail) {
1184 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1185 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1186 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1187 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1188 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1189 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1190 $facture->lines[$i]->ref_ext =
'';
1194 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1196 $facid = $facture->create($user);
1198 $this->error = $facture->error;
1199 $this->errors = $facture->errors;
1200 } elseif ($this->
type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
1203 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1204 foreach ($Tfk_object as $fk_object) {
1205 $facture->add_object_linked($typeObject, $fk_object);
1209 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1225 global $conf, $hookmanager;
1233 $object->fetch($fromid);
1236 $objFrom = clone $object;
1239 if (!empty($this->socid) && $this->socid != $object->socid) {
1242 if ($objsoc->fetch($this->socid) > 0) {
1243 $object->socid = $objsoc->id;
1244 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1245 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1246 $object->fk_project =
'';
1247 $object->fk_delivery_address =
'';
1254 $object->statut = self::STATUS_DRAFT;
1255 $object->status = self::STATUS_DRAFT;
1258 $object->date = (empty($this->date) ?
dol_now() : $this->date);
1259 $object->user_author = $user->id;
1260 $object->user_valid = null;
1261 $object->fk_user_author = $user->id;
1262 $object->fk_user_valid = null;
1263 $object->fk_facture_source = 0;
1264 $object->date_creation =
'';
1265 $object->date_modification =
'';
1266 $object->date_validation =
'';
1267 $object->ref_client =
'';
1268 $object->close_code =
'';
1269 $object->close_note =
'';
1270 if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) {
1271 $object->note_private =
'';
1272 $object->note_public =
'';
1276 foreach ($object->lines as $i => $line) {
1277 if (($object->lines[$i]->info_bits & 0x02) == 0x02) {
1278 unset($object->lines[$i]);
1284 if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
1296 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1297 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1301 $object->lines[$i]->date_start = $newFirst;
1302 $object->lines[$i]->date_end = $newLast;
1306 $object->lines[$i]->ref_ext =
'';
1310 $object->context[
'createfromclone'] =
'createfromclone';
1311 $result = $object->create($user);
1314 $this->error = $object->error;
1315 $this->errors = $object->errors;
1318 if ($object->copy_linked_contact($objFrom,
'internal') < 0) {
1320 $this->error = $object->error;
1321 $this->errors = $object->errors;
1322 } elseif ($object->socid == $objFrom->socid) {
1324 if ($object->copy_linked_contact($objFrom,
'external') < 0) {
1326 $this->error = $object->error;
1327 $this->errors = $object->errors;
1334 if (is_object($hookmanager)) {
1335 $parameters = array(
'objFrom'=>$objFrom);
1337 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $object, $action);
1344 unset($object->context[
'createfromclone']);
1348 $this->
db->commit();
1351 $this->
db->rollback();
1365 global $conf, $hookmanager;
1373 $num = count($object->lines);
1374 for ($i = 0; $i < $num; $i++) {
1377 $line->libelle = $object->lines[$i]->libelle;
1378 $line->label = $object->lines[$i]->label;
1379 $line->desc = $object->lines[$i]->desc;
1380 $line->subprice = $object->lines[$i]->subprice;
1381 $line->total_ht = $object->lines[$i]->total_ht;
1382 $line->total_tva = $object->lines[$i]->total_tva;
1383 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1384 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1385 $line->total_ttc = $object->lines[$i]->total_ttc;
1386 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1387 $line->tva_tx = $object->lines[$i]->tva_tx;
1388 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1389 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1390 $line->qty = $object->lines[$i]->qty;
1391 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1392 $line->remise_percent = $object->lines[$i]->remise_percent;
1393 $line->fk_product = $object->lines[$i]->fk_product;
1394 $line->info_bits = $object->lines[$i]->info_bits;
1395 $line->product_type = $object->lines[$i]->product_type;
1396 $line->rang = $object->lines[$i]->rang;
1397 $line->special_code = $object->lines[$i]->special_code;
1398 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1399 $line->fk_unit = $object->lines[$i]->fk_unit;
1400 $line->date_start = $object->lines[$i]->date_start;
1401 $line->date_end = $object->lines[$i]->date_end;
1404 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1405 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1406 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1407 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1408 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1409 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1411 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1412 $marginInfos =
getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
1413 $line->pa_ht = $marginInfos[0];
1416 $object->lines[$i]->fetch_optionals();
1417 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1418 $line->array_options[$options_key] = $value;
1421 $this->lines[$i] = $line;
1424 $this->socid = $object->socid;
1425 $this->fk_project = $object->fk_project;
1426 $this->fk_account = $object->fk_account;
1427 $this->cond_reglement_id = $object->cond_reglement_id;
1428 $this->mode_reglement_id = $object->mode_reglement_id;
1429 $this->availability_id = $object->availability_id;
1430 $this->demand_reason_id = $object->demand_reason_id;
1431 $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
1432 $this->date_livraison = $object->delivery_date;
1433 $this->fk_delivery_address = $object->fk_delivery_address;
1434 $this->contact_id = $object->contact_id;
1435 $this->ref_client = $object->ref_client;
1437 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1438 $this->note_private = $object->note_private;
1439 $this->note_public = $object->note_public;
1442 $this->module_source = $object->module_source;
1443 $this->pos_source = $object->pos_source;
1445 $this->origin = $object->element;
1446 $this->origin_id = $object->id;
1448 $this->fk_user_author = $user->id;
1451 $object->fetch_optionals();
1452 foreach ($object->array_options as $options_key => $value) {
1453 $this->array_options[$options_key] = $value;
1457 $this->linked_objects[$this->origin] = $this->origin_id;
1458 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1459 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1462 $ret = $this->
create($user);
1466 $hookmanager->initHooks(array(
'invoicedao'));
1468 $parameters = array(
'objFrom'=>$object);
1470 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1499 global $conf, $langs, $hookmanager, $action;
1501 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1502 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1507 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1511 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1513 if ($date > (
dol_get_last_hour(
dol_now(
'tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1514 $origin->error =
'ErrorDateIsInFuture';
1518 if ($payment_terms_id <= 0) {
1519 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1523 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1525 if (empty($payment_conditions_deposit_percent)) {
1526 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1530 if (empty($origin->deposit_percent)) {
1531 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1535 $deposit =
new self($origin->db);
1536 $deposit->socid = $origin->socid;
1537 $deposit->type = self::TYPE_DEPOSIT;
1538 $deposit->fk_project = $origin->fk_project;
1539 $deposit->ref_client = $origin->ref_client;
1540 $deposit->date = $date;
1541 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1542 $deposit->cond_reglement_id = $payment_terms_id;
1543 $deposit->availability_id = $origin->availability_id;
1544 $deposit->demand_reason_id = $origin->demand_reason_id;
1545 $deposit->fk_account = $origin->fk_account;
1546 $deposit->fk_incoterms = $origin->fk_incoterms;
1547 $deposit->location_incoterms = $origin->location_incoterms;
1548 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1549 $deposit->multicurrency_code = $origin->multicurrency_code;
1550 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1551 $deposit->module_source = $origin->module_source;
1552 $deposit->pos_source = $origin->pos_source;
1553 $deposit->model_pdf =
'crabe';
1555 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1557 if (!empty($conf->global->$modelByTypeConfName)) {
1558 $deposit->model_pdf = $conf->global->$modelByTypeConfName;
1559 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
1560 $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
1563 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1564 $deposit->note_private = $origin->note_private;
1565 $deposit->note_public = $origin->note_public;
1568 $deposit->origin = $origin->element;
1569 $deposit->origin_id = $origin->id;
1573 foreach ($origin->array_options as $extrakey => $value) {
1574 $deposit->array_options[$extrakey] = $value;
1577 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1579 foreach ($overrideFields as $key => $value) {
1580 $deposit->$key = $value;
1583 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1585 $origin->db->begin();
1588 $createReturn = $deposit->create($user, $notrigger);
1590 if ($createReturn <= 0) {
1591 $origin->db->rollback();
1592 $origin->error = $deposit->error;
1593 $origin->errors = $deposit->errors;
1597 $amount_ttc_diff = 0;
1598 $amountdeposit = array();
1599 $descriptions = array();
1601 if (! empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1602 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1604 $TTotalByTva = array();
1605 foreach ($origin->lines as &$line) {
1606 if (!empty($line->special_code)) {
1609 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1610 $descriptions[$line->tva_tx] .=
'<li>' . (! empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1611 $descriptions[$line->tva_tx] .= (! empty($line->product_label) ? $line->product_label .
' - ' :
'');
1612 $descriptions[$line->tva_tx] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1613 $descriptions[$line->tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1616 foreach ($TTotalByTva as $tva => &$total) {
1617 $coef = $total / $origin->total_ttc;
1618 $am = $amount * $coef;
1619 $amount_ttc_diff += $am;
1620 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1624 $lines = $origin->lines;
1625 $numlines = count($lines);
1626 for ($i = 0; $i < $numlines; $i++) {
1627 if (empty($lines[$i]->qty)) {
1630 if (!empty($lines[$i]->special_code)) {
1634 $totalamount += $lines[$i]->total_ht;
1635 $tva_tx = $lines[$i]->tva_tx;
1636 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1637 $descriptions[$tva_tx] .=
'<li>' . (! empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1638 $descriptions[$tva_tx] .= (! empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1639 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1640 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1643 if ($totalamount == 0) {
1644 $amountdeposit[0] = 0;
1647 $amount_ttc_diff = $amountdeposit[0];
1650 foreach ($amountdeposit as $tva => $amount) {
1651 if (empty($amount)) {
1655 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1658 if (! empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && ! empty($descriptions[$tva])) {
1659 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1662 $addlineResult = $deposit->addline(
1669 (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1689 if ($addlineResult < 0) {
1690 $origin->db->rollback();
1691 $origin->error = $deposit->error;
1692 $origin->errors = $deposit->errors;
1697 $diff = $deposit->total_ttc - $amount_ttc_diff;
1699 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1700 $deposit->fetch_lines();
1701 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1703 $updatelineResult = $deposit->updateline(
1704 $deposit->lines[0]->id,
1705 $deposit->lines[0]->desc,
1707 $deposit->lines[0]->qty,
1708 $deposit->lines[0]->remise_percent,
1709 $deposit->lines[0]->date_start,
1710 $deposit->lines[0]->date_end,
1711 $deposit->lines[0]->tva_tx,
1715 $deposit->lines[0]->info_bits,
1716 $deposit->lines[0]->product_type,
1720 $deposit->lines[0]->pa_ht,
1721 $deposit->lines[0]->label,
1727 if ($updatelineResult < 0) {
1728 $origin->db->rollback();
1729 $origin->error = $deposit->error;
1730 $origin->errors = $deposit->errors;
1736 if (! is_object($hookmanager)) {
1737 require_once DOL_DOCUMENT_ROOT .
'/core/class/hookmanager.class.php';
1741 $hookmanager->initHooks(array(
'invoicedao'));
1743 $parameters = array(
'objFrom' => $origin);
1744 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1747 $origin->db->rollback();
1748 $origin->error = $hookmanager->error;
1749 $origin->errors = $hookmanager->errors;
1753 if (! empty($autoValidateDeposit)) {
1754 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1756 if ($validateReturn < 0) {
1757 $origin->db->rollback();
1758 $origin->error = $deposit->error;
1759 $origin->errors = $deposit->errors;
1764 unset($deposit->context[
'createdepositfromorigin']);
1766 $origin->db->commit();
1785 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
1787 global $langs, $conf, $user, $mysoc;
1789 if (!empty($conf->dol_no_mouse_hover)) {
1795 if ($option ==
'withdraw') {
1796 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
1798 $url = DOL_URL_ROOT.
'/compta/facture/card.php?facid='.$this->id;
1801 if (!$user->rights->facture->lire) {
1805 if ($option !==
'nolink') {
1807 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1808 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
1809 $add_save_lastsearch_values = 1;
1811 if ($add_save_lastsearch_values) {
1812 $url .=
'&save_lastsearch_values=1';
1820 $picto = $this->picto;
1821 if ($this->
type == self::TYPE_REPLACEMENT) {
1824 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1827 if ($this->
type == self::TYPE_DEPOSIT) {
1832 if ($user->rights->facture->lire) {
1833 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1834 if ($this->
type == self::TYPE_REPLACEMENT) {
1835 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv(
"ReplacementInvoice").
'</u>';
1837 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1838 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv(
"CreditNote").
'</u>';
1840 if ($this->
type == self::TYPE_DEPOSIT) {
1841 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv(
"Deposit").
'</u>';
1843 if ($this->
type == self::TYPE_SITUATION) {
1844 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv(
"InvoiceSituation").
'</u>';
1846 if (isset($this->statut) && isset($this->alreadypaid)) {
1847 $label .=
' '.$this->getLibStatut(5, $this->alreadypaid);
1849 if (!empty($this->
ref)) {
1850 $label .=
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
1852 if (!empty($this->ref_client)) {
1853 $label .=
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_client;
1855 if (!empty($this->date)) {
1856 $label .=
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
1858 if (!empty($this->total_ht)) {
1859 $label .=
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1861 if (!empty($this->total_tva)) {
1862 $label .=
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1864 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1865 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1867 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1868 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1870 if (!empty($this->total_ttc)) {
1871 $label .=
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1874 $label .=
' - '.$moretitle;
1878 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
1879 if (empty($notooltip) && $user->rights->facture->lire) {
1880 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1881 $label = $langs->trans(
"Invoice");
1882 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
1884 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
1885 $linkclose .=
' class="classfortooltip"';
1888 $linkstart =
'<a href="'.$url.
'"';
1889 $linkstart .= $linkclose.
'>';
1892 if ($option ==
'nolink') {
1897 $result .= $linkstart;
1899 $result .=
img_object(($notooltip ?
'' : $label), $picto, ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1901 if ($withpicto != 2) {
1902 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
1904 $result .= $linkend;
1906 if ($addlinktonotes) {
1907 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1910 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
1911 $result .=
' <span class="note inline-block">';
1912 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
1917 $result .=
'</span>';
1921 global $action, $hookmanager;
1922 $hookmanager->initHooks(array(
'invoicedao'));
1923 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value'=> $save_lastsearch_value,
'target' => $target);
1924 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
1926 $result = $hookmanager->resPrint;
1928 $result .= $hookmanager->resPrint;
1944 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused =
'', $fetch_situation =
false)
1946 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
1950 $sql =
'SELECT f.rowid,f.entity,f.ref,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc';
1951 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
1952 $sql .=
', f.remise_percent, f.remise_absolue, f.remise';
1953 $sql .=
', f.datef as df, f.date_pointoftax';
1954 $sql .=
', f.date_lim_reglement as dlr';
1955 $sql .=
', f.datec as datec';
1956 $sql .=
', f.date_valid as datev';
1957 $sql .=
', f.tms as datem';
1958 $sql .=
', f.note_private, f.note_public, f.fk_statut, 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';
1959 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
1960 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1961 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1962 $sql .=
', f.fk_account';
1963 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1964 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1965 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1966 $sql .=
', f.fk_incoterms, f.location_incoterms';
1967 $sql .=
', f.module_source, f.pos_source';
1968 $sql .=
", i.libelle as label_incoterms";
1969 $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";
1970 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
1971 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
1972 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
1973 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
1976 $sql .=
" WHERE f.rowid=".((int) $rowid);
1978 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
1980 $sql .=
" AND f.ref='".$this->db->escape($ref).
"'";
1983 $sql .=
" AND f.ref_ext='".$this->db->escape($ref_ext).
"'";
1986 $sql .=
" AND f.ref_int='".$this->db->escape($notused).
"'";
1990 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
1994 $obj = $this->
db->fetch_object(
$resql);
1996 $this->
id = $obj->rowid;
1997 $this->entity = $obj->entity;
1999 $this->
ref = $obj->ref;
2000 $this->ref_client = $obj->ref_client;
2001 $this->ref_customer = $obj->ref_client;
2002 $this->ref_ext = $obj->ref_ext;
2003 $this->
type = $obj->type;
2004 $this->date = $this->
db->jdate($obj->df);
2005 $this->date_pointoftax = $this->
db->jdate($obj->date_pointoftax);
2006 $this->date_creation = $this->
db->jdate($obj->datec);
2007 $this->date_validation = $this->
db->jdate($obj->datev);
2008 $this->date_modification = $this->
db->jdate($obj->datem);
2009 $this->datem = $this->
db->jdate($obj->datem);
2010 $this->remise_percent = $obj->remise_percent;
2011 $this->remise_absolue = $obj->remise_absolue;
2012 $this->total_ht = $obj->total_ht;
2013 $this->total_tva = $obj->total_tva;
2014 $this->total_localtax1 = $obj->localtax1;
2015 $this->total_localtax2 = $obj->localtax2;
2016 $this->total_ttc = $obj->total_ttc;
2017 $this->revenuestamp = $obj->revenuestamp;
2018 $this->paye = $obj->paye;
2019 $this->close_code = $obj->close_code;
2020 $this->close_note = $obj->close_note;
2022 $this->socid = $obj->fk_soc;
2023 $this->thirdparty = null;
2025 $this->fk_project = $obj->fk_project;
2026 $this->project = null;
2028 $this->statut = $obj->fk_statut;
2029 $this->status = $obj->fk_statut;
2031 $this->date_lim_reglement = $this->
db->jdate($obj->dlr);
2032 $this->mode_reglement_id = $obj->fk_mode_reglement;
2033 $this->mode_reglement_code = $obj->mode_reglement_code;
2034 $this->mode_reglement = $obj->mode_reglement_libelle;
2035 $this->cond_reglement_id = $obj->fk_cond_reglement;
2036 $this->cond_reglement_code = $obj->cond_reglement_code;
2037 $this->cond_reglement = $obj->cond_reglement_libelle;
2038 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2039 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
2040 $this->fk_facture_source = $obj->fk_facture_source;
2041 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2042 $this->note = $obj->note_private;
2043 $this->note_private = $obj->note_private;
2044 $this->note_public = $obj->note_public;
2045 $this->user_author = $obj->fk_user_author;
2046 $this->user_valid = $obj->fk_user_valid;
2047 $this->user_modification = $obj->fk_user_modif;
2048 $this->fk_user_author = $obj->fk_user_author;
2049 $this->fk_user_valid = $obj->fk_user_valid;
2050 $this->fk_user_modif = $obj->fk_user_modif;
2051 $this->model_pdf = $obj->model_pdf;
2052 $this->modelpdf = $obj->model_pdf;
2053 $this->last_main_doc = $obj->last_main_doc;
2054 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2055 $this->situation_counter = $obj->situation_counter;
2056 $this->situation_final = $obj->situation_final;
2057 $this->retained_warranty = $obj->retained_warranty;
2058 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2059 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2061 $this->extraparams = (array) json_decode($obj->extraparams,
true);
2064 $this->fk_incoterms = $obj->fk_incoterms;
2065 $this->location_incoterms = $obj->location_incoterms;
2066 $this->label_incoterms = $obj->label_incoterms;
2068 $this->module_source = $obj->module_source;
2069 $this->pos_source = $obj->pos_source;
2072 $this->fk_multicurrency = $obj->fk_multicurrency;
2073 $this->multicurrency_code = $obj->multicurrency_code;
2074 $this->multicurrency_tx = $obj->multicurrency_tx;
2075 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2076 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2077 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2079 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2083 if ($this->status == self::STATUS_DRAFT) {
2084 $this->brouillon = 1;
2092 $this->lines = array();
2096 $this->error = $this->
db->error();
2104 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2106 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2110 $this->error = $this->
db->lasterror();
2125 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2128 global $langs, $conf;
2130 $this->lines = array();
2132 $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,';
2133 $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,';
2134 $sql .=
' l.situation_percent, l.fk_prev_id,';
2135 $sql .=
' l.rang, l.special_code,';
2136 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2137 $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,';
2138 $sql .=
' l.fk_unit,';
2139 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2140 $sql .=
' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2141 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2142 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2143 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2144 $sql .=
' ORDER BY l.rang, l.rowid';
2146 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2147 $result = $this->
db->query($sql);
2149 $num = $this->
db->num_rows($result);
2152 $objp = $this->
db->fetch_object($result);
2155 $line->id = $objp->rowid;
2156 $line->rowid = $objp->rowid;
2157 $line->fk_facture = $objp->fk_facture;
2158 $line->label = $objp->custom_label;
2159 $line->desc = $objp->description;
2160 $line->description = $objp->description;
2161 $line->product_type = $objp->product_type;
2162 $line->ref = $objp->product_ref;
2163 $line->product_ref = $objp->product_ref;
2164 $line->libelle = $objp->product_label;
2165 $line->product_label = $objp->product_label;
2166 $line->product_desc = $objp->product_desc;
2167 $line->fk_product_type = $objp->fk_product_type;
2168 $line->qty = $objp->qty;
2169 $line->subprice = $objp->subprice;
2170 $line->ref_ext = $objp->ref_ext;
2172 $line->vat_src_code = $objp->vat_src_code;
2173 $line->tva_tx = $objp->tva_tx;
2174 $line->localtax1_tx = $objp->localtax1_tx;
2175 $line->localtax2_tx = $objp->localtax2_tx;
2176 $line->localtax1_type = $objp->localtax1_type;
2177 $line->localtax2_type = $objp->localtax2_type;
2178 $line->remise_percent = $objp->remise_percent;
2179 $line->fk_remise_except = $objp->fk_remise_except;
2180 $line->fk_product = $objp->fk_product;
2181 $line->date_start = $this->
db->jdate($objp->date_start);
2182 $line->date_end = $this->
db->jdate($objp->date_end);
2183 $line->date_start = $this->
db->jdate($objp->date_start);
2184 $line->date_end = $this->
db->jdate($objp->date_end);
2185 $line->info_bits = $objp->info_bits;
2186 $line->total_ht = $objp->total_ht;
2187 $line->total_tva = $objp->total_tva;
2188 $line->total_localtax1 = $objp->total_localtax1;
2189 $line->total_localtax2 = $objp->total_localtax2;
2190 $line->total_ttc = $objp->total_ttc;
2191 $line->code_ventilation = $objp->fk_code_ventilation;
2192 $line->fk_fournprice = $objp->fk_fournprice;
2193 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2194 $line->pa_ht = $marginInfos[0];
2195 $line->marge_tx = $marginInfos[1];
2196 $line->marque_tx = $marginInfos[2];
2197 $line->rang = $objp->rang;
2198 $line->special_code = $objp->special_code;
2199 $line->fk_parent_line = $objp->fk_parent_line;
2200 $line->situation_percent = $objp->situation_percent;
2201 $line->fk_prev_id = $objp->fk_prev_id;
2202 $line->fk_unit = $objp->fk_unit;
2205 $line->fk_accounting_account = $objp->fk_code_ventilation;
2208 $line->fk_multicurrency = $objp->fk_multicurrency;
2209 $line->multicurrency_code = $objp->multicurrency_code;
2210 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2211 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2212 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2213 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2215 $line->fetch_optionals();
2218 if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2220 $tmpproduct->fetch($objp->fk_product);
2221 $tmpproduct->getMultiLangs();
2223 $line->multilangs = $tmpproduct->multilangs;
2226 $this->lines[$i] = $line;
2230 $this->
db->free($result);
2233 $this->error = $this->
db->error();
2248 $this->tab_previous_situation_invoice = array();
2249 $this->tab_next_situation_invoice = array();
2251 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2252 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2253 $sql .=
' AND entity = '.((int) $this->entity);
2254 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2255 $sql .=
' ORDER BY situation_counter ASC';
2257 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2258 $result = $this->
db->query($sql);
2259 if ($result && $this->
db->num_rows($result) > 0) {
2260 while ($objp = $this->
db->fetch_object($result)) {
2262 if ($invoice->fetch($objp->rowid) > 0) {
2263 if ($objp->situation_counter < $this->situation_counter
2264 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2266 $this->tab_previous_situation_invoice[] = $invoice;
2268 $this->tab_next_situation_invoice[] = $invoice;
2289 if (empty($this->
type)) {
2290 $this->
type = self::TYPE_STANDARD;
2292 if (isset($this->
ref)) {
2293 $this->
ref = trim($this->
ref);
2295 if (isset($this->ref_ext)) {
2296 $this->ref_ext = trim($this->ref_ext);
2298 if (isset($this->ref_client)) {
2299 $this->ref_client = trim($this->ref_client);
2301 if (isset($this->increment)) {
2302 $this->increment = trim($this->increment);
2304 if (isset($this->close_code)) {
2305 $this->close_code = trim($this->close_code);
2307 if (isset($this->close_note)) {
2308 $this->close_note = trim($this->close_note);
2310 if (isset($this->note) || isset($this->note_private)) {
2311 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2313 if (isset($this->note) || isset($this->note_private)) {
2314 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2316 if (isset($this->note_public)) {
2317 $this->note_public = trim($this->note_public);
2319 if (isset($this->model_pdf)) {
2320 $this->model_pdf = trim($this->model_pdf);
2322 if (isset($this->import_key)) {
2323 $this->import_key = trim($this->import_key);
2325 if (isset($this->retained_warranty)) {
2326 $this->retained_warranty = floatval($this->retained_warranty);
2334 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2335 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2336 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2337 $sql .=
" type=".(isset($this->
type) ? $this->
db->escape($this->
type) :
"null").
",";
2338 $sql .=
" ref_client=".(isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null").
",";
2339 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2340 $sql .=
" fk_soc=".(isset($this->socid) ? $this->
db->escape($this->socid) :
"null").
",";
2341 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2342 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2343 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2344 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2345 $sql .=
" paye=".(isset($this->paye) ? $this->
db->escape($this->paye) : 0).
",";
2346 $sql .=
" remise_percent=".(isset($this->remise_percent) ? $this->
db->escape($this->remise_percent) :
"null").
",";
2347 $sql .=
" remise_absolue=".(isset($this->remise_absolue) ? $this->
db->escape($this->remise_absolue) :
"null").
",";
2348 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2349 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2350 $sql .=
" total_tva=".(isset($this->total_tva) ? $this->total_tva :
"null").
",";
2351 $sql .=
" localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 :
"null").
",";
2352 $sql .=
" localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 :
"null").
",";
2353 $sql .=
" total_ht=".(isset($this->total_ht) ? $this->total_ht :
"null").
",";
2354 $sql .=
" total_ttc=".(isset($this->total_ttc) ? $this->total_ttc :
"null").
",";
2355 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? $this->
db->escape($this->revenuestamp) :
"null").
",";
2356 $sql .=
" fk_statut=".(isset($this->statut) ? $this->
db->escape($this->statut) :
"null").
",";
2357 $sql .=
" fk_user_author=".(isset($this->user_author) ? $this->
db->escape($this->user_author) :
"null").
",";
2358 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? $this->
db->escape($this->fk_user_valid) :
"null").
",";
2359 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? $this->
db->escape($this->fk_facture_source) :
"null").
",";
2360 $sql .=
" fk_projet=".(isset($this->fk_project) ? $this->
db->escape($this->fk_project) :
"null").
",";
2361 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->
db->escape($this->cond_reglement_id) :
"null").
",";
2362 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->
db->escape($this->mode_reglement_id) :
"null").
",";
2363 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2364 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2365 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2366 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2367 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2368 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : $this->
db->escape($this->situation_cycle_ref)).
",";
2369 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : $this->
db->escape($this->situation_counter)).
",";
2370 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : $this->
db->escape($this->situation_final)).
",";
2371 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty)).
",";
2372 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2373 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) :
"null");
2374 $sql .=
" WHERE rowid=".((int) $this->
id);
2378 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2382 $this->errors[] =
"Error ".$this->db->lasterror();
2392 if (!$error && !$notrigger) {
2403 foreach ($this->errors as $errmsg) {
2404 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2405 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2407 $this->
db->rollback();
2410 $this->
db->commit();
2426 global $conf, $langs;
2428 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2429 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2434 $result = $remise->fetch($idremise);
2437 if ($remise->fk_facture) {
2438 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2439 $this->
db->rollback();
2444 $facligne->fk_facture = $this->id;
2445 $facligne->fk_remise_except = $remise->id;
2446 $facligne->desc = $remise->description;
2447 $facligne->vat_src_code = $remise->vat_src_code;
2448 $facligne->tva_tx = $remise->tva_tx;
2449 $facligne->subprice = -$remise->amount_ht;
2450 $facligne->fk_product = 0;
2452 $facligne->remise_percent = 0;
2453 $facligne->rang = -1;
2454 $facligne->info_bits = 2;
2456 if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
2457 $facligne->rang = 1;
2458 $linecount = count($this->lines);
2459 for ($ii = 1; $ii <= $linecount; $ii++) {
2465 if ($remise->fk_facture_source > 0) {
2467 $srcinvoice->fetch($remise->fk_facture_source);
2468 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2470 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2471 $facligne->pa_ht = $arraytmp[
'pa_total'];
2474 $facligne->total_ht = -$remise->amount_ht;
2475 $facligne->total_tva = -$remise->amount_tva;
2476 $facligne->total_ttc = -$remise->amount_ttc;
2478 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2479 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2480 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2481 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2483 $lineid = $facligne->insert();
2488 $result = $remise->link_to_invoice($lineid, 0);
2490 $this->error = $remise->error;
2491 $this->
db->rollback();
2495 $this->
db->commit();
2498 $this->error = $facligne->error;
2499 $this->
db->rollback();
2503 $this->error = $facligne->error;
2504 $this->
db->rollback();
2508 $this->
db->rollback();
2530 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2531 if (empty($ref_client)) {
2532 $sql .=
' SET ref_client = NULL';
2534 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2536 $sql .=
" WHERE rowid = ".((int) $this->
id);
2538 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2541 $this->errors[] = $this->
db->error();
2546 $this->ref_client = $ref_client;
2549 if (!$notrigger && empty($error)) {
2559 $this->ref_client = $ref_client;
2561 $this->
db->commit();
2564 foreach ($this->errors as $errmsg) {
2565 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2566 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2568 $this->
db->rollback();
2581 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2583 global $langs, $conf;
2584 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2588 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2601 if (!$error && !$notrigger) {
2615 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2629 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2630 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2631 $sql .=
' AND fk_facture_line IS NULL';
2636 $list_rowid_det = array();
2637 foreach ($this->lines as $key => $invoiceline) {
2638 $list_rowid_det[] = $invoiceline->id;
2642 if (count($list_rowid_det)) {
2643 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2644 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2645 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(join(
',', $list_rowid_det)).
')';
2647 if (!$this->
db->query($sql)) {
2648 $this->error = $this->
db->error().
" sql=".$sql;
2649 $this->errors[] = $this->error;
2650 $this->
db->rollback();
2657 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2658 $sql .=
' SET fk_invoice = NULL';
2659 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2661 if (!$this->
db->query($sql)) {
2662 $this->error = $this->
db->error().
" sql=".$sql;
2663 $this->errors[] = $this->error;
2664 $this->
db->rollback();
2668 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'projet_task_time';
2669 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2670 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2672 if (!$this->
db->query($sql)) {
2673 $this->error = $this->
db->error().
" sql=".$sql;
2674 $this->errors[] = $this->error;
2675 $this->
db->rollback();
2680 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
2681 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2682 $langs->load(
"agenda");
2684 $num = count($this->lines);
2685 for ($i = 0; $i < $num; $i++) {
2686 if ($this->lines[$i]->fk_product > 0) {
2688 $mouvP->origin = &$this;
2689 $mouvP->setOrigin($this->element, $this->
id);
2691 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2692 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2694 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2701 $main = MAIN_DB_PREFIX.
'facturedet';
2702 $ef = $main.
"_extrafields";
2703 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2705 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2708 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2717 if ($conf->facture->dir_output && !empty($this->
ref)) {
2718 $dir = $conf->facture->dir_output.
"/".$ref;
2719 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2720 if (file_exists($file)) {
2724 $langs->load(
"errors");
2725 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2726 $this->errors[] = $this->error;
2727 $this->
db->rollback();
2731 if (file_exists($dir)) {
2733 $langs->load(
"errors");
2734 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2735 $this->errors[] = $this->error;
2736 $this->
db->rollback();
2742 $this->
db->commit();
2745 $this->error = $this->
db->lasterror().
" sql=".$sql;
2746 $this->errors[] = $this->error;
2747 $this->
db->rollback();
2751 $this->error = $this->
db->lasterror().
" sql=".$sql;
2752 $this->errors[] = $this->error;
2753 $this->
db->rollback();
2757 $this->
db->rollback();
2774 public function set_paid($user, $close_code =
'', $close_note =
'')
2777 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2778 return $this->
setPaid($user, $close_code, $close_note);
2790 public function setPaid($user, $close_code =
'', $close_note =
'')
2794 if ($this->paye != 1) {
2799 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
2801 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2802 $sql .=
' fk_statut='.self::STATUS_CLOSED;
2807 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2810 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2812 $sql .=
', fk_user_closing = '.((int) $user->id);
2813 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
2814 $sql .=
" WHERE rowid = ".((int) $this->
id);
2826 $this->error = $this->
db->lasterror();
2830 $this->
db->commit();
2833 $this->
db->rollback();
2856 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
2874 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2875 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
2876 $sql .=
' date_closing=null,';
2877 $sql .=
' fk_user_closing=null';
2878 $sql .=
" WHERE rowid = ".((int) $this->
id);
2880 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
2891 $this->error = $this->
db->error();
2896 $this->
db->commit();
2899 $this->
db->rollback();
2921 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
2922 return $this->
setCanceled($user, $close_code, $close_note);
2935 public function setCanceled($user, $close_code =
'', $close_note =
'')
2937 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
2941 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2942 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
2944 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2947 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2949 $sql .=
" WHERE rowid = ".((int) $this->
id);
2955 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2956 $sql .=
' SET fk_facture = NULL';
2957 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
2964 $this->
db->rollback();
2969 $this->
db->commit();
2972 $this->error = $this->
db->error().
" sql=".$sql;
2973 $this->
db->rollback();
2977 $this->error = $this->
db->error().
" sql=".$sql;
2978 $this->
db->rollback();
2994 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
2996 global $conf, $langs, $mysoc;
2997 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2999 $productStatic = null;
3000 $warehouseStatic = null;
3001 if ($batch_rule > 0) {
3002 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3003 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3004 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3005 $productStatic =
new Product($this->
db);
3007 $productbatch =
new ProductBatch($this->
db);
3013 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3020 if ($this->statut != self::STATUS_DRAFT) {
3021 dol_syslog(get_class($this).
"::validate status is not draft. operation canceled.", LOG_WARNING);
3024 if (count($this->lines) <= 0) {
3025 $langs->load(
"errors");
3026 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3029 if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
3030 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
3031 $this->error =
'Permission denied';
3032 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
3035 if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
3037 if (!$last_of_type[0]) {
3038 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3044 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3045 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3046 foreach ($array_to_check as $key) {
3047 $keymin = strtolower($key);
3048 if (!property_exists($this->thirdparty, $keymin)) {
3051 $vallabel = $this->thirdparty->$keymin;
3053 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3055 if ($this->thirdparty->isACompany()) {
3057 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3058 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3059 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3060 $langs->load(
"errors");
3061 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3062 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3068 if ($key ==
'EMAIL') {
3070 if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
3071 $langs->load(
"errors");
3072 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3073 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3077 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3079 if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
3080 $langs->load(
"errors");
3081 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3082 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3091 $array_to_check = array(
'REF_CLIENT'=>
'RefCustomer');
3092 foreach ($array_to_check as $key => $val) {
3093 $keymin = strtolower($key);
3094 $vallabel = $this->$keymin;
3097 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3098 if (!$vallabel && !empty($conf->global->$keymandatory)) {
3099 $langs->load(
"errors");
3101 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val)), null,
'errors');
3108 if ($this->
type == self::TYPE_REPLACEMENT) {
3110 if ($this->fk_facture_source <= 0) {
3111 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3112 $this->
db->rollback();
3118 $result = $facreplaced->fetch($this->fk_facture_source);
3120 $this->error = $langs->trans(
"ErrorBadInvoice");
3121 $this->
db->rollback();
3126 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3127 if ($idreplacement && $idreplacement != $this->
id) {
3128 $facreplacement =
new Facture($this->
db);
3129 $facreplacement->fetch($idreplacement);
3130 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3131 $this->
db->rollback();
3135 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3137 $this->error = $facreplaced->error;
3138 $this->
db->rollback();
3144 if ($force_number) {
3145 $num = $force_number;
3146 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3147 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3162 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3163 $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).
"'";
3164 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3165 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3166 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3168 $sql .=
" WHERE rowid = ".((int) $this->
id);
3170 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3178 if (!$error && (preg_match(
'/^[\(]?PROV/i', $this->
ref))) {
3184 $result = $this->thirdparty->set_as_client();
3187 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
3188 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3189 $langs->load(
"agenda");
3192 $cpt = count($this->lines);
3193 for ($i = 0; $i < $cpt; $i++) {
3194 if ($this->lines[$i]->fk_product > 0) {
3196 $mouvP->origin = &$this;
3197 $mouvP->setOrigin($this->element, $this->
id);
3199 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3200 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3203 $this->error = $mouvP->error;
3206 $is_batch_line =
false;
3207 if ($batch_rule > 0) {
3208 $productStatic->fetch($this->lines[$i]->fk_product);
3209 if ($productStatic->hasbatch()) {
3210 $is_batch_line =
true;
3211 $product_qty_remain = $this->lines[$i]->qty;
3217 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3218 $sortorder =
'ASC,ASC,ASC,ASC';
3221 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ? null : 0), $sortfield, $sortorder);
3222 if (!is_array($resBatchList)) {
3224 $this->error = $this->
db->lasterror();
3228 $batchList = $resBatchList;
3229 if (empty($batchList)) {
3231 $langs->load(
'errors');
3232 $warehouseStatic->fetch($idwarehouse);
3233 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3234 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3237 foreach ($batchList as $batch) {
3238 if ($batch->qty <= 0) {
3243 if ($batch->qty >= $product_qty_remain) {
3244 $product_batch_qty = $product_qty_remain;
3247 $product_batch_qty = $batch->qty;
3249 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3252 $this->error = $mouvP->error;
3256 $product_qty_remain -= $product_batch_qty;
3258 if ($product_qty_remain <= 0) {
3263 if (!$error && $product_qty_remain > 0) {
3264 if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
3266 $batch = $batchList[0];
3267 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3270 $this->error = $mouvP->error;
3274 $langs->load(
'errors');
3275 $warehouseStatic->fetch($idwarehouse);
3276 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3277 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3284 if (!$is_batch_line) {
3285 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3288 $this->error = $mouvP->error;
3301 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3302 $invoice_situation =
new Facture($this->
db);
3303 $result = $invoice_situation->fetch($this->fk_facture_source);
3304 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3305 $invoice_situation->situation_final = 0;
3307 $result = $invoice_situation->setFinal($user, 1);
3310 $this->error = $invoice_situation->error;
3311 $this->errors = $invoice_situation->errors;
3317 if (!$error && !$notrigger) {
3327 $this->oldref = $this->ref;
3330 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3332 $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).
"'";
3333 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->
db->escape($this->
ref).
"' and entity = ".$conf->entity;
3337 $this->error = $this->
db->lasterror();
3343 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3344 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3345 if (!$error && file_exists($dirsource)) {
3346 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3348 if (@rename($dirsource, $dirdest)) {
3351 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3352 foreach ($listoffiles as $fileentry) {
3353 $dirsource = $fileentry[
'name'];
3354 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3355 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3356 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3357 @rename($dirsource, $dirdest);
3374 $this->statut = self::STATUS_VALIDATED;
3375 $this->status = self::STATUS_VALIDATED;
3376 $this->brouillon = 0;
3377 $this->date_validation = $now;
3380 if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3382 $nboflines = count($this->lines);
3383 while (($i < $nboflines) && $final) {
3384 $final = ($this->lines[$i]->situation_percent == 100);
3388 if (empty($final)) {
3389 $this->situation_final = 0;
3391 $this->situation_final = 1;
3402 $this->
db->commit();
3405 $this->
db->rollback();
3418 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3419 $is_last = $next_invoice->is_last_in_cycle();
3421 if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
3422 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3426 $next_invoice->brouillon = 1;
3428 foreach ($next_invoice->lines as $line) {
3429 $result = $next_invoice->updateline(
3434 $line->remise_percent,
3438 $line->localtax1_tx,
3439 $line->localtax2_tx,
3442 $line->product_type,
3443 $line->fk_parent_line,
3445 $line->fk_fournprice,
3448 $line->special_code,
3449 $line->array_options,
3450 $line->situation_percent,
3455 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3476 global $conf, $langs;
3480 if ($this->statut == self::STATUS_DRAFT) {
3481 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3489 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3490 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3491 $sql .=
" WHERE rowid = ".((int) $this->
id);
3493 $result = $this->
db->query($sql);
3496 $this->oldcopy = clone $this;
3500 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3501 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3502 $langs->load(
"agenda");
3504 $num = count($this->lines);
3505 for ($i = 0; $i < $num; $i++) {
3506 if ($this->lines[$i]->fk_product > 0) {
3508 $mouvP->origin = &$this;
3509 $mouvP->setOrigin($this->element, $this->
id);
3511 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3512 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3514 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3521 $old_statut = $this->statut;
3522 $this->brouillon = 1;
3523 $this->statut = self::STATUS_DRAFT;
3524 $this->status = self::STATUS_DRAFT;
3527 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3530 $this->statut = $old_statut;
3531 $this->status = $old_statut;
3532 $this->brouillon = 0;
3536 $this->
db->rollback();
3541 $this->
db->commit();
3544 $this->
db->rollback();
3548 $this->error = $this->
db->error();
3549 $this->
db->rollback();
3603 $remise_percent = 0,
3608 $fk_remise_except =
'',
3609 $price_base_type =
'HT',
3616 $fk_parent_line = 0,
3617 $fk_fournprice = null,
3621 $situation_percent = 100,
3626 $noupdateafterinsertline = 0
3630 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3634 global $mysoc, $conf, $langs;
3636 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, ventil=$ventil, 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);
3638 if ($this->statut == self::STATUS_DRAFT) {
3639 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3642 if (empty($remise_percent)) {
3643 $remise_percent = 0;
3648 if (empty($info_bits)) {
3654 if (empty($ventil)) {
3657 if (empty($txtva)) {
3660 if (empty($txlocaltax1)) {
3663 if (empty($txlocaltax2)) {
3666 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3667 $fk_parent_line = 0;
3669 if (empty($fk_prev_id)) {
3670 $fk_prev_id =
'null';
3672 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3673 $situation_percent = 100;
3675 if (empty($ref_ext)) {
3679 $remise_percent =
price2num($remise_percent);
3682 $pu_ht_devise =
price2num($pu_ht_devise);
3685 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3691 if ($price_base_type ==
'HT') {
3702 if ($date_start && $date_end && $date_start > $date_end) {
3703 $langs->load(
"errors");
3704 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3710 $product_type = $type;
3711 if (!empty($fk_product) && $fk_product > 0) {
3713 $result = $product->fetch($fk_product);
3714 $product_type = $product->type;
3716 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3717 $langs->load(
"errors");
3718 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3719 $this->
db->rollback();
3729 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3730 $vat_src_code = $reg[1];
3731 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3739 $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);
3741 $total_ht = $tabprice[0];
3742 $total_tva = $tabprice[1];
3743 $total_ttc = $tabprice[2];
3744 $total_localtax1 = $tabprice[9];
3745 $total_localtax2 = $tabprice[10];
3746 $pu_ht = $tabprice[3];
3749 $multicurrency_total_ht = $tabprice[16];
3750 $multicurrency_total_tva = $tabprice[17];
3751 $multicurrency_total_ttc = $tabprice[18];
3752 $pu_ht_devise = $tabprice[19];
3756 if ($ranktouse == -1) {
3757 $rangmax = $this->
line_max($fk_parent_line);
3758 $ranktouse = $rangmax + 1;
3764 $this->line->context = $this->context;
3766 $this->line->fk_facture = $this->id;
3767 $this->line->label = $label;
3768 $this->line->desc = $desc;
3769 $this->line->ref_ext = $ref_ext;
3771 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty);
3772 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
3774 $this->line->vat_src_code = $vat_src_code;
3775 $this->line->tva_tx = $txtva;
3776 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3777 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3778 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
3779 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
3781 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
3782 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
3783 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
3784 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
3785 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
3787 $this->line->fk_product = $fk_product;
3788 $this->line->product_type = $product_type;
3789 $this->line->remise_percent = $remise_percent;
3790 $this->line->date_start = $date_start;
3791 $this->line->date_end = $date_end;
3792 $this->line->ventil = $ventil;
3793 $this->line->rang = $ranktouse;
3794 $this->line->info_bits = $info_bits;
3795 $this->line->fk_remise_except = $fk_remise_except;
3797 $this->line->special_code = $special_code;
3798 $this->line->fk_parent_line = $fk_parent_line;
3799 $this->line->origin = $origin;
3800 $this->line->origin_id = $origin_id;
3801 $this->line->situation_percent = $situation_percent;
3802 $this->line->fk_prev_id = $fk_prev_id;
3803 $this->line->fk_unit = $fk_unit;
3806 $this->line->fk_fournprice = $fk_fournprice;
3807 $this->line->pa_ht = $pa_ht;
3810 $this->line->fk_multicurrency = $this->fk_multicurrency;
3811 $this->line->multicurrency_code = $this->multicurrency_code;
3812 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
3814 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
3815 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
3816 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
3818 if (is_array($array_options) && count($array_options) > 0) {
3819 $this->line->array_options = $array_options;
3822 $result = $this->line->insert();
3825 if (!empty($fk_parent_line)) {
3827 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
3828 $linecount = count($this->lines);
3829 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
3835 if (empty($noupdateafterinsertline)) {
3840 $this->
db->commit();
3841 return $this->line->id;
3843 $this->error = $this->
db->lasterror();
3844 $this->
db->rollback();
3848 $this->error = $this->line->error;
3849 $this->errors = $this->line->errors;
3850 $this->
db->rollback();
3854 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3890 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 = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext =
'', $rang = 0)
3892 global $conf, $user;
3895 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3898 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3900 global $mysoc, $langs;
3902 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);
3904 if ($this->statut == self::STATUS_DRAFT) {
3907 if (!$this->error) {
3908 $this->error = $langs->trans(
'invoiceLineProgressError');
3914 if ($date_start && $date_end && $date_start > $date_end) {
3915 $langs->load(
"errors");
3916 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3926 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3927 $fk_parent_line = 0;
3929 if (empty($special_code) || $special_code == 3) {
3932 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3933 $situation_percent = 100;
3935 if (empty($ref_ext)) {
3939 $remise_percent =
price2num($remise_percent);
3942 $pu_ht_devise =
price2num($pu_ht_devise);
3944 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3964 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3965 $vat_src_code = $reg[1];
3966 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3969 $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);
3971 $total_ht = $tabprice[0];
3972 $total_tva = $tabprice[1];
3973 $total_ttc = $tabprice[2];
3974 $total_localtax1 = $tabprice[9];
3975 $total_localtax2 = $tabprice[10];
3976 $pu_ht = $tabprice[3];
3977 $pu_tva = $tabprice[4];
3978 $pu_ttc = $tabprice[5];
3981 $multicurrency_total_ht = $tabprice[16];
3982 $multicurrency_total_tva = $tabprice[17];
3983 $multicurrency_total_ttc = $tabprice[18];
3984 $pu_ht_devise = $tabprice[19];
3989 if ($remise_percent > 0) {
3990 $remise = round(($pu * $remise_percent / 100), 2);
3991 $price = ($pu - $remise);
3997 $line->fetch($rowid);
3998 $line->fetch_optionals();
4000 if (!empty($line->fk_product)) {
4002 $result = $product->fetch($line->fk_product);
4003 $product_type = $product->type;
4005 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
4006 $langs->load(
"errors");
4007 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4008 $this->
db->rollback();
4013 $staticline = clone $line;
4015 $line->oldline = $staticline;
4016 $this->line = $line;
4017 $this->line->context = $this->context;
4018 $this->line->rang = $rang;
4021 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4022 $rangmax = $this->
line_max($fk_parent_line);
4023 $this->line->rang = $rangmax + 1;
4026 $this->line->id = $rowid;
4027 $this->line->rowid = $rowid;
4028 $this->line->label = $label;
4029 $this->line->desc = $desc;
4030 $this->line->ref_ext = $ref_ext;
4031 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty);
4033 $this->line->vat_src_code = $vat_src_code;
4034 $this->line->tva_tx = $txtva;
4035 $this->line->localtax1_tx = $txlocaltax1;
4036 $this->line->localtax2_tx = $txlocaltax2;
4037 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
4038 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
4040 $this->line->remise_percent = $remise_percent;
4041 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht);
4042 $this->line->date_start = $date_start;
4043 $this->line->date_end = $date_end;
4044 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht);
4045 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
4046 $this->line->total_localtax1 = $total_localtax1;
4047 $this->line->total_localtax2 = $total_localtax2;
4048 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
4049 $this->line->info_bits = $info_bits;
4050 $this->line->special_code = $special_code;
4051 $this->line->product_type = $type;
4052 $this->line->fk_parent_line = $fk_parent_line;
4053 $this->line->skip_update_total = $skip_update_total;
4054 $this->line->situation_percent = $situation_percent;
4055 $this->line->fk_unit = $fk_unit;
4057 $this->line->fk_fournprice = $fk_fournprice;
4058 $this->line->pa_ht = $pa_ht;
4061 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise);
4062 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht);
4063 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
4064 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4066 if (is_array($array_options) && count($array_options) > 0) {
4068 foreach ($array_options as $key => $value) {
4069 $this->line->array_options[$key] = $array_options[$key];
4073 $result = $this->line->update($user, $notrigger);
4076 if (!empty($fk_parent_line)) {
4082 $this->
db->commit();
4085 $this->error = $this->line->error;
4086 $this->
db->rollback();
4090 $this->error =
"Invoice statut makes operation forbidden";
4104 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4105 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4106 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4108 $result = $this->
db->query($sql);
4110 $this->error = $this->
db->error();
4114 $obj = $this->
db->fetch_object($result);
4116 if ($obj === null) {
4119 return $situation_percent < $obj->situation_percent;
4135 global $mysoc, $user;
4138 if (($line->info_bits & 2) == 2) {
4142 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4145 if ($percent > 100) {
4148 $line->situation_percent = $percent;
4149 $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,
'', $percent);
4150 $line->total_ht = $tabprice[0];
4151 $line->total_tva = $tabprice[1];
4152 $line->total_ttc = $tabprice[2];
4153 $line->total_localtax1 = $tabprice[9];
4154 $line->total_localtax2 = $tabprice[10];
4155 $line->multicurrency_total_ht = $tabprice[16];
4156 $line->multicurrency_total_tva = $tabprice[17];
4157 $line->multicurrency_total_ttc = $tabprice[18];
4158 $line->update($user);
4161 if ($update_price) {
4176 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4178 if ($this->statut != self::STATUS_DRAFT) {
4179 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4186 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
4187 $sql .=
' SET fk_facture_line = NULL';
4188 $sql .=
' WHERE fk_facture_line = '.((int) $rowid);
4190 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
4191 $result = $this->
db->query($sql);
4193 $this->error = $this->
db->error();
4194 $this->
db->rollback();
4200 $line->context = $this->context;
4203 $result = $line->fetch($rowid);
4204 if (!($result > 0)) {
4208 if ($line->delete($user) > 0) {
4212 $this->
db->commit();
4215 $this->
db->rollback();
4216 $this->error = $this->
db->lasterror();
4220 $this->
db->rollback();
4221 $this->error = $line->error;
4240 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4241 return $this->
setDiscount($user, $remise, $notrigger);
4255 if (empty($remise)) {
4259 if ($user->rights->facture->creer) {
4266 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4267 $sql .=
' SET remise_percent = '.((float) $remise);
4268 $sql .=
" WHERE rowid = ".((int) $this->
id);
4269 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4274 $this->errors[] = $this->
db->error();
4278 if (!$notrigger && empty($error)) {
4288 $this->remise_percent = $remise;
4291 $this->
db->commit();
4294 foreach ($this->errors as $errmsg) {
4295 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4296 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4298 $this->
db->rollback();
4317 if (empty($remise)) {
4321 if ($user->rights->facture->creer) {
4328 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4329 $sql .=
' SET remise_absolue = '.((float) $remise);
4330 $sql .=
" WHERE rowid = ".((int) $this->
id);
4331 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4336 $this->errors[] = $this->
db->error();
4341 $this->oldcopy = clone $this;
4342 $this->remise_absolue = $remise;
4346 if (!$notrigger && empty($error)) {
4356 $this->
db->commit();
4359 foreach ($this->errors as $errmsg) {
4360 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4361 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4363 $this->
db->rollback();
4379 global $conf, $langs;
4381 if ($this->module_source ==
'takepos') {
4382 $langs->load(
'cashdesk');
4384 $moduleName =
'takepos';
4385 $moduleSourceName =
'Takepos';
4386 $addonConstName =
'TAKEPOS_REF_ADDON';
4389 if (empty($conf->global->TAKEPOS_REF_ADDON)) {
4390 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4393 $addon = $conf->global->TAKEPOS_REF_ADDON;
4395 $langs->load(
'bills');
4397 $moduleName =
'facture';
4398 $moduleSourceName =
'Invoice';
4399 $addonConstName =
'FACTURE_ADDON';
4402 if (empty($conf->global->FACTURE_ADDON)) {
4403 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4404 } elseif ($conf->global->FACTURE_ADDON ==
'terre') {
4405 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4406 } elseif ($conf->global->FACTURE_ADDON ==
'mercure') {
4407 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4410 $addon = $conf->global->FACTURE_ADDON;
4413 if (!empty($addon)) {
4414 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = ".$conf->global->FACTURE_ADDON.
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4418 $file = $addon.
'.php';
4419 $classname = $addon;
4423 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4424 foreach ($dirmodels as $reldir) {
4425 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4428 if (is_file($dir.$file) && is_readable($dir.$file)) {
4429 $mybool |= include_once $dir.$file;
4435 $file = $addon.
'/'.$addon.
'.modules.php';
4436 $classname =
'mod_'.$moduleName.
'_'.$addon;
4437 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4439 foreach ($conf->file->dol_document_root as $dirroot) {
4440 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4443 if (is_file($dir.$file) && is_readable($dir.$file)) {
4444 $mybool |= include_once $dir.$file;
4454 $obj =
new $classname();
4456 $numref = $obj->getNextValue($soc, $this, $mode);
4463 if ($mode !=
'last' && !$numref) {
4464 $this->error = $obj->error;
4470 $langs->load(
'errors');
4471 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4484 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4485 $sql .=
' date_closing as dateclosing,';
4486 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4487 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4488 $sql .=
' WHERE c.rowid = '.((int) $id);
4490 $result = $this->
db->query($sql);
4492 if ($this->
db->num_rows($result)) {
4493 $obj = $this->
db->fetch_object($result);
4494 $this->
id = $obj->rowid;
4495 if ($obj->fk_user_author) {
4496 $cuser =
new User($this->
db);
4497 $cuser->fetch($obj->fk_user_author);
4498 $this->user_creation = $cuser;
4500 if ($obj->fk_user_valid) {
4501 $vuser =
new User($this->
db);
4502 $vuser->fetch($obj->fk_user_valid);
4503 $this->user_validation = $vuser;
4505 if ($obj->fk_user_closing) {
4506 $cluser =
new User($this->
db);
4507 $cluser->fetch($obj->fk_user_closing);
4508 $this->user_closing = $cluser;
4511 $this->date_creation = $this->
db->jdate($obj->datec);
4512 $this->date_modification = $this->
db->jdate($obj->datem);
4513 $this->date_validation = $this->
db->jdate($obj->datev);
4514 $this->date_closing = $this->
db->jdate($obj->dateclosing);
4516 $this->
db->free($result);
4537 public function liste_array($shortlist = 0, $draft = 0, $excluser =
'', $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4540 global $conf, $user;
4544 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4545 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4546 if (empty($user->rights->societe->client->voir) && !$socid) {
4547 $sql .=
", sc.fk_soc, sc.fk_user";
4549 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4550 if (empty($user->rights->societe->client->voir) && !$socid) {
4551 $sql .=
", ".MAIN_DB_PREFIX.
"societe_commerciaux as sc";
4553 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4554 $sql .=
" AND f.fk_soc = s.rowid";
4555 if (empty($user->rights->societe->client->voir) && !$socid) {
4556 $sql .=
" AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4559 $sql .=
" AND s.rowid = ".((int) $socid);
4562 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4564 if (is_object($excluser)) {
4565 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4567 $sql .= $this->
db->order($sortfield, $sortorder);
4568 $sql .= $this->
db->plimit($limit, $offset);
4570 $result = $this->
db->query($sql);
4572 $numc = $this->
db->num_rows($result);
4575 while ($i < $numc) {
4576 $obj = $this->
db->fetch_object($result);
4578 if ($shortlist == 1) {
4579 $ga[$obj->fid] = $obj->ref;
4580 } elseif ($shortlist == 2) {
4581 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4583 $ga[$i][
'id'] = $obj->fid;
4584 $ga[$i][
'ref'] = $obj->ref;
4585 $ga[$i][
'name'] = $obj->name;
4614 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4615 $sql .=
" ff.rowid as rowidnext";
4617 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4618 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4619 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4620 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4621 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4622 $sql .=
" AND f.paye = 0";
4623 $sql .=
" AND pf.fk_paiement IS NULL";
4624 $sql .=
" AND ff.fk_statut IS NULL";
4626 $sql .=
" AND f.fk_soc = ".((int) $socid);
4629 $sql .=
" ORDER BY f.ref";
4631 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4634 while ($obj = $this->
db->fetch_object(
$resql)) {
4635 $return[$obj->rowid] = array(
4636 'id' => $obj->rowid,
4638 'status' => $obj->status,
4639 'paid' => $obj->paid,
4646 $this->error = $this->
db->error();
4669 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
4670 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4671 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4672 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4673 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4674 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4678 $sql .=
" AND ff.type IS NULL";
4679 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4681 if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4683 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4684 $sql .=
'(SELECT MAX(fs.rowid)';
4685 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4686 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4687 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4688 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4690 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4692 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4695 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4699 $sql .=
" AND f.fk_soc = ".((int) $socid);
4701 $sql .=
" ORDER BY f.ref";
4703 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4706 while ($obj = $this->
db->fetch_object(
$resql)) {
4708 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4711 if ($obj->fk_statut == self::STATUS_CLOSED) {
4716 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4717 $return[$obj->rowid] = array(
'ref'=>$obj->ref,
'status'=>$obj->fk_statut,
'type'=>$obj->type,
'paye'=>$obj->paye,
'paymentornot'=>$paymentornot);
4723 $this->error = $this->
db->error();
4739 global $conf, $langs;
4743 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
4744 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4745 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4746 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4747 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4750 $sql .= $clause.
" f.paye=0";
4751 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4752 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
4754 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
4759 $langs->load(
"bills");
4763 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4764 $response->label = $langs->trans(
"CustomerBillsUnpaid");
4765 $response->labelShort = $langs->trans(
"Unpaid");
4766 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4769 $generic_facture =
new Facture($this->
db);
4771 while ($obj = $this->
db->fetch_object(
$resql)) {
4772 $generic_facture->date_lim_reglement = $this->
db->jdate($obj->datefin);
4773 $generic_facture->statut = $obj->fk_statut;
4775 $response->nbtodo++;
4776 $response->total += $obj->total_ht;
4778 if ($generic_facture->hasDelay()) {
4779 $response->nbtodolate++;
4780 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4788 $this->error = $this->
db->error();
4827 global $conf, $langs, $user;
4831 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
4836 $sql =
"SELECT rowid";
4837 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
4838 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
4839 $sql .= $this->
db->plimit(100);
4843 $num_prods = $this->
db->num_rows(
$resql);
4845 while ($i < $num_prods) {
4847 $row = $this->
db->fetch_row(
$resql);
4848 $prodids[$i] = $row[0];
4852 if (empty($num_prods)) {
4859 $this->
ref =
'SPECIMEN';
4860 $this->specimen = 1;
4862 $this->date = $nownotime;
4863 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4864 $this->cond_reglement_id = 1;
4865 $this->cond_reglement_code =
'RECEP';
4867 $this->mode_reglement_id = 0;
4868 $this->mode_reglement_code =
'';
4870 $this->note_public =
'This is a comment (public)';
4871 $this->note_private =
'This is a comment (private)';
4872 $this->note =
'This is a comment (private)';
4874 $this->fk_user_author = $user->id;
4876 $this->multicurrency_tx = 1;
4877 $this->multicurrency_code = $conf->currency;
4879 $this->fk_incoterms = 0;
4880 $this->location_incoterms =
'';
4882 if (empty($option) || $option !=
'nolines') {
4886 while ($xnbp < $nbp) {
4888 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
4890 $line->subprice = 100;
4891 $line->tva_tx = 19.6;
4892 $line->localtax1_tx = 0;
4893 $line->localtax2_tx = 0;
4894 $line->remise_percent = 0;
4896 $prodid = mt_rand(1, $num_prods);
4897 $line->fk_product = $prodids[$prodid];
4899 $line->total_ht = -100;
4900 $line->total_ttc = -119.6;
4901 $line->total_tva = -19.6;
4902 $line->multicurrency_total_ht = -200;
4903 $line->multicurrency_total_ttc = -239.2;
4904 $line->multicurrency_total_tva = -39.2;
4905 } elseif ($xnbp == 2) {
4906 $line->subprice = -100;
4907 $line->total_ht = -100;
4908 $line->total_ttc = -119.6;
4909 $line->total_tva = -19.6;
4910 $line->remise_percent = 0;
4911 $line->multicurrency_total_ht = -200;
4912 $line->multicurrency_total_ttc = -239.2;
4913 $line->multicurrency_total_tva = -39.2;
4914 } elseif ($xnbp == 3) {
4915 $prodid = mt_rand(1, $num_prods);
4916 $line->fk_product = $prodids[$prodid];
4917 $line->total_ht = 50;
4918 $line->total_ttc = 59.8;
4919 $line->total_tva = 9.8;
4920 $line->multicurrency_total_ht = 100;
4921 $line->multicurrency_total_ttc = 119.6;
4922 $line->multicurrency_total_tva = 19.6;
4923 $line->remise_percent = 50;
4926 $prodid = mt_rand(1, $num_prods);
4927 $line->fk_product = $prodids[$prodid];
4928 $line->total_ht = 100;
4929 $line->total_ttc = 119.6;
4930 $line->total_tva = 19.6;
4931 $line->multicurrency_total_ht = 200;
4932 $line->multicurrency_total_ttc = 239.2;
4933 $line->multicurrency_total_tva = 39.2;
4934 $line->remise_percent = 0;
4937 $this->lines[$xnbp] = $line;
4940 $this->total_ht += $line->total_ht;
4941 $this->total_tva += $line->total_tva;
4942 $this->total_ttc += $line->total_ttc;
4944 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4945 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4946 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4950 $this->revenuestamp = 0;
4954 $line->desc = $langs->trans(
"Description").
" (offered line)";
4956 $line->subprice = 100;
4957 $line->tva_tx = 19.6;
4958 $line->localtax1_tx = 0;
4959 $line->localtax2_tx = 0;
4960 $line->remise_percent = 100;
4961 $line->total_ht = 0;
4962 $line->total_ttc = 0;
4963 $line->total_tva = 0;
4964 $line->multicurrency_total_ht = 0;
4965 $line->multicurrency_total_ttc = 0;
4966 $line->multicurrency_total_tva = 0;
4967 $prodid = mt_rand(1, $num_prods);
4968 $line->fk_product = $prodids[$prodid];
4970 $this->lines[$xnbp] = $line;
4984 global $conf, $user;
4986 $this->nb = array();
4990 $sql =
"SELECT count(f.rowid) as nb";
4991 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4992 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
4993 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4994 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4995 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4998 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
5002 while ($obj = $this->
db->fetch_object(
$resql)) {
5003 $this->nb[
"invoices"] = $obj->nb;
5009 $this->error = $this->
db->error();
5035 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
5037 global $conf, $langs;
5039 $outputlangs->loadLangs(array(
"bills",
"products"));
5043 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5045 if (!empty($this->model_pdf)) {
5046 $modele = $this->model_pdf;
5047 } elseif (!empty($this->modelpdf)) {
5048 $modele = $this->modelpdf;
5049 } elseif (!empty($conf->global->$thisTypeConfName)) {
5050 $modele = $conf->global->$thisTypeConfName;
5051 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
5052 $modele = $conf->global->FACTURE_ADDON_PDF;
5056 $modelpath =
"core/modules/facture/doc/";
5058 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5068 $sql =
'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.
'facture as f';
5069 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5072 if ($this->
db->num_rows(
$resql) > 0) {
5073 $res = $this->
db->fetch_array(
$resql);
5074 $ref = $res[
'max(situation_cycle_ref)'];
5082 $this->error = $this->
db->lasterror();
5083 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5097 return ($this->situation_counter == 1);
5111 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5112 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5113 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5114 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5118 while ($row = $this->
db->fetch_object(
$resql)) {
5121 $situation->fetch($id);
5122 $res[] = $situation;
5125 $this->error = $this->
db->error();
5126 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5146 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5151 $this->errors[] = $this->
db->error();
5155 if (!$notrigger && empty($error)) {
5165 $this->
db->commit();
5168 foreach ($this->errors as $errmsg) {
5169 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5170 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5172 $this->
db->rollback();
5188 if (!empty($this->situation_cycle_ref)) {
5190 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5191 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5192 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5196 $res = $this->
db->fetch_array(
$resql);
5197 $last = $res[
'max(situation_counter)'];
5198 return ($last == $this->situation_counter);
5200 $this->error = $this->
db->lasterror();
5201 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5259 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5260 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5262 $totalpaid = floatval($totalpaid);
5264 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5265 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5267 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5290 $displayWarranty =
false;
5291 if (!empty($this->retained_warranty)) {
5292 $displayWarranty =
true;
5296 $displayWarranty =
false;
5297 if (!empty($this->situation_final)) {
5298 $displayWarranty =
true;
5301 $displayWarranty =
true;
5303 foreach ($this->lines as $i => $line) {
5304 if ($line->product_type < 2 && $line->situation_percent < 100) {
5305 $displayWarranty =
false;
5313 return $displayWarranty;
5323 if (empty($this->retained_warranty)) {
5327 $retainedWarrantyAmount = 0;
5331 $displayWarranty =
true;
5333 if (!empty($this->lines)) {
5334 foreach ($this->lines as $i => $line) {
5335 if ($line->product_type < 2 && $line->situation_percent < 100) {
5336 $displayWarranty =
false;
5342 if ($displayWarranty && !empty($this->situation_final)) {
5344 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5347 foreach ($TPreviousIncoice as &$fac) {
5348 $total2BillWT += $fac->total_ttc;
5350 $total2BillWT += $this->total_ttc;
5352 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5358 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5361 if ($rounding < 0) {
5362 $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5365 if ($rounding > 0) {
5366 return round($retainedWarrantyAmount, $rounding);
5369 return $retainedWarrantyAmount;
5380 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5382 if ($this->statut >= 0) {
5383 $fieldname =
'retained_warranty';
5384 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5385 $sql .=
" SET ".$fieldname.
" = ".((
float) $value);
5386 $sql .=
' WHERE rowid='.((int) $this->
id);
5388 if ($this->
db->query($sql)) {
5389 $this->retained_warranty = floatval($value);
5392 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5393 $this->error = $this->
db->error();
5397 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5398 $this->error =
'Status of the object is incompatible '.$this->statut;
5413 if (!$timestamp && $dateYmd) {
5414 $timestamp = $this->
db->jdate($dateYmd);
5418 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5419 if ($this->statut >= 0) {
5420 $fieldname =
'retained_warranty_date_limit';
5421 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5422 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5423 $sql .=
' WHERE rowid = '.((int) $this->
id);
5425 if ($this->
db->query($sql)) {
5426 $this->retained_warranty_date_limit = $timestamp;
5429 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5430 $this->error = $this->
db->error();
5434 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5435 $this->error =
'Status of the object is incompatible '.$this->statut;
5452 global $conf, $langs, $user;
5458 $errorsMsg = array();
5460 $langs->load(
"bills");
5463 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5473 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5474 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5475 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5486 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5487 if (!empty($paymentmode) && $paymentmode !=
'all') {
5488 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5490 $sql .=
" WHERE f.paye = 0";
5491 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5492 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5493 $sql .=
" AND f.entity IN (".getEntity(
'facture').
")";
5494 if (!empty($paymentmode) && $paymentmode !=
'all') {
5495 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5498 $sql .= $this->
db->order(
"date_lim_reglement",
"ASC");
5503 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5504 if (!empty($paymentmode) && $paymentmode !=
'all') {
5505 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5507 $this->output .=
'<br>';
5510 while ($obj = $this->
db->fetch_object(
$resql)) {
5513 $res = $tmpinvoice->fetch($obj->id);
5515 $tmpinvoice->fetch_thirdparty();
5517 $outputlangs =
new Translate(
'', $conf);
5518 if ($tmpinvoice->thirdparty->default_lang) {
5519 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5520 $outputlangs->loadLangs(array(
"main",
"bills"));
5522 $outputlangs = $langs;
5526 $arraymessage = $formmail->getEMailTemplate($this->
db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5527 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5528 $langs->load(
"errors");
5529 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5542 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5545 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5551 $res = $tmpinvoice->fetch_thirdparty();
5552 $recipient = $tmpinvoice->thirdparty;
5554 if (!empty($recipient->email)) {
5555 $to = $recipient->email;
5557 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for user.";
5561 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5566 $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
5568 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5572 if (!$error && $to) {
5576 $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
5578 $trackid =
'inv'.$tmpinvoice->id;
5579 $sendcontext =
'standard';
5582 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(),
'',
"", 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5585 if ($cMailFile->sendfile()) {
5589 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5594 $actioncomm->type_code =
'AC_OTH_AUTO';
5595 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5596 $actioncomm->contact_id = 0;
5598 $actioncomm->code =
'AC_EMAIL';
5599 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK';
5600 $actioncomm->note_private = $sendContent;
5601 $actioncomm->fk_project = $tmpinvoice->fk_project;
5602 $actioncomm->datep =
dol_now();
5603 $actioncomm->datef = $actioncomm->datep;
5604 $actioncomm->percentage = -1;
5605 $actioncomm->authorid = $user->id;
5606 $actioncomm->userownerid = $user->id;
5608 $actioncomm->email_msgid = $cMailFile->msgid;
5609 $actioncomm->email_from = $from;
5610 $actioncomm->email_sender =
'';
5611 $actioncomm->email_to = $to;
5615 $actioncomm->errors_to = $errors_to;
5619 $actioncomm->create($user);
5621 $errormesg = $cMailFile->error.
' : '.$to;
5625 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5630 $actioncomm->type_code =
'AC_OTH_AUTO';
5631 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5632 $actioncomm->contact_id = 0;
5634 $actioncomm->code =
'AC_EMAIL';
5635 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5636 $actioncomm->note_private = $errormesg;
5637 $actioncomm->fk_project = $tmpinvoice->fk_project;
5638 $actioncomm->datep =
dol_now();
5639 $actioncomm->datef = $actioncomm->datep;
5640 $actioncomm->percentage = -1;
5641 $actioncomm->authorid = $user->id;
5642 $actioncomm->userownerid = $user->id;
5644 $actioncomm->email_msgid = $cMailFile->msgid;
5645 $actioncomm->email_from = $from;
5646 $actioncomm->email_sender =
'';
5647 $actioncomm->email_to = $to;
5651 $actioncomm->errors_to = $errors_to;
5655 $actioncomm->create($user);
5658 $this->
db->commit();
5662 $errorsMsg[] = $errormesg;
5665 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
5675 $this->output .=
'Nb of emails sent : '.$nbMailSend;
5678 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg)) ? join(
', ', $errorsMsg) : $error;
5692 $sql =
"SELECT datef";
5693 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
5694 $sql .=
" WHERE type = " . (int) $this->
type ;
5695 $sql .=
" AND date_valid IS NOT NULL";
5696 $sql .=
" ORDER BY datef DESC LIMIT 1";
5698 $result = $this->
db->query($sql);
5701 if ($this->
db->num_rows($result)) {
5702 $obj = $this->
db->fetch_object($result);
5703 $last_date = $this->
db->jdate($obj->datef);
5704 $invoice_date = $this->date;
5706 $is_last_of_same_type = $invoice_date >= $last_date;
5707 if ($allow_validated_drafts) {
5708 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->
ref,
'PROV') && $this->status == self::STATUS_DRAFT);
5711 return array($is_last_of_same_type, $last_date);
5731 public $element =
'facturedet';
5736 public $table_element =
'facturedet';
5750 public $localtax1_type;
5751 public $localtax2_type;
5752 public $fk_remise_except;
5755 public $fk_fournprice;
5760 public $remise_percent;
5762 public $special_code;
5770 public $fk_code_ventilation = 0;
5775 public $skip_update_total;
5780 public $situation_percent;
5788 public $fk_multicurrency;
5789 public $multicurrency_code;
5790 public $multicurrency_subprice;
5791 public $multicurrency_total_ht;
5792 public $multicurrency_total_tva;
5793 public $multicurrency_total_ttc;
5803 $sql =
'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,';
5804 $sql .=
' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
5805 $sql .=
' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,';
5806 $sql .=
' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
5807 $sql .=
' fd.fk_code_ventilation,';
5808 $sql .=
' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
5809 $sql .=
' fd.situation_percent, fd.fk_prev_id,';
5810 $sql .=
' fd.multicurrency_subprice,';
5811 $sql .=
' fd.multicurrency_total_ht,';
5812 $sql .=
' fd.multicurrency_total_tva,';
5813 $sql .=
' fd.multicurrency_total_ttc,';
5814 $sql .=
' p.ref as product_ref, p.label as product_label, p.description as product_desc';
5815 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as fd';
5816 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON fd.fk_product = p.rowid';
5817 $sql .=
' WHERE fd.rowid = '.((int) $rowid);
5819 $result = $this->
db->query($sql);
5821 $objp = $this->
db->fetch_object($result);
5823 $this->
rowid = $objp->rowid;
5824 $this->
id = $objp->rowid;
5825 $this->fk_facture = $objp->fk_facture;
5826 $this->fk_parent_line = $objp->fk_parent_line;
5827 $this->label = $objp->custom_label;
5828 $this->desc = $objp->description;
5829 $this->qty = $objp->qty;
5830 $this->subprice = $objp->subprice;
5831 $this->ref_ext = $objp->ref_ext;
5832 $this->vat_src_code = $objp->vat_src_code;
5833 $this->tva_tx = $objp->tva_tx;
5834 $this->localtax1_tx = $objp->localtax1_tx;
5835 $this->localtax2_tx = $objp->localtax2_tx;
5836 $this->remise_percent = $objp->remise_percent;
5837 $this->fk_remise_except = $objp->fk_remise_except;
5838 $this->fk_product = $objp->fk_product;
5839 $this->product_type = $objp->product_type;
5840 $this->date_start = $this->
db->jdate($objp->date_start);
5841 $this->date_end = $this->
db->jdate($objp->date_end);
5842 $this->info_bits = $objp->info_bits;
5843 $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
5844 $this->special_code = $objp->special_code;
5845 $this->total_ht = $objp->total_ht;
5846 $this->total_tva = $objp->total_tva;
5847 $this->total_localtax1 = $objp->total_localtax1;
5848 $this->total_localtax2 = $objp->total_localtax2;
5849 $this->total_ttc = $objp->total_ttc;
5850 $this->fk_code_ventilation = $objp->fk_code_ventilation;
5851 $this->rang = $objp->rang;
5852 $this->fk_fournprice = $objp->fk_fournprice;
5853 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
5854 $this->pa_ht = $marginInfos[0];
5855 $this->marge_tx = $marginInfos[1];
5856 $this->marque_tx = $marginInfos[2];
5858 $this->
ref = $objp->product_ref;
5860 $this->product_ref = $objp->product_ref;
5861 $this->product_label = $objp->product_label;
5862 $this->product_desc = $objp->product_desc;
5864 $this->fk_unit = $objp->fk_unit;
5865 $this->fk_user_modif = $objp->fk_user_modif;
5866 $this->fk_user_author = $objp->fk_user_author;
5868 $this->situation_percent = $objp->situation_percent;
5869 $this->fk_prev_id = $objp->fk_prev_id;
5871 $this->multicurrency_subprice = $objp->multicurrency_subprice;
5872 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
5873 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
5874 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
5876 $this->
db->free($result);
5880 $this->error = $this->
db->lasterror();
5892 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
5894 global $langs, $user, $conf;
5898 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
5900 dol_syslog(get_class($this).
"::insert rang=".$this->rang, LOG_DEBUG);
5903 $this->desc = trim($this->desc);
5904 if (empty($this->tva_tx)) {
5907 if (empty($this->localtax1_tx)) {
5908 $this->localtax1_tx = 0;
5910 if (empty($this->localtax2_tx)) {
5911 $this->localtax2_tx = 0;
5913 if (empty($this->localtax1_type)) {
5914 $this->localtax1_type = 0;
5916 if (empty($this->localtax2_type)) {
5917 $this->localtax2_type = 0;
5919 if (empty($this->total_localtax1)) {
5920 $this->total_localtax1 = 0;
5922 if (empty($this->total_localtax2)) {
5923 $this->total_localtax2 = 0;
5925 if (empty($this->rang)) {
5928 if (empty($this->remise_percent)) {
5929 $this->remise_percent = 0;
5931 if (empty($this->info_bits)) {
5932 $this->info_bits = 0;
5934 if (empty($this->subprice)) {
5935 $this->subprice = 0;
5937 if (empty($this->ref_ext)) {
5938 $this->ref_ext =
'';
5940 if (empty($this->special_code)) {
5941 $this->special_code = 0;
5943 if (empty($this->fk_parent_line)) {
5944 $this->fk_parent_line = 0;
5946 if (empty($this->fk_prev_id)) {
5947 $this->fk_prev_id = 0;
5949 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
5950 $this->situation_percent = 100;
5953 if (empty($this->pa_ht)) {
5956 if (empty($this->multicurrency_subprice)) {
5957 $this->multicurrency_subprice = 0;
5959 if (empty($this->multicurrency_total_ht)) {
5960 $this->multicurrency_total_ht = 0;
5962 if (empty($this->multicurrency_total_tva)) {
5963 $this->multicurrency_total_tva = 0;
5965 if (empty($this->multicurrency_total_ttc)) {
5966 $this->multicurrency_total_ttc = 0;
5970 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
5971 if (($result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
5974 $this->pa_ht = $result;
5979 if ($this->product_type < 0) {
5980 $this->error =
'ErrorProductTypeMustBe0orMore';
5983 if (!empty($this->fk_product) && $this->fk_product > 0) {
5987 $this->error =
'ErrorProductIdDoesNotExists';
5988 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
5996 $sql =
'INSERT INTO '.MAIN_DB_PREFIX.
'facturedet';
5997 $sql .=
' (fk_facture, fk_parent_line, label, description, qty,';
5998 $sql .=
' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
5999 $sql .=
' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6000 $sql .=
' date_start, date_end, fk_code_ventilation, ';
6001 $sql .=
' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6002 $sql .=
' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6003 $sql .=
' situation_percent, fk_prev_id,';
6004 $sql .=
' fk_unit, fk_user_author, fk_user_modif,';
6005 $sql .=
' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
6007 $sql .=
" VALUES (".$this->fk_facture.
",";
6008 $sql .=
" ".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null").
",";
6009 $sql .=
" ".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null").
",";
6010 $sql .=
" '".$this->db->escape($this->desc).
"',";
6011 $sql .=
" ".price2num($this->qty).
",";
6012 $sql .=
" ".(empty($this->vat_src_code) ?
"''" :
"'".$this->db->escape($this->vat_src_code).
"'").
",";
6013 $sql .=
" ".price2num($this->tva_tx).
",";
6014 $sql .=
" ".price2num($this->localtax1_tx).
",";
6015 $sql .=
" ".price2num($this->localtax2_tx).
",";
6016 $sql .=
" '".$this->db->escape($this->localtax1_type).
"',";
6017 $sql .=
" '".$this->db->escape($this->localtax2_type).
"',";
6018 $sql .=
' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product :
"null").
',';
6019 $sql .=
" ".((int) $this->product_type).
",";
6020 $sql .=
" ".price2num($this->remise_percent).
",";
6021 $sql .=
" ".price2num($this->subprice).
",";
6022 $sql .=
" '".$this->db->escape($this->ref_ext).
"',";
6023 $sql .=
' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except :
"null").
',';
6024 $sql .=
" ".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null").
",";
6025 $sql .=
" ".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null").
",";
6026 $sql .=
' '.((int) $this->fk_code_ventilation).
',';
6027 $sql .=
' '.((int) $this->rang).
',';
6028 $sql .=
' '.((int) $this->special_code).
',';
6029 $sql .=
' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice :
"null").
',';
6030 $sql .=
' '.price2num($this->pa_ht).
',';
6031 $sql .=
" '".$this->db->escape($this->info_bits).
"',";
6032 $sql .=
" ".price2num($this->total_ht).
",";
6033 $sql .=
" ".price2num($this->total_tva).
",";
6034 $sql .=
" ".price2num($this->total_ttc).
",";
6035 $sql .=
" ".price2num($this->total_localtax1).
",";
6036 $sql .=
" ".price2num($this->total_localtax2);
6037 $sql .=
", ".((float) $this->situation_percent);
6038 $sql .=
", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id :
"null");
6039 $sql .=
", ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6040 $sql .=
", ".((int) $user->id);
6041 $sql .=
", ".((int) $user->id);
6042 $sql .=
", ".(int) $this->fk_multicurrency;
6043 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
6044 $sql .=
", ".price2num($this->multicurrency_subprice);
6045 $sql .=
", ".price2num($this->multicurrency_total_ht);
6046 $sql .=
", ".price2num($this->multicurrency_total_tva);
6047 $sql .=
", ".price2num($this->multicurrency_total_ttc);
6050 dol_syslog(get_class($this).
"::insert", LOG_DEBUG);
6053 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facturedet');
6054 $this->
rowid = $this->id;
6065 if ($this->fk_remise_except) {
6067 $result = $discount->fetch($this->fk_remise_except);
6072 if ($discount->fk_facture_line > 0) {
6073 if (empty($noerrorifdiscountalreadylinked)) {
6074 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed", $discount->id);
6075 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6076 $this->
db->rollback();
6080 $result = $discount->link_to_invoice($this->
rowid, 0);
6082 $this->error = $discount->error;
6083 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6084 $this->
db->rollback();
6089 $this->error = $langs->trans(
"ErrorADiscountThatHasBeenRemovedIsIncluded");
6090 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6091 $this->
db->rollback();
6095 $this->error = $discount->error;
6096 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6097 $this->
db->rollback();
6104 $result = $this->
call_trigger(
'LINEBILL_INSERT', $user);
6106 $this->
db->rollback();
6112 $this->
db->commit();
6115 $this->error = $this->
db->lasterror();
6116 $this->
db->rollback();
6128 public function update($user =
'', $notrigger = 0)
6130 global $user, $conf;
6134 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6137 $this->desc = trim($this->desc);
6138 if (empty($this->ref_ext)) {
6139 $this->ref_ext =
'';
6141 if (empty($this->tva_tx)) {
6144 if (empty($this->localtax1_tx)) {
6145 $this->localtax1_tx = 0;
6147 if (empty($this->localtax2_tx)) {
6148 $this->localtax2_tx = 0;
6150 if (empty($this->localtax1_type)) {
6151 $this->localtax1_type = 0;
6153 if (empty($this->localtax2_type)) {
6154 $this->localtax2_type = 0;
6156 if (empty($this->total_localtax1)) {
6157 $this->total_localtax1 = 0;
6159 if (empty($this->total_localtax2)) {
6160 $this->total_localtax2 = 0;
6162 if (empty($this->remise_percent)) {
6163 $this->remise_percent = 0;
6165 if (empty($this->info_bits)) {
6166 $this->info_bits = 0;
6168 if (empty($this->special_code)) {
6169 $this->special_code = 0;
6171 if (empty($this->product_type)) {
6172 $this->product_type = 0;
6174 if (empty($this->fk_parent_line)) {
6175 $this->fk_parent_line = 0;
6177 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6178 $this->situation_percent = 100;
6180 if (empty($this->pa_ht)) {
6184 if (empty($this->multicurrency_subprice)) {
6185 $this->multicurrency_subprice = 0;
6187 if (empty($this->multicurrency_total_ht)) {
6188 $this->multicurrency_total_ht = 0;
6190 if (empty($this->multicurrency_total_tva)) {
6191 $this->multicurrency_total_tva = 0;
6193 if (empty($this->multicurrency_total_ttc)) {
6194 $this->multicurrency_total_ttc = 0;
6198 if ($this->product_type < 0) {
6203 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6205 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6209 $this->pa_ht = $result;
6216 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6217 $sql .=
" description='".$this->db->escape($this->desc).
"'";
6218 $sql .=
", ref_ext='".$this->db->escape($this->ref_ext).
"'";
6219 $sql .=
", label=".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null");
6220 $sql .=
", subprice=".price2num($this->subprice);
6221 $sql .=
", remise_percent=".price2num($this->remise_percent);
6222 if ($this->fk_remise_except) {
6223 $sql .=
", fk_remise_except=".$this->fk_remise_except;
6225 $sql .=
", fk_remise_except=null";
6227 $sql .=
", vat_src_code = '".(empty($this->vat_src_code) ?
'' : $this->
db->escape($this->vat_src_code)).
"'";
6228 $sql .=
", tva_tx=".price2num($this->tva_tx);
6229 $sql .=
", localtax1_tx=".price2num($this->localtax1_tx);
6230 $sql .=
", localtax2_tx=".price2num($this->localtax2_tx);
6231 $sql .=
", localtax1_type='".$this->db->escape($this->localtax1_type).
"'";
6232 $sql .=
", localtax2_type='".$this->db->escape($this->localtax2_type).
"'";
6233 $sql .=
", qty=".price2num($this->qty);
6234 $sql .=
", date_start=".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null");
6235 $sql .=
", date_end=".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null");
6236 $sql .=
", product_type=".$this->product_type;
6237 $sql .=
", info_bits='".$this->db->escape($this->info_bits).
"'";
6238 $sql .=
", special_code='".$this->db->escape($this->special_code).
"'";
6239 if (empty($this->skip_update_total)) {
6240 $sql .=
", total_ht=".price2num($this->total_ht);
6241 $sql .=
", total_tva=".price2num($this->total_tva);
6242 $sql .=
", total_ttc=".price2num($this->total_ttc);
6243 $sql .=
", total_localtax1=".price2num($this->total_localtax1);
6244 $sql .=
", total_localtax2=".price2num($this->total_localtax2);
6246 $sql .=
", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ?
"'".$this->db->escape($this->fk_fournprice).
"'" :
"null");
6247 $sql .=
", buy_price_ht=".(($this->pa_ht || $this->pa_ht === 0 || $this->pa_ht ===
'0') ?
price2num($this->pa_ht) :
"null");
6248 $sql .=
", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null");
6249 if (!empty($this->rang)) {
6250 $sql .=
", rang=".((int) $this->rang);
6252 $sql .=
", situation_percent = ".((float) $this->situation_percent);
6253 $sql .=
", fk_unit = ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6254 $sql .=
", fk_user_modif = ".((int) $user->id);
6257 $sql .=
", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6258 $sql .=
", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6259 $sql .=
", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6260 $sql .=
", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6262 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6264 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
6268 $this->
id = $this->rowid;
6275 if (!$error && !$notrigger) {
6277 $result = $this->
call_trigger(
'LINEBILL_MODIFY', $user);
6279 $this->
db->rollback();
6284 $this->
db->commit();
6287 $this->error = $this->
db->error();
6288 $this->
db->rollback();
6300 public function delete($tmpuser = null, $notrigger =
false)
6307 if (empty($notrigger)) {
6308 $result = $this->
call_trigger(
'LINEBILL_DELETE', $user);
6310 $this->
db->rollback();
6319 $this->
db->rollback();
6323 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->
rowid);
6325 if ($this->
db->query($sql)) {
6326 $this->
db->commit();
6329 $this->error = $this->
db->error().
" sql=".$sql;
6330 $this->
db->rollback();
6346 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6349 if (empty($this->total_localtax1)) {
6350 $this->total_localtax1 = 0;
6352 if (empty($this->total_localtax2)) {
6353 $this->total_localtax2 = 0;
6357 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6358 $sql .=
" total_ht=".price2num($this->total_ht).
"";
6359 $sql .=
",total_tva=".price2num($this->total_tva).
"";
6360 $sql .=
",total_localtax1=".price2num($this->total_localtax1).
"";
6361 $sql .=
",total_localtax2=".price2num($this->total_localtax2).
"";
6362 $sql .=
",total_ttc=".price2num($this->total_ttc).
"";
6363 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6365 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6369 $this->
db->commit();
6372 $this->error = $this->
db->error();
6373 $this->
db->rollback();
6390 global $invoicecache;
6391 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6395 if (!isset($invoicecache[$invoiceid])) {
6396 $invoicecache[$invoiceid] =
new Facture($this->
db);
6397 $invoicecache[$invoiceid]->fetch($invoiceid);
6403 $sql =
"SELECT situation_percent FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->fk_prev_id);
6406 $res = $this->
db->fetch_array(
$resql);
6408 $returnPercent = floatval($res[
'situation_percent']);
6410 if ($include_credit_note) {
6411 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6412 $sql .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6413 $sql .=
" WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6414 $sql .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6415 $sql .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6417 $res = $this->
db->query($sql);
6419 while ($obj = $this->
db->fetch_object($res)) {
6420 $returnPercent = $returnPercent + floatval($obj->situation_percent);
6427 return $returnPercent;
6429 $this->error = $this->
db->error();
6430 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6431 $this->
db->rollback();
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield= 'rowid')
Return the value of a filed into a dictionary for the record $id.
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Class to manage stock movements.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode= 'all', $template= '')
Send reminders by emails for ivoices that are due CAN BE A CRON TASK.
const TYPE_STANDARD
Standard invoice.
getRetainedWarrantyAmount($rounding=-1)
static isExistingObject($element, $id, $ref= '', $ref_ext= '')
Check an object id/ref exists If you don't need/want to instantiate object and just need to know if o...
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm= 'auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
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.
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
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=0, $situation_percent=100, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext= '', $rang=0)
Update a detail line.
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
deleteline($rowid)
Delete line in database.
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
Class to manage agenda events (actions)
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...
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
fetch($rowid)
Load invoice line from database.
setRetainedWarranty($value)
Change the retained warranty.
$conf db
API class for accounts.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getLinesArray()
Create an array of invoice lines.
Class to manage products or services.
dol_now($mode= 'auto')
Return date for now.
line_order($renum=false, $rowidorder= 'ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
setRetainedWarrantyDateLimit($timestamp, $dateYmd=false)
Change the retained_warranty_date_limit.
deleteObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $rowid= '', $f_user=null, $notrigger=0)
Delete all links between an object $this.
dol_delete_preview($object)
Delete all preview files linked to object instance.
Class to manage invoice templates.
insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
Insert line into database.
static commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
delete_linked_contact($source= '', $code= '')
Delete all links between an object $this and all its contacts.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller= '', $localtaxes_array= '', $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code= '')
Calculate totals (net, vat, ...) of a line.
Class to manage Dolibarr users.
const TYPE_REPLACEMENT
Replacement invoice.
Class to manage Dolibarr database access.
add_contact($fk_socpeople, $type_contact, $source= 'external', $notrigger=0)
Add a link between element $this->element and a contact.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this->lines.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
set_unpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
__construct(DoliDB $db)
Constructor.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
get_prev_sits()
Returns an array containing the previous situations as Facture objects.
fetch($rowid, $ref= '', $ref_ext= '', $notused= '', $fetch_situation=false)
Get object from database.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
const TYPE_PROFORMA
Proforma invoice (should not be used.
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...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Parent class of all other business classes for details of elements (invoices, contracts, proposals, orders, ...)
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
load_state_board()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
const TYPE_SITUATION
Situation invoice.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
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...
const TYPE_CREDIT_NOTE
Credit note invoice.
getNextNumRef($soc, $mode= 'next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
updatePriceNextInvoice(&$langs)
Update price of next invoice.
static getIdAndTxFromCode($dbs, $code, $date_document= '')
Get id and rate of currency from code.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form...
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...
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
Class to manage third parties objects (customers, suppliers, prospects...)
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
const STATUS_VALIDATED
Validated (need to be paid)
getSommePaiement($multicurrency=0)
Return amount of payments already done.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is '...
create(User $user, $notrigger=0, $forceduedate=0)
Create invoice in database.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
deleteEcmFiles($mode=0)
Delete related files of object in database.
dol_get_next_month($month, $year)
Return next month.
$pos_source
key of pos source ('0', '1', ...)
Class to manage shipments.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext,$replyto); $mailfile->sendfile();.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
const STATUS_DRAFT
Draft status.
set_remise_absolue($user, $remise, $notrigger=0)
Set absolute discount.
update(User $user, $notrigger=0)
Update database.
dol_getdate($timestamp, $fast=false, $forcetimezone= '')
Return an array with locale date info.
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). ...
$module_source
key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos', ...)
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
set_paid($user, $close_code= '', $close_note= '')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1 or partialy (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0.
deleteExtraFields()
Delete all extra fields values for the current object.
Class to manage translations.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
const STATUS_CLOSED
Classified paid.
getNomUrl($withpicto=0, $option= '', $max=0, $short=0, $moretitle= '', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target= '')
Return clicable link of object (with eventually picto)
static getIdFromCode($dbs, $code)
Get id of currency from code.
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.
setCanceled($user, $close_code= '', $close_note= '')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
$fk_fac_rec_source
id of template invoice when generated from a template invoice
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) ...
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...
setUnpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
if(isModEnabled('facture')&&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur')&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)&&$user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice')&&$user->rights->supplier_invoice->lire)) if(isModEnabled('don')&&!empty($user->rights->don->lire)) if(isModEnabled('tax')&&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture')&&isModEnabled('commande')&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Superclass for invoices classes.
const STATUS_ABANDONED
Classified abandoned and no payment done.
getIdBillingContact()
Retourne id des contacts clients de facturation.
const TYPE_DEPOSIT
Deposit invoice.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
div float
Buy price without taxes.
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
hasDelay()
Is the customer invoice delayed?
call_trigger($triggerName, $user)
Call trigger based on this instance.
setDraft($user, $idwarehouse=-1)
Set draft status.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add objects linked in llx_element_element.
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
getIdShippingContact()
Retourne id des contacts clients de livraison.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Class to manage absolute discounts.
info($id)
Load miscellaneous information for tab "Info".
$fk_facture_source
id of source invoice if replacement invoice or credit note
$fk_parent_line
Id parent line.
$paye
1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code) ...
isModEnabled($module)
Is Dolibarr module enabled.
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. ...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
Class to manage invoices.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
initAsSpecimen($option= '')
Initialise an instance with random values.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
is_first()
Checks if the invoice is the first of a cycle.
addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start= '', $date_end= '', $ventil=0, $info_bits=0, $fk_remise_except= '', $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=0, $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).
liste_array($shortlist=0, $draft=0, $excluser= '', $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.
update_price($exclspec=0, $roundingadjust= 'none', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines)...
$fk_facture
From llx_facturedet Id facture.
setPaid($user, $close_code= '', $close_note= '')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1 or partially (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0.
update_total()
Update DB line fields total_xxx Used by migration.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
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.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
Class to manage predefined suppliers products.
get_prev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of the previous line.
Class to manage invoice lines.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
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...
Class to manage warehouses.
update($user= '', $notrigger=0)
Update line into database.
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed...
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid