43 require_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;
165 public $remise_absolue;
166 public $remise_percent;
169 public $total_localtax1;
170 public $total_localtax2;
172 public $revenuestamp;
202 public $linked_objects = array();
204 public $date_lim_reglement;
205 public $cond_reglement_code;
206 public $mode_reglement_code;
216 public $lines = array();
219 public $extraparams = array();
223 public $date_pointoftax;
229 public $fk_multicurrency;
231 public $multicurrency_code;
232 public $multicurrency_tx;
233 public $multicurrency_total_ht;
234 public $multicurrency_total_tva;
235 public $multicurrency_total_ttc;
240 public $situation_cycle_ref;
245 public $situation_counter;
250 public $situation_final;
255 public $tab_previous_situation_invoice = array();
260 public $tab_next_situation_invoice = array();
267 public $retained_warranty;
272 public $retained_warranty_date_limit;
277 public $retained_warranty_fk_cond_reglement;
308 public $fields = array(
309 'rowid' =>array(
'type'=>
'integer',
'label'=>
'TechnicalID',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>1),
310 'ref' =>array(
'type'=>
'varchar(30)',
'label'=>
'Ref',
'enabled'=>1,
'visible'=>1,
'notnull'=>1,
'showoncombobox'=>1,
'position'=>5),
311 'entity' =>array(
'type'=>
'integer',
'label'=>
'Entity',
'default'=>1,
'enabled'=>1,
'visible'=>-2,
'notnull'=>1,
'position'=>20,
'index'=>1),
312 'ref_client' =>array(
'type'=>
'varchar(255)',
'label'=>
'RefCustomer',
'enabled'=>1,
'visible'=>-1,
'position'=>10),
313 'ref_ext' =>array(
'type'=>
'varchar(255)',
'label'=>
'Ref ext',
'enabled'=>1,
'visible'=>0,
'position'=>12),
314 'type' =>array(
'type'=>
'smallint(6)',
'label'=>
'Type',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>15),
316 'fk_soc' =>array(
'type'=>
'integer:Societe:societe/class/societe.class.php',
'label'=>
'ThirdParty',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>50),
317 'datef' =>array(
'type'=>
'date',
'label'=>
'DateInvoice',
'enabled'=>1,
'visible'=>1,
'position'=>20),
318 'date_valid' =>array(
'type'=>
'date',
'label'=>
'DateValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>22),
319 'date_lim_reglement' =>array(
'type'=>
'date',
'label'=>
'DateDue',
'enabled'=>1,
'visible'=>1,
'position'=>25),
320 'date_closing' =>array(
'type'=>
'datetime',
'label'=>
'Date closing',
'enabled'=>1,
'visible'=>-1,
'position'=>30),
321 'paye' =>array(
'type'=>
'smallint(6)',
'label'=>
'InvoicePaidCompletely',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>80),
323 'remise_percent' =>array(
'type'=>
'double',
'label'=>
'RelativeDiscount',
'enabled'=>1,
'visible'=>-1,
'position'=>90),
324 'remise_absolue' =>array(
'type'=>
'double',
'label'=>
'CustomerRelativeDiscount',
'enabled'=>1,
'visible'=>-1,
'position'=>91),
326 'close_code' =>array(
'type'=>
'varchar(16)',
'label'=>
'EarlyClosingReason',
'enabled'=>1,
'visible'=>-1,
'position'=>92),
327 'close_note' =>array(
'type'=>
'varchar(128)',
'label'=>
'EarlyClosingComment',
'enabled'=>1,
'visible'=>-1,
'position'=>93),
328 'total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountHT',
'enabled'=>1,
'visible'=>1,
'position'=>95,
'isameasure'=>1),
329 'total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountVAT',
'enabled'=>1,
'visible'=>-1,
'position'=>100,
'isameasure'=>1),
330 'localtax1' =>array(
'type'=>
'double(24,8)',
'label'=>
'LT1',
'enabled'=>1,
'visible'=>-1,
'position'=>110,
'isameasure'=>1),
331 'localtax2' =>array(
'type'=>
'double(24,8)',
'label'=>
'LT2',
'enabled'=>1,
'visible'=>-1,
'position'=>120,
'isameasure'=>1),
332 'revenuestamp' =>array(
'type'=>
'double(24,8)',
'label'=>
'RevenueStamp',
'enabled'=>1,
'visible'=>-1,
'position'=>115,
'isameasure'=>1),
333 'total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountTTC',
'enabled'=>1,
'visible'=>1,
'position'=>130,
'isameasure'=>1),
334 'fk_facture_source' =>array(
'type'=>
'integer',
'label'=>
'SourceInvoice',
'enabled'=>1,
'visible'=>-1,
'position'=>170),
335 'fk_projet' =>array(
'type'=>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label'=>
'Project',
'enabled'=>1,
'visible'=>-1,
'position'=>175),
336 'fk_account' =>array(
'type'=>
'integer',
'label'=>
'Fk account',
'enabled'=>1,
'visible'=>-1,
'position'=>180),
337 'fk_currency' =>array(
'type'=>
'varchar(3)',
'label'=>
'CurrencyCode',
'enabled'=>1,
'visible'=>-1,
'position'=>185),
338 'fk_cond_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentTerm',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>190),
339 'fk_mode_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentMode',
'enabled'=>1,
'visible'=>-1,
'position'=>195),
340 'note_private' =>array(
'type'=>
'text',
'label'=>
'NotePrivate',
'enabled'=>1,
'visible'=>0,
'position'=>205),
341 'note_public' =>array(
'type'=>
'text',
'label'=>
'NotePublic',
'enabled'=>1,
'visible'=>0,
'position'=>210),
342 'model_pdf' =>array(
'type'=>
'varchar(255)',
'label'=>
'Model pdf',
'enabled'=>1,
'visible'=>0,
'position'=>215),
343 'extraparams' =>array(
'type'=>
'varchar(255)',
'label'=>
'Extraparams',
'enabled'=>1,
'visible'=>-1,
'position'=>225),
344 'situation_cycle_ref' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation cycle ref',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>230),
345 'situation_counter' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation counter',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>235),
346 'situation_final' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation final',
'enabled'=>
'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1',
'visible'=>-1,
'position'=>240),
347 'retained_warranty' =>array(
'type'=>
'double',
'label'=>
'Retained warranty',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>245),
348 'retained_warranty_date_limit' =>array(
'type'=>
'date',
'label'=>
'Retained warranty date limit',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>250),
349 '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),
350 'fk_incoterms' =>array(
'type'=>
'integer',
'label'=>
'IncotermCode',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>260),
351 'location_incoterms' =>array(
'type'=>
'varchar(255)',
'label'=>
'IncotermLabel',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>265),
352 'date_pointoftax' =>array(
'type'=>
'date',
'label'=>
'DatePointOfTax',
'enabled'=>
'$conf->global->INVOICE_POINTOFTAX_DATE',
'visible'=>-1,
'position'=>270),
353 'fk_multicurrency' =>array(
'type'=>
'integer',
'label'=>
'MulticurrencyID',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>275),
354 'multicurrency_code' =>array(
'type'=>
'varchar(255)',
'label'=>
'Currency',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>280),
355 'multicurrency_tx' =>array(
'type'=>
'double(24,8)',
'label'=>
'CurrencyRate',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>285,
'isameasure'=>1),
356 'multicurrency_total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountHT',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>290,
'isameasure'=>1),
357 'multicurrency_total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountVAT',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>291,
'isameasure'=>1),
358 'multicurrency_total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountTTC',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>292,
'isameasure'=>1),
359 'fk_fac_rec_source' =>array(
'type'=>
'integer',
'label'=>
'RecurringInvoiceSource',
'enabled'=>1,
'visible'=>-1,
'position'=>305),
360 'last_main_doc' =>array(
'type'=>
'varchar(255)',
'label'=>
'LastMainDoc',
'enabled'=>1,
'visible'=>-1,
'position'=>310),
361 'module_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSModule',
'enabled'=>1,
'visible'=>-1,
'position'=>315),
362 'pos_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSTerminal',
'enabled'=>1,
'visible'=>-1,
'position'=>320),
363 'datec' =>array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'enabled'=>1,
'visible'=>-1,
'position'=>500),
364 'tms' =>array(
'type'=>
'timestamp',
'label'=>
'DateModificationShort',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>502),
365 'fk_user_author' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'enabled'=>1,
'visible'=>-1,
'position'=>506),
366 'fk_user_modif' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'enabled'=>1,
'visible'=>-1,
'notnull'=>-1,
'position'=>508),
367 'fk_user_valid' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>510),
368 'fk_user_closing' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserClosing',
'enabled'=>1,
'visible'=>-1,
'position'=>512),
369 'import_key' =>array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'enabled'=>1,
'visible'=>-2,
'position'=>900),
370 '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')),
432 const CLOSECODE_DISCOUNTVAT =
'discount_vat';
433 const CLOSECODE_BADDEBT =
'badcustomer';
434 const CLOSECODE_BANKCHARGE =
'bankcharge';
435 const CLOSECODE_OTHER =
'other';
437 const CLOSECODE_ABANDONED =
'abandon';
438 const CLOSECODE_REPLACED =
'replaced';
461 public function create(
User $user, $notrigger = 0, $forceduedate = 0)
463 global $langs, $conf, $mysoc, $hookmanager;
467 if (empty($this->
type)) {
470 $this->ref_client = trim($this->ref_client);
471 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
472 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
473 $this->note_public = trim($this->note_public);
474 if (!$this->cond_reglement_id) {
475 $this->cond_reglement_id = 0;
477 if (!$this->mode_reglement_id) {
478 $this->mode_reglement_id = 0;
480 $this->brouillon = 1;
484 if (!empty($this->multicurrency_code)) {
486 if (empty($this->multicurrency_tx)) {
494 $this->fk_multicurrency = 0;
496 if (empty($this->fk_multicurrency)) {
497 $this->multicurrency_code = $conf->currency;
498 $this->fk_multicurrency = 0;
499 $this->multicurrency_tx = 1;
502 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
505 if (empty($this->date)) {
506 $this->error =
"Try to create an invoice with an empty parameter (date)";
507 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
511 $result = $soc->fetch($this->socid);
513 $this->error =
"Failed to fetch company: ".$soc->error;
514 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
519 $this->date_creation = $now;
523 $originaldatewhen =
null;
524 $nextdatewhen =
null;
525 $previousdaynextdatewhen =
null;
528 if ($this->fac_rec > 0) {
529 $this->fk_fac_rec_source = $this->fac_rec;
531 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
533 $result = $_facrec->fetch($this->fac_rec);
534 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
537 $originaldatewhen = $_facrec->date_when;
538 $nextdatewhen =
null; $previousdaynextdatewhen =
null;
539 if ($originaldatewhen) {
540 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
544 if (!empty($_facrec->frequency)) {
545 $this->socid = $_facrec->socid;
547 $this->entity = $_facrec->entity;
550 $this->fk_project =
GETPOST(
'projectid',
'int') > 0 ? ((int)
GETPOST(
'projectid',
'int')) : $_facrec->fk_project;
551 $this->note_public =
GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
552 $this->note_private =
GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
553 $this->model_pdf =
GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
554 $this->cond_reglement_id =
GETPOST(
'cond_reglement_id',
'int') > 0 ? ((int)
GETPOST(
'cond_reglement_id',
'int')) : $_facrec->cond_reglement_id;
555 $this->mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int') > 0 ? ((int)
GETPOST(
'mode_reglement_id',
'int')) : $_facrec->mode_reglement_id;
556 $this->fk_account =
GETPOST(
'fk_account') > 0 ? ((int)
GETPOST(
'fk_account')) : $_facrec->fk_account;
559 $this->total_ht = $_facrec->total_ht;
560 $this->total_ttc = $_facrec->total_ttc;
563 $this->remise_absolue = $_facrec->remise_absolue;
564 $this->remise_percent = $_facrec->remise_percent;
565 $this->fk_incoterms = $_facrec->fk_incoterms;
566 $this->location_incoterms = $_facrec->location_incoterms;
572 $this->ref_client = trim($this->ref_client);
573 $this->ref_customer = trim($this->ref_customer);
574 $this->note_public = trim($this->note_public);
575 $this->note_private = trim($this->note_private);
576 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
578 $this->array_options = $_facrec->array_options;
580 if (!$this->mode_reglement_id) {
581 $this->mode_reglement_id = 0;
583 $this->brouillon = 1;
587 $this->linked_objects = $_facrec->linkedObjectsIds;
592 if ($_facrec->frequency > 0) {
593 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
594 if (empty($_facrec->date_when)) {
595 $_facrec->date_when = $now;
597 $next_date = $_facrec->getNextDate();
598 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
600 $result = $_facrec->setNextDate($next_date, 1);
604 $outputlangs = $langs;
607 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
608 $newlang = $this->thirdparty->default_lang;
610 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
611 $newlang = $this->default_lang;
613 if (!empty($newlang)) {
615 $outputlangs->setDefaultLang($newlang);
621 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
624 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
627 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
630 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
631 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
632 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
633 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
634 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
645 if (empty($forceduedate)) {
651 $this->date_lim_reglement = $duedate;
653 $this->date_lim_reglement = $forceduedate;
657 $socid = $this->socid;
659 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
666 $sql .=
", remise_absolue";
667 $sql .=
", remise_percent";
669 $sql .=
", date_pointoftax";
670 $sql .=
", note_private";
671 $sql .=
", note_public";
672 $sql .=
", ref_client";
673 $sql .=
", fk_account";
674 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
675 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
676 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
677 $sql .=
", fk_incoterms, location_incoterms";
678 $sql .=
", fk_multicurrency";
679 $sql .=
", multicurrency_code";
680 $sql .=
", multicurrency_tx";
681 $sql .=
", retained_warranty";
682 $sql .=
", retained_warranty_date_limit";
683 $sql .=
", retained_warranty_fk_cond_reglement";
687 $sql .=
", ".setEntity($this);
688 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
689 $sql .=
", '".$this->db->escape($this->
type).
"'";
690 $sql .=
", ".((int) $socid);
691 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
692 $sql .=
", ".($this->remise_absolue > 0 ? $this->remise_absolue :
'NULL');
693 $sql .=
", ".($this->remise_percent > 0 ? $this->remise_percent :
'NULL');
694 $sql .=
", '".$this->db->idate($this->date).
"'";
695 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
696 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
697 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
698 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
699 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
700 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
701 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape($this->pos_source).
"'" :
"null");
702 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape($this->fk_fac_rec_source).
"'" :
"null");
703 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape($this->fk_facture_source).
"'" :
"null");
704 $sql .=
", ".($user->id > 0 ? (int) $user->id :
"null");
705 $sql .=
", ".($this->fk_project ? $this->fk_project :
"null");
706 $sql .=
", ".((int) $this->cond_reglement_id);
707 $sql .=
", ".((int) $this->mode_reglement_id);
708 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
709 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
710 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape($this->situation_cycle_ref).
"'" :
"null");
711 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape($this->situation_counter).
"'" :
"null");
712 $sql .=
", ".($this->situation_final ? $this->situation_final : 0);
713 $sql .=
", ".(int) $this->fk_incoterms;
714 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
715 $sql .=
", ".(int) $this->fk_multicurrency;
716 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
717 $sql .=
", ".(double) $this->multicurrency_tx;
718 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty));
719 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
720 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
725 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facture');
728 $this->
ref =
'(PROV'.$this->id.
')';
729 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->
db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
736 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
737 $this->linked_objects = $this->linkedObjectsIds;
741 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
742 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
743 if (is_array($tmp_origin_id)) {
744 foreach ($tmp_origin_id as $origin_id) {
747 $this->error = $this->
db->lasterror();
753 $origin_id = $tmp_origin_id;
756 $this->error = $this->
db->lasterror();
764 if (!$error && $this->
id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) {
765 $originforcontact = $this->origin;
766 $originidforcontact = $this->origin_id;
767 if ($originforcontact ==
'shipping') {
768 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
770 $exp->fetch($this->origin_id);
771 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
772 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
773 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
774 $originforcontact =
'commande';
775 if (is_object($value)) {
776 $originidforcontact = $value->id;
778 $originidforcontact = $value;
785 $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";
786 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->
db->escape($originforcontact).
"'";
788 $resqlcontact = $this->
db->query($sqlcontact);
790 while ($objcontact = $this->
db->fetch_object($resqlcontact)) {
792 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
802 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
805 dol_syslog(
"There is ".count($this->lines).
" lines that are invoice lines objects");
806 foreach ($this->lines as $i => $val) {
807 $newinvoiceline = $this->lines[$i];
809 $newinvoiceline->context = $this->context;
811 $newinvoiceline->fk_facture = $this->id;
813 $newinvoiceline->origin = $this->lines[$i]->element;
814 $newinvoiceline->origin_id = $this->lines[$i]->id;
817 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
818 $newinvoiceline->date_start = $originaldatewhen;
820 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
821 $newinvoiceline->date_end = $previousdaynextdatewhen;
826 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
831 $vatrate = $newinvoiceline->tva_tx;
832 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', $vatrate)) $vatrate.=
' ('.$newinvoiceline->vat_src_code.
')';
834 $newinvoiceline->fk_parent_line = $fk_parent_line;
838 $discount->fetch($newinvoiceline->fk_remise_except);
840 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
841 $newinvoiceline->fk_remise_except = $discountId;
845 $newinvoiceline->desc,
846 $newinvoiceline->subprice,
847 $newinvoiceline->qty,
849 $newinvoiceline->localtax1_tx,
850 $newinvoiceline->localtax2_tx,
851 $newinvoiceline->fk_product,
852 $newinvoiceline->remise_percent,
853 $newinvoiceline->date_start,
854 $newinvoiceline->date_end,
855 $newinvoiceline->fk_code_ventilation,
856 $newinvoiceline->info_bits,
857 $newinvoiceline->fk_remise_except,
860 $newinvoiceline->product_type,
861 $newinvoiceline->rang,
862 $newinvoiceline->special_code,
863 $newinvoiceline->element,
866 $newinvoiceline->fk_fournprice,
867 $newinvoiceline->pa_ht,
868 $newinvoiceline->label,
869 $newinvoiceline->array_options,
870 $newinvoiceline->situation_percent,
871 $newinvoiceline->fk_prev_id,
872 $newinvoiceline->fk_unit,
873 $newinvoiceline->multicurrency_subprice,
874 $newinvoiceline->ref_ext,
879 if ($result > 0 && $newinvoiceline->product_type == 9) {
880 $fk_parent_line = $result;
884 $this->error = $newinvoiceline->error;
885 $this->errors = $newinvoiceline->errors;
890 } elseif (!$error && empty($this->fac_rec)) {
893 dol_syslog(
"There is ".count($this->lines).
" lines that are array lines");
895 foreach ($this->lines as $i => $val) {
896 $line = $this->lines[$i];
900 if (!is_object($line)) {
901 $line = (object) $line;
906 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
911 $vatrate = $line->tva_tx;
912 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', $vatrate)) {
913 $vatrate .=
' ('.$line->vat_src_code.
')';
916 if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
917 $originid = $line->origin_id;
918 $origintype = $line->origin;
920 $originid = $line->id;
921 $origintype = $this->element;
925 if (empty($line->ref_ext)) {
937 $line->remise_percent,
940 $line->fk_code_ventilation,
942 $line->fk_remise_except,
951 $line->fk_fournprice,
954 $line->array_options,
955 $line->situation_percent,
958 $line->multicurrency_subprice,
963 $this->error = $this->
db->lasterror();
965 $this->
db->rollback();
970 if ($result > 0 && $line->product_type == 9) {
971 $fk_parent_line = $result;
980 if (!$error && $this->fac_rec > 0) {
981 foreach ($_facrec->lines as $i => $val) {
982 if ($_facrec->lines[$i]->fk_product) {
984 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
995 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
996 $tva_npr = $_facrec->lines[$i]->info_bits;
997 if (empty($tva_tx)) {
1000 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1001 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1003 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1004 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1007 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1008 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1010 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1015 if ($conf->global->MARGIN_TYPE ==
'costprice' && !empty($producttmp->cost_price)) {
1016 $buyprice = $producttmp->cost_price;
1017 } elseif (
isModEnabled(
'stock') && ($conf->global->MARGIN_TYPE ==
'costprice' || $conf->global->MARGIN_TYPE ==
'pmp') && !empty($producttmp->pmp)) {
1018 $buyprice = $producttmp->pmp;
1020 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1021 if ($producttmp->product_fourn_price_id > 0) {
1022 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1028 $result_insert = $this->
addline(
1029 $_facrec->lines[$i]->desc,
1030 $_facrec->lines[$i]->subprice,
1031 $_facrec->lines[$i]->qty,
1035 $_facrec->lines[$i]->fk_product,
1036 $_facrec->lines[$i]->remise_percent,
1037 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1038 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1044 $_facrec->lines[$i]->product_type,
1045 $_facrec->lines[$i]->rang,
1046 $_facrec->lines[$i]->special_code,
1050 $fk_product_fournisseur_price,
1052 $_facrec->lines[$i]->label,
1053 empty($_facrec->lines[$i]->array_options) ?
null:$_facrec->lines[$i]->array_options,
1056 $_facrec->lines[$i]->fk_unit,
1057 $_facrec->lines[$i]->multicurrency_subprice,
1058 $_facrec->lines[$i]->ref_ext,
1062 if ($result_insert < 0) {
1064 $this->error = $this->
db->error();
1083 if (!$error && !$notrigger) {
1093 $this->
db->commit();
1096 $this->
db->rollback();
1100 $this->error = $langs->trans(
'FailedToUpdatePrice');
1101 $this->
db->rollback();
1105 dol_syslog(get_class($this).
"::create error ".$this->error, LOG_ERR);
1106 $this->
db->rollback();
1110 $this->error = $this->
db->error();
1111 $this->
db->rollback();
1135 if (!empty($this->array_options)) {
1136 $facture->array_options = $this->array_options;
1139 foreach ($this->lines as &$line) {
1140 $line->fetch_optionals();
1144 $facture->type = $this->type;
1145 $facture->socid = $this->socid;
1146 $facture->date = $this->date;
1147 $facture->date_pointoftax = $this->date_pointoftax;
1148 $facture->note_public = $this->note_public;
1149 $facture->note_private = $this->note_private;
1150 $facture->ref_client = $this->ref_client;
1151 $facture->modelpdf = $this->model_pdf;
1152 $facture->model_pdf = $this->model_pdf;
1153 $facture->fk_project = $this->fk_project;
1154 $facture->cond_reglement_id = $this->cond_reglement_id;
1155 $facture->mode_reglement_id = $this->mode_reglement_id;
1156 $facture->remise_absolue = $this->remise_absolue;
1157 $facture->remise_percent = $this->remise_percent;
1159 $facture->origin = $this->origin;
1160 $facture->origin_id = $this->origin_id;
1161 $facture->fk_account = $this->fk_account;
1163 $facture->lines = $this->lines;
1164 $facture->situation_counter = $this->situation_counter;
1165 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1166 $facture->situation_final = $this->situation_final;
1168 $facture->retained_warranty = $this->retained_warranty;
1169 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1170 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1172 $facture->fk_user_author = $user->id;
1176 foreach ($facture->lines as $i => $tmpline) {
1177 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1178 if ($invertdetail) {
1179 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1180 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1181 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1182 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1183 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1184 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1185 $facture->lines[$i]->ref_ext =
'';
1189 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1191 $facid = $facture->create($user);
1193 $this->error = $facture->error;
1194 $this->errors = $facture->errors;
1195 } elseif ($this->
type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
1198 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1199 foreach ($Tfk_object as $fk_object) {
1200 $facture->add_object_linked($typeObject, $fk_object);
1204 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1220 global $conf, $hookmanager;
1228 $object->fetch($fromid);
1231 $objFrom = clone $object;
1234 if (!empty($this->socid) && $this->socid != $object->socid) {
1237 if ($objsoc->fetch($this->socid) > 0) {
1238 $object->socid = $objsoc->id;
1239 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1240 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1241 $object->fk_project =
'';
1242 $object->fk_delivery_address =
'';
1253 $object->date = (empty($this->date) ?
dol_now() : $this->date);
1254 $object->user_author = $user->id;
1255 $object->user_valid =
null;
1256 $object->fk_user_author = $user->id;
1257 $object->fk_user_valid =
null;
1258 $object->fk_facture_source = 0;
1259 $object->date_creation =
'';
1260 $object->date_modification =
'';
1261 $object->date_validation =
'';
1262 $object->ref_client =
'';
1263 $object->close_code =
'';
1264 $object->close_note =
'';
1266 $object->note_private =
'';
1267 $object->note_public =
'';
1271 foreach ($object->lines as $i => $line) {
1272 if (($object->lines[$i]->info_bits & 0x02) == 0x02) {
1273 unset($object->lines[$i]);
1279 if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
1291 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1292 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1296 $object->lines[$i]->date_start = $newFirst;
1297 $object->lines[$i]->date_end = $newLast;
1301 $object->lines[$i]->ref_ext =
'';
1305 $object->context[
'createfromclone'] =
'createfromclone';
1306 $result = $object->create($user);
1309 $this->error = $object->error;
1310 $this->errors = $object->errors;
1313 if ($object->copy_linked_contact($objFrom,
'internal') < 0) {
1315 $this->error = $object->error;
1316 $this->errors = $object->errors;
1317 } elseif ($object->socid == $objFrom->socid) {
1319 if ($object->copy_linked_contact($objFrom,
'external') < 0) {
1321 $this->error = $object->error;
1322 $this->errors = $object->errors;
1329 if (is_object($hookmanager)) {
1330 $parameters = array(
'objFrom'=>$objFrom);
1332 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $object, $action);
1334 $this->errors += $hookmanager->errors;
1335 $this->error = $hookmanager->error;
1341 unset($object->context[
'createfromclone']);
1345 $this->
db->commit();
1348 $this->
db->rollback();
1362 global $conf, $hookmanager;
1370 $num = count($object->lines);
1371 for ($i = 0; $i < $num; $i++) {
1374 $line->libelle = $object->lines[$i]->libelle;
1375 $line->label = $object->lines[$i]->label;
1376 $line->desc = $object->lines[$i]->desc;
1377 $line->subprice = $object->lines[$i]->subprice;
1378 $line->total_ht = $object->lines[$i]->total_ht;
1379 $line->total_tva = $object->lines[$i]->total_tva;
1380 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1381 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1382 $line->total_ttc = $object->lines[$i]->total_ttc;
1383 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1384 $line->tva_tx = $object->lines[$i]->tva_tx;
1385 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1386 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1387 $line->qty = $object->lines[$i]->qty;
1388 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1389 $line->remise_percent = $object->lines[$i]->remise_percent;
1390 $line->fk_product = $object->lines[$i]->fk_product;
1391 $line->info_bits = $object->lines[$i]->info_bits;
1392 $line->product_type = $object->lines[$i]->product_type;
1393 $line->rang = $object->lines[$i]->rang;
1394 $line->special_code = $object->lines[$i]->special_code;
1395 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1396 $line->fk_unit = $object->lines[$i]->fk_unit;
1397 $line->date_start = $object->lines[$i]->date_start;
1398 $line->date_end = $object->lines[$i]->date_end;
1401 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1402 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1403 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1404 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1405 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1406 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1408 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1409 $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);
1410 $line->pa_ht = $marginInfos[0];
1413 $object->lines[$i]->fetch_optionals();
1414 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1415 $line->array_options[$options_key] = $value;
1418 $this->lines[$i] = $line;
1421 $this->socid = $object->socid;
1422 $this->fk_project = $object->fk_project;
1423 $this->fk_account = $object->fk_account;
1424 $this->cond_reglement_id = $object->cond_reglement_id;
1425 $this->mode_reglement_id = $object->mode_reglement_id;
1426 $this->availability_id = $object->availability_id;
1427 $this->demand_reason_id = $object->demand_reason_id;
1428 $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
1429 $this->date_livraison = $object->delivery_date;
1430 $this->fk_delivery_address = $object->fk_delivery_address;
1431 $this->contact_id = $object->contact_id;
1432 $this->ref_client = $object->ref_client;
1434 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1435 $this->note_private = $object->note_private;
1436 $this->note_public = $object->note_public;
1439 $this->module_source = $object->module_source;
1440 $this->pos_source = $object->pos_source;
1442 $this->origin = $object->element;
1443 $this->origin_id = $object->id;
1445 $this->fk_user_author = $user->id;
1448 $object->fetch_optionals();
1449 foreach ($object->array_options as $options_key => $value) {
1450 $this->array_options[$options_key] = $value;
1454 $this->linked_objects[$this->origin] = $this->origin_id;
1455 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1456 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1459 $ret = $this->
create($user);
1463 $hookmanager->initHooks(array(
'invoicedao'));
1465 $parameters = array(
'objFrom'=>$object);
1467 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1469 $this->errors += $hookmanager->errors;
1470 $this->error = $hookmanager->error;
1498 global $conf, $langs, $hookmanager, $action;
1500 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1501 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1506 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1510 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1512 if ($date > (
dol_get_last_hour(
dol_now(
'tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1513 $origin->error =
'ErrorDateIsInFuture';
1517 if ($payment_terms_id <= 0) {
1518 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1522 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1524 if (empty($payment_conditions_deposit_percent)) {
1525 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1529 if (empty($origin->deposit_percent)) {
1530 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1534 $deposit =
new self($origin->db);
1535 $deposit->socid = $origin->socid;
1537 $deposit->fk_project = $origin->fk_project;
1538 $deposit->ref_client = $origin->ref_client;
1539 $deposit->date = $date;
1540 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1541 $deposit->cond_reglement_id = $payment_terms_id;
1542 $deposit->availability_id = $origin->availability_id;
1543 $deposit->demand_reason_id = $origin->demand_reason_id;
1544 $deposit->fk_account = $origin->fk_account;
1545 $deposit->fk_incoterms = $origin->fk_incoterms;
1546 $deposit->location_incoterms = $origin->location_incoterms;
1547 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1548 $deposit->multicurrency_code = $origin->multicurrency_code;
1549 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1550 $deposit->module_source = $origin->module_source;
1551 $deposit->pos_source = $origin->pos_source;
1552 $deposit->model_pdf =
'crabe';
1554 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1556 if (!empty($conf->global->$modelByTypeConfName)) {
1557 $deposit->model_pdf = $conf->global->$modelByTypeConfName;
1558 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
1559 $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
1562 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1563 $deposit->note_private = $origin->note_private;
1564 $deposit->note_public = $origin->note_public;
1567 $deposit->origin = $origin->element;
1568 $deposit->origin_id = $origin->id;
1570 $origin->fetch_optionals();
1572 foreach ($origin->array_options as $extrakey => $value) {
1573 $deposit->array_options[$extrakey] = $value;
1576 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1578 foreach ($overrideFields as $key => $value) {
1579 $deposit->$key = $value;
1582 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1584 $origin->db->begin();
1587 $createReturn = $deposit->create($user, $notrigger);
1589 if ($createReturn <= 0) {
1590 $origin->db->rollback();
1591 $origin->error = $deposit->error;
1592 $origin->errors = $deposit->errors;
1596 $amount_ttc_diff = 0;
1597 $amountdeposit = array();
1598 $descriptions = array();
1600 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1601 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1603 $TTotalByTva = array();
1604 foreach ($origin->lines as &$line) {
1605 if (!empty($line->special_code)) {
1608 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1609 $descriptions[$line->tva_tx] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1610 $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1611 $descriptions[$line->tva_tx] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1612 $descriptions[$line->tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1615 foreach ($TTotalByTva as $tva => &$total) {
1616 $coef = $total / $origin->total_ttc;
1617 $am = $amount * $coef;
1618 $amount_ttc_diff += $am;
1619 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1623 $lines = $origin->lines;
1624 $numlines = count($lines);
1625 for ($i = 0; $i < $numlines; $i++) {
1626 if (empty($lines[$i]->qty)) {
1629 if (!empty($lines[$i]->special_code)) {
1633 $totalamount += $lines[$i]->total_ht;
1634 $tva_tx = $lines[$i]->tva_tx;
1635 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1636 $descriptions[$tva_tx] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1637 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1638 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1639 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1642 if ($totalamount == 0) {
1643 $amountdeposit[0] = 0;
1646 $amount_ttc_diff = $amountdeposit[0];
1649 foreach ($amountdeposit as $tva => $amount) {
1650 if (empty($amount)) {
1654 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1657 if (!empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && !empty($descriptions[$tva])) {
1658 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1661 $addlineResult = $deposit->addline(
1668 (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1688 if ($addlineResult < 0) {
1689 $origin->db->rollback();
1690 $origin->error = $deposit->error;
1691 $origin->errors = $deposit->errors;
1696 $diff = $deposit->total_ttc - $amount_ttc_diff;
1698 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1699 $deposit->fetch_lines();
1700 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1702 $updatelineResult = $deposit->updateline(
1703 $deposit->lines[0]->id,
1704 $deposit->lines[0]->desc,
1706 $deposit->lines[0]->qty,
1707 $deposit->lines[0]->remise_percent,
1708 $deposit->lines[0]->date_start,
1709 $deposit->lines[0]->date_end,
1710 $deposit->lines[0]->tva_tx,
1714 $deposit->lines[0]->info_bits,
1715 $deposit->lines[0]->product_type,
1719 $deposit->lines[0]->pa_ht,
1720 $deposit->lines[0]->label,
1726 if ($updatelineResult < 0) {
1727 $origin->db->rollback();
1728 $origin->error = $deposit->error;
1729 $origin->errors = $deposit->errors;
1735 if (! is_object($hookmanager)) {
1736 require_once DOL_DOCUMENT_ROOT .
'/core/class/hookmanager.class.php';
1740 $hookmanager->initHooks(array(
'invoicedao'));
1742 $parameters = array(
'objFrom' => $origin);
1743 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1746 $origin->db->rollback();
1747 $origin->error = $hookmanager->error;
1748 $origin->errors = $hookmanager->errors;
1752 if (!empty($autoValidateDeposit)) {
1753 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1755 if ($validateReturn < 0) {
1756 $origin->db->rollback();
1757 $origin->error = $deposit->error;
1758 $origin->errors = $deposit->errors;
1763 unset($deposit->context[
'createdepositfromorigin']);
1765 $origin->db->commit();
1784 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
1786 global $langs, $conf, $user, $mysoc;
1788 if (!empty($conf->dol_no_mouse_hover)) {
1794 if ($option ==
'withdraw') {
1795 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
1797 $url = DOL_URL_ROOT.
'/compta/facture/card.php?facid='.$this->id;
1800 if (!$user->hasRight(
"facture",
"read")) {
1804 if ($option !==
'nolink') {
1806 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1807 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
1808 $add_save_lastsearch_values = 1;
1810 if ($add_save_lastsearch_values) {
1811 $url .=
'&save_lastsearch_values=1';
1819 $picto = $this->picto;
1820 if ($this->
type == self::TYPE_REPLACEMENT) {
1823 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1826 if ($this->
type == self::TYPE_DEPOSIT) {
1831 if ($user->hasRight(
"facture",
"read")) {
1832 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1833 if (isset($this->statut) && isset($this->alreadypaid)) {
1834 $label .=
' '.$this->getLibStatut(5, $this->alreadypaid);
1836 $label .=
' '.$this->getLibType(1);
1837 if (!empty($this->
ref)) {
1838 $label .=
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
1840 if (!empty($this->ref_client)) {
1841 $label .=
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_client;
1843 if (!empty($this->date)) {
1844 $label .=
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
1846 if (!empty($this->total_ht)) {
1847 $label .=
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1849 if (!empty($this->total_tva)) {
1850 $label .=
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1852 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1853 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1855 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1856 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1858 if (!empty($this->total_ttc)) {
1859 $label .=
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1862 $label .=
' - '.$moretitle;
1866 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
1867 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
1868 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1869 $label = $langs->trans(
"Invoice");
1870 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
1872 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
1873 $linkclose .=
' class="classfortooltip"';
1876 $linkstart =
'<a href="'.$url.
'"';
1877 $linkstart .= $linkclose.
'>';
1880 if ($option ==
'nolink') {
1885 $result .= $linkstart;
1887 $result .=
img_object(($notooltip ?
'' : $label), $picto, ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1889 if ($withpicto != 2) {
1890 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
1892 $result .= $linkend;
1894 if ($addlinktonotes) {
1895 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1898 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
1899 $result .=
' <span class="note inline-block">';
1900 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
1905 $result .=
'</span>';
1909 global $action, $hookmanager;
1910 $hookmanager->initHooks(array(
'invoicedao'));
1911 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value'=> $save_lastsearch_value,
'target' => $target);
1912 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
1914 $result = $hookmanager->resPrint;
1916 $result .= $hookmanager->resPrint;
1932 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused =
'', $fetch_situation =
false)
1934 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
1938 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.fk_soc';
1939 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
1940 $sql .=
', f.remise_percent, f.remise_absolue, f.remise';
1941 $sql .=
', f.datef as df, f.date_pointoftax';
1942 $sql .=
', f.date_lim_reglement as dlr';
1943 $sql .=
', f.datec as datec';
1944 $sql .=
', f.date_valid as datev';
1945 $sql .=
', f.tms as datem';
1946 $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';
1947 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
1948 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1949 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1950 $sql .=
', f.fk_account';
1951 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1952 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1953 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1954 $sql .=
', f.fk_incoterms, f.location_incoterms';
1955 $sql .=
', f.module_source, f.pos_source';
1956 $sql .=
", i.libelle as label_incoterms";
1957 $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";
1958 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
1959 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
1960 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
1961 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
1964 $sql .=
" WHERE f.rowid = ".((int) $rowid);
1966 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
1968 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
1971 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
1975 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
1979 $obj = $this->
db->fetch_object(
$resql);
1981 $this->
id = $obj->rowid;
1982 $this->entity = $obj->entity;
1984 $this->
ref = $obj->ref;
1985 $this->ref_client = $obj->ref_client;
1986 $this->ref_customer = $obj->ref_client;
1987 $this->ref_ext = $obj->ref_ext;
1988 $this->
type = $obj->type;
1989 $this->date = $this->
db->jdate($obj->df);
1990 $this->date_pointoftax = $this->
db->jdate($obj->date_pointoftax);
1991 $this->date_creation = $this->
db->jdate($obj->datec);
1992 $this->date_validation = $this->
db->jdate($obj->datev);
1993 $this->date_modification = $this->
db->jdate($obj->datem);
1994 $this->datem = $this->
db->jdate($obj->datem);
1995 $this->remise_percent = $obj->remise_percent;
1996 $this->remise_absolue = $obj->remise_absolue;
1997 $this->total_ht = $obj->total_ht;
1998 $this->total_tva = $obj->total_tva;
1999 $this->total_localtax1 = $obj->localtax1;
2000 $this->total_localtax2 = $obj->localtax2;
2001 $this->total_ttc = $obj->total_ttc;
2002 $this->revenuestamp = $obj->revenuestamp;
2003 $this->paye = $obj->paye;
2004 $this->close_code = $obj->close_code;
2005 $this->close_note = $obj->close_note;
2007 $this->socid = $obj->fk_soc;
2008 $this->thirdparty =
null;
2010 $this->fk_project = $obj->fk_project;
2011 $this->project =
null;
2013 $this->statut = $obj->fk_statut;
2014 $this->status = $obj->fk_statut;
2016 $this->date_lim_reglement = $this->
db->jdate($obj->dlr);
2017 $this->mode_reglement_id = $obj->fk_mode_reglement;
2018 $this->mode_reglement_code = $obj->mode_reglement_code;
2019 $this->mode_reglement = $obj->mode_reglement_libelle;
2020 $this->cond_reglement_id = $obj->fk_cond_reglement;
2021 $this->cond_reglement_code = $obj->cond_reglement_code;
2022 $this->cond_reglement = $obj->cond_reglement_libelle;
2023 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2024 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2025 $this->fk_facture_source = $obj->fk_facture_source;
2026 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2027 $this->note = $obj->note_private;
2028 $this->note_private = $obj->note_private;
2029 $this->note_public = $obj->note_public;
2030 $this->user_author = $obj->fk_user_author;
2031 $this->user_valid = $obj->fk_user_valid;
2032 $this->user_modification = $obj->fk_user_modif;
2033 $this->fk_user_author = $obj->fk_user_author;
2034 $this->fk_user_valid = $obj->fk_user_valid;
2035 $this->fk_user_modif = $obj->fk_user_modif;
2036 $this->model_pdf = $obj->model_pdf;
2037 $this->modelpdf = $obj->model_pdf;
2038 $this->last_main_doc = $obj->last_main_doc;
2039 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2040 $this->situation_counter = $obj->situation_counter;
2041 $this->situation_final = $obj->situation_final;
2042 $this->retained_warranty = $obj->retained_warranty;
2043 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2044 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2046 $this->extraparams = (array) json_decode($obj->extraparams,
true);
2049 $this->fk_incoterms = $obj->fk_incoterms;
2050 $this->location_incoterms = $obj->location_incoterms;
2051 $this->label_incoterms = $obj->label_incoterms;
2053 $this->module_source = $obj->module_source;
2054 $this->pos_source = $obj->pos_source;
2057 $this->fk_multicurrency = $obj->fk_multicurrency;
2058 $this->multicurrency_code = $obj->multicurrency_code;
2059 $this->multicurrency_tx = $obj->multicurrency_tx;
2060 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2061 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2062 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2064 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2068 if ($this->status == self::STATUS_DRAFT) {
2069 $this->brouillon = 1;
2077 $this->lines = array();
2081 $this->error = $this->
db->error();
2089 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2091 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2095 $this->error = $this->
db->lasterror();
2110 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2113 global $langs, $conf;
2115 $this->lines = array();
2117 $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,';
2118 $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,';
2119 $sql .=
' l.situation_percent, l.fk_prev_id,';
2120 $sql .=
' l.rang, l.special_code,';
2121 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2122 $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,';
2123 $sql .=
' l.fk_unit,';
2124 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2125 $sql .=
' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2126 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2127 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2128 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2129 $sql .=
' ORDER BY l.rang, l.rowid';
2131 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2132 $result = $this->
db->query($sql);
2134 $num = $this->
db->num_rows($result);
2137 $objp = $this->
db->fetch_object($result);
2140 $line->id = $objp->rowid;
2141 $line->rowid = $objp->rowid;
2142 $line->fk_facture = $objp->fk_facture;
2143 $line->label = $objp->custom_label;
2144 $line->desc = $objp->description;
2145 $line->description = $objp->description;
2146 $line->product_type = $objp->product_type;
2147 $line->ref = $objp->product_ref;
2148 $line->product_ref = $objp->product_ref;
2149 $line->libelle = $objp->product_label;
2150 $line->product_label = $objp->product_label;
2151 $line->product_desc = $objp->product_desc;
2152 $line->fk_product_type = $objp->fk_product_type;
2153 $line->qty = $objp->qty;
2154 $line->subprice = $objp->subprice;
2155 $line->ref_ext = $objp->ref_ext;
2157 $line->vat_src_code = $objp->vat_src_code;
2158 $line->tva_tx = $objp->tva_tx;
2159 $line->localtax1_tx = $objp->localtax1_tx;
2160 $line->localtax2_tx = $objp->localtax2_tx;
2161 $line->localtax1_type = $objp->localtax1_type;
2162 $line->localtax2_type = $objp->localtax2_type;
2163 $line->remise_percent = $objp->remise_percent;
2164 $line->fk_remise_except = $objp->fk_remise_except;
2165 $line->fk_product = $objp->fk_product;
2166 $line->date_start = $this->
db->jdate($objp->date_start);
2167 $line->date_end = $this->
db->jdate($objp->date_end);
2168 $line->date_start = $this->
db->jdate($objp->date_start);
2169 $line->date_end = $this->
db->jdate($objp->date_end);
2170 $line->info_bits = $objp->info_bits;
2171 $line->total_ht = $objp->total_ht;
2172 $line->total_tva = $objp->total_tva;
2173 $line->total_localtax1 = $objp->total_localtax1;
2174 $line->total_localtax2 = $objp->total_localtax2;
2175 $line->total_ttc = $objp->total_ttc;
2176 $line->code_ventilation = $objp->fk_code_ventilation;
2177 $line->fk_fournprice = $objp->fk_fournprice;
2178 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2179 $line->pa_ht = $marginInfos[0];
2180 $line->marge_tx = $marginInfos[1];
2181 $line->marque_tx = $marginInfos[2];
2182 $line->rang = $objp->rang;
2183 $line->special_code = $objp->special_code;
2184 $line->fk_parent_line = $objp->fk_parent_line;
2185 $line->situation_percent = $objp->situation_percent;
2186 $line->fk_prev_id = $objp->fk_prev_id;
2187 $line->fk_unit = $objp->fk_unit;
2190 $line->fk_accounting_account = $objp->fk_code_ventilation;
2193 $line->fk_multicurrency = $objp->fk_multicurrency;
2194 $line->multicurrency_code = $objp->multicurrency_code;
2195 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2196 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2197 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2198 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2200 $line->fetch_optionals();
2203 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2205 $tmpproduct->fetch($objp->fk_product);
2206 $tmpproduct->getMultiLangs();
2208 $line->multilangs = $tmpproduct->multilangs;
2211 $this->lines[$i] = $line;
2215 $this->
db->free($result);
2218 $this->error = $this->
db->error();
2233 $this->tab_previous_situation_invoice = array();
2234 $this->tab_next_situation_invoice = array();
2236 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2237 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2238 $sql .=
' AND entity = '.((int) $this->entity);
2239 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2240 $sql .=
' ORDER BY situation_counter ASC';
2242 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2243 $result = $this->
db->query($sql);
2244 if ($result && $this->
db->num_rows($result) > 0) {
2245 while ($objp = $this->
db->fetch_object($result)) {
2247 if ($invoice->fetch($objp->rowid) > 0) {
2248 if ($objp->situation_counter < $this->situation_counter
2249 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2251 $this->tab_previous_situation_invoice[] = $invoice;
2253 $this->tab_next_situation_invoice[] = $invoice;
2274 if (empty($this->
type)) {
2277 if (isset($this->
ref)) {
2278 $this->
ref = trim($this->
ref);
2280 if (isset($this->ref_ext)) {
2281 $this->ref_ext = trim($this->ref_ext);
2283 if (isset($this->ref_client)) {
2284 $this->ref_client = trim($this->ref_client);
2286 if (isset($this->increment)) {
2287 $this->increment = trim($this->increment);
2289 if (isset($this->close_code)) {
2290 $this->close_code = trim($this->close_code);
2292 if (isset($this->close_note)) {
2293 $this->close_note = trim($this->close_note);
2295 if (isset($this->note) || isset($this->note_private)) {
2296 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2298 if (isset($this->note) || isset($this->note_private)) {
2299 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2301 if (isset($this->note_public)) {
2302 $this->note_public = trim($this->note_public);
2304 if (isset($this->model_pdf)) {
2305 $this->model_pdf = trim($this->model_pdf);
2307 if (isset($this->import_key)) {
2308 $this->import_key = trim($this->import_key);
2310 if (isset($this->retained_warranty)) {
2311 $this->retained_warranty = floatval($this->retained_warranty);
2319 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2320 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2321 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2322 $sql .=
" type=".(isset($this->
type) ? $this->
db->escape($this->
type) :
"null").
",";
2323 $sql .=
" ref_client=".(isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null").
",";
2324 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2325 $sql .=
" fk_soc=".(isset($this->socid) ? $this->
db->escape($this->socid) :
"null").
",";
2326 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2327 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2328 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2329 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2330 $sql .=
" paye=".(isset($this->paye) ? $this->
db->escape($this->paye) : 0).
",";
2331 $sql .=
" remise_percent=".(isset($this->remise_percent) ? $this->
db->escape($this->remise_percent) :
"null").
",";
2332 $sql .=
" remise_absolue=".(isset($this->remise_absolue) ? $this->
db->escape($this->remise_absolue) :
"null").
",";
2333 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2334 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2335 $sql .=
" total_tva=".(isset($this->total_tva) ? $this->total_tva :
"null").
",";
2336 $sql .=
" localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 :
"null").
",";
2337 $sql .=
" localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 :
"null").
",";
2338 $sql .=
" total_ht=".(isset($this->total_ht) ? $this->total_ht :
"null").
",";
2339 $sql .=
" total_ttc=".(isset($this->total_ttc) ? $this->total_ttc :
"null").
",";
2340 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? $this->
db->escape($this->revenuestamp) :
"null").
",";
2341 $sql .=
" fk_statut=".(isset($this->statut) ? $this->
db->escape($this->statut) :
"null").
",";
2342 $sql .=
" fk_user_author=".(isset($this->user_author) ? $this->
db->escape($this->user_author) :
"null").
",";
2343 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? $this->
db->escape($this->fk_user_valid) :
"null").
",";
2344 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? $this->
db->escape($this->fk_facture_source) :
"null").
",";
2345 $sql .=
" fk_projet=".(isset($this->fk_project) ? $this->
db->escape($this->fk_project) :
"null").
",";
2346 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->
db->escape($this->cond_reglement_id) :
"null").
",";
2347 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->
db->escape($this->mode_reglement_id) :
"null").
",";
2348 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2349 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2350 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2351 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2352 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2353 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : $this->
db->escape($this->situation_cycle_ref)).
",";
2354 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : $this->
db->escape($this->situation_counter)).
",";
2355 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : $this->
db->escape($this->situation_final)).
",";
2356 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty)).
",";
2357 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2358 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) :
"null");
2359 $sql .=
" WHERE rowid=".((int) $this->
id);
2363 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2367 $this->errors[] =
"Error ".$this->db->lasterror();
2377 if (!$error && !$notrigger) {
2388 foreach ($this->errors as $errmsg) {
2389 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2390 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2392 $this->
db->rollback();
2395 $this->
db->commit();
2411 global $conf, $langs;
2413 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2414 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2419 $result = $remise->fetch($idremise);
2422 if ($remise->fk_facture) {
2423 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2424 $this->
db->rollback();
2429 $facligne->fk_facture = $this->id;
2430 $facligne->fk_remise_except = $remise->id;
2431 $facligne->desc = $remise->description;
2432 $facligne->vat_src_code = $remise->vat_src_code;
2433 $facligne->tva_tx = $remise->tva_tx;
2434 $facligne->subprice = -$remise->amount_ht;
2435 $facligne->fk_product = 0;
2437 $facligne->remise_percent = 0;
2438 $facligne->rang = -1;
2439 $facligne->info_bits = 2;
2441 if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
2442 $facligne->rang = 1;
2443 $linecount = count($this->lines);
2444 for ($ii = 1; $ii <= $linecount; $ii++) {
2450 if ($remise->fk_facture_source > 0) {
2452 $srcinvoice->fetch($remise->fk_facture_source);
2453 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2455 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2456 $facligne->pa_ht = $arraytmp[
'pa_total'];
2459 $facligne->total_ht = -$remise->amount_ht;
2460 $facligne->total_tva = -$remise->amount_tva;
2461 $facligne->total_ttc = -$remise->amount_ttc;
2463 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2464 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2465 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2466 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2468 $lineid = $facligne->insert();
2473 $result = $remise->link_to_invoice($lineid, 0);
2475 $this->error = $remise->error;
2476 $this->
db->rollback();
2480 $this->
db->commit();
2483 $this->error = $facligne->error;
2484 $this->
db->rollback();
2488 $this->error = $facligne->error;
2489 $this->
db->rollback();
2493 $this->
db->rollback();
2515 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2516 if (empty($ref_client)) {
2517 $sql .=
' SET ref_client = NULL';
2519 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2521 $sql .=
" WHERE rowid = ".((int) $this->
id);
2523 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2526 $this->errors[] = $this->
db->error();
2531 $this->ref_client = $ref_client;
2534 if (!$notrigger && empty($error)) {
2544 $this->ref_client = $ref_client;
2546 $this->
db->commit();
2549 foreach ($this->errors as $errmsg) {
2550 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2551 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2553 $this->
db->rollback();
2566 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2568 global $langs, $conf;
2569 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2573 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2586 if (!$error && !$notrigger) {
2600 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2614 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2615 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2616 $sql .=
' AND fk_facture_line IS NULL';
2621 $list_rowid_det = array();
2622 foreach ($this->lines as $key => $invoiceline) {
2623 $list_rowid_det[] = $invoiceline->id;
2627 if (count($list_rowid_det)) {
2628 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2629 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2630 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(join(
',', $list_rowid_det)).
')';
2632 if (!$this->
db->query($sql)) {
2633 $this->error = $this->
db->error().
" sql=".$sql;
2634 $this->errors[] = $this->error;
2635 $this->
db->rollback();
2642 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2643 $sql .=
' SET fk_invoice = NULL';
2644 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2646 if (!$this->
db->query($sql)) {
2647 $this->error = $this->
db->error().
" sql=".$sql;
2648 $this->errors[] = $this->error;
2649 $this->
db->rollback();
2653 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'projet_task_time';
2654 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2655 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2657 if (!$this->
db->query($sql)) {
2658 $this->error = $this->
db->error().
" sql=".$sql;
2659 $this->errors[] = $this->error;
2660 $this->
db->rollback();
2665 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
2666 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2667 $langs->load(
"agenda");
2669 $num = count($this->lines);
2670 for ($i = 0; $i < $num; $i++) {
2671 if ($this->lines[$i]->fk_product > 0) {
2673 $mouvP->origin = &$this;
2674 $mouvP->setOrigin($this->element, $this->
id);
2676 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2677 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2679 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2686 $main = MAIN_DB_PREFIX.
'facturedet';
2687 $ef = $main.
"_extrafields";
2688 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2690 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2693 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2702 if ($conf->facture->dir_output && !empty($this->
ref)) {
2703 $dir = $conf->facture->dir_output.
"/".$ref;
2704 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2705 if (file_exists($file)) {
2709 $langs->load(
"errors");
2710 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2711 $this->errors[] = $this->error;
2712 $this->
db->rollback();
2716 if (file_exists($dir)) {
2718 $langs->load(
"errors");
2719 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2720 $this->errors[] = $this->error;
2721 $this->
db->rollback();
2727 $this->
db->commit();
2730 $this->error = $this->
db->lasterror().
" sql=".$sql;
2731 $this->errors[] = $this->error;
2732 $this->
db->rollback();
2736 $this->error = $this->
db->lasterror().
" sql=".$sql;
2737 $this->errors[] = $this->error;
2738 $this->
db->rollback();
2742 $this->
db->rollback();
2759 public function set_paid($user, $close_code =
'', $close_note =
'')
2762 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2763 return $this->
setPaid($user, $close_code, $close_note);
2775 public function setPaid($user, $close_code =
'', $close_note =
'')
2779 if ($this->paye != 1) {
2784 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
2786 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2787 $sql .=
' fk_statut='.self::STATUS_CLOSED;
2792 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2795 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2797 $sql .=
', fk_user_closing = '.((int) $user->id);
2798 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
2799 $sql .=
" WHERE rowid = ".((int) $this->
id);
2811 $this->error = $this->
db->lasterror();
2815 $this->
db->commit();
2818 $this->
db->rollback();
2841 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
2859 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2860 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
2861 $sql .=
' date_closing=null,';
2862 $sql .=
' fk_user_closing=null';
2863 $sql .=
" WHERE rowid = ".((int) $this->
id);
2865 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
2876 $this->error = $this->
db->error();
2881 $this->
db->commit();
2884 $this->
db->rollback();
2906 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
2907 return $this->
setCanceled($user, $close_code, $close_note);
2920 public function setCanceled($user, $close_code =
'', $close_note =
'')
2922 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
2926 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2927 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
2929 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2932 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2934 $sql .=
" WHERE rowid = ".((int) $this->
id);
2940 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2941 $sql .=
' SET fk_facture = NULL';
2942 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
2949 $this->
db->rollback();
2954 $this->
db->commit();
2957 $this->error = $this->
db->error().
" sql=".$sql;
2958 $this->
db->rollback();
2962 $this->error = $this->
db->error().
" sql=".$sql;
2963 $this->
db->rollback();
2979 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
2981 global $conf, $langs, $mysoc;
2982 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2984 $productStatic =
null;
2985 $warehouseStatic =
null;
2986 if ($batch_rule > 0) {
2987 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2988 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
2989 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
2990 $productStatic =
new Product($this->
db);
2992 $productbatch =
new ProductBatch($this->
db);
2998 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3005 if ($this->statut != self::STATUS_DRAFT) {
3006 dol_syslog(get_class($this).
"::validate status is not draft. operation canceled.", LOG_WARNING);
3009 if (count($this->lines) <= 0) {
3010 $langs->load(
"errors");
3011 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3014 if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
3015 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
3016 $this->error =
'Permission denied';
3017 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
3020 if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
3022 if (!$last_of_type[0]) {
3023 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3029 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3030 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3031 foreach ($array_to_check as $key) {
3032 $keymin = strtolower($key);
3033 if (!property_exists($this->thirdparty, $keymin)) {
3036 $vallabel = $this->thirdparty->$keymin;
3038 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3040 if ($this->thirdparty->isACompany()) {
3042 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3043 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3044 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3045 $langs->load(
"errors");
3046 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3047 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3053 if ($key ==
'EMAIL') {
3055 if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
3056 $langs->load(
"errors");
3057 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3058 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3062 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3064 if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
3065 $langs->load(
"errors");
3066 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3067 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3076 $array_to_check = array(
'REF_CLIENT'=>
'RefCustomer');
3077 foreach ($array_to_check as $key => $val) {
3078 $keymin = strtolower($key);
3079 $vallabel = $this->$keymin;
3082 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3083 if (!$vallabel && !empty($conf->global->$keymandatory)) {
3084 $langs->load(
"errors");
3086 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val)),
null,
'errors');
3093 if ($this->
type == self::TYPE_REPLACEMENT) {
3095 if ($this->fk_facture_source <= 0) {
3096 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3097 $this->
db->rollback();
3103 $result = $facreplaced->fetch($this->fk_facture_source);
3105 $this->error = $langs->trans(
"ErrorBadInvoice");
3106 $this->
db->rollback();
3111 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3112 if ($idreplacement && $idreplacement != $this->
id) {
3113 $facreplacement =
new Facture($this->
db);
3114 $facreplacement->fetch($idreplacement);
3115 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3116 $this->
db->rollback();
3120 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3122 $this->error = $facreplaced->error;
3123 $this->
db->rollback();
3129 if ($force_number) {
3130 $num = $force_number;
3131 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3132 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3147 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3148 $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).
"'";
3149 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3150 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3151 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3153 $sql .=
" WHERE rowid = ".((int) $this->
id);
3155 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3163 if (!$error && (preg_match(
'/^[\(]?PROV/i', $this->
ref))) {
3169 $result = $this->thirdparty->set_as_client();
3172 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
3173 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3174 $langs->load(
"agenda");
3177 $cpt = count($this->lines);
3178 for ($i = 0; $i < $cpt; $i++) {
3179 if ($this->lines[$i]->fk_product > 0) {
3181 $mouvP->origin = &$this;
3182 $mouvP->setOrigin($this->element, $this->
id);
3184 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3185 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3188 $this->error = $mouvP->error;
3191 $is_batch_line =
false;
3192 if ($batch_rule > 0) {
3193 $productStatic->fetch($this->lines[$i]->fk_product);
3194 if ($productStatic->hasbatch()) {
3195 $is_batch_line =
true;
3196 $product_qty_remain = $this->lines[$i]->qty;
3202 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3203 $sortorder =
'ASC,ASC,ASC,ASC';
3206 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ?
null : 0), $sortfield, $sortorder);
3207 if (!is_array($resBatchList)) {
3209 $this->error = $this->
db->lasterror();
3213 $batchList = $resBatchList;
3214 if (empty($batchList)) {
3216 $langs->load(
'errors');
3217 $warehouseStatic->fetch($idwarehouse);
3218 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3219 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3222 foreach ($batchList as $batch) {
3223 if ($batch->qty <= 0) {
3228 if ($batch->qty >= $product_qty_remain) {
3229 $product_batch_qty = $product_qty_remain;
3232 $product_batch_qty = $batch->qty;
3234 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3237 $this->error = $mouvP->error;
3241 $product_qty_remain -= $product_batch_qty;
3243 if ($product_qty_remain <= 0) {
3248 if (!$error && $product_qty_remain > 0) {
3249 if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
3251 $batch = $batchList[0];
3252 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3255 $this->error = $mouvP->error;
3259 $langs->load(
'errors');
3260 $warehouseStatic->fetch($idwarehouse);
3261 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3262 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3269 if (!$is_batch_line) {
3270 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3273 $this->error = $mouvP->error;
3286 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3287 $invoice_situation =
new Facture($this->
db);
3288 $result = $invoice_situation->fetch($this->fk_facture_source);
3289 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3290 $invoice_situation->situation_final = 0;
3292 $result = $invoice_situation->setFinal($user, 1);
3295 $this->error = $invoice_situation->error;
3296 $this->errors = $invoice_situation->errors;
3302 if (!$error && !$notrigger) {
3312 $this->oldref = $this->ref;
3315 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3317 $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).
"'";
3318 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->
db->escape($this->
ref).
"' and entity = ".$conf->entity;
3322 $this->error = $this->
db->lasterror();
3328 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3329 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3330 if (!$error && file_exists($dirsource)) {
3331 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3333 if (@rename($dirsource, $dirdest)) {
3336 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3337 foreach ($listoffiles as $fileentry) {
3338 $dirsource = $fileentry[
'name'];
3339 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3340 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3341 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3342 @rename($dirsource, $dirdest);
3361 $this->brouillon = 0;
3362 $this->date_validation = $now;
3365 if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3367 $nboflines = count($this->lines);
3368 while (($i < $nboflines) && $final) {
3369 $final = ($this->lines[$i]->situation_percent == 100);
3373 if (empty($final)) {
3374 $this->situation_final = 0;
3376 $this->situation_final = 1;
3387 $this->
db->commit();
3390 $this->
db->rollback();
3403 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3404 $is_last = $next_invoice->is_last_in_cycle();
3406 if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
3407 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3411 $next_invoice->brouillon = 1;
3413 foreach ($next_invoice->lines as $line) {
3414 $result = $next_invoice->updateline(
3419 $line->remise_percent,
3423 $line->localtax1_tx,
3424 $line->localtax2_tx,
3427 $line->product_type,
3428 $line->fk_parent_line,
3430 $line->fk_fournprice,
3433 $line->special_code,
3434 $line->array_options,
3435 $line->situation_percent,
3440 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3461 global $conf, $langs;
3465 if ($this->statut == self::STATUS_DRAFT) {
3466 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3474 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3475 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3476 $sql .=
" WHERE rowid = ".((int) $this->
id);
3478 $result = $this->
db->query($sql);
3481 $this->oldcopy = clone $this;
3485 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3486 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3487 $langs->load(
"agenda");
3489 $num = count($this->lines);
3490 for ($i = 0; $i < $num; $i++) {
3491 if ($this->lines[$i]->fk_product > 0) {
3493 $mouvP->origin = &$this;
3494 $mouvP->setOrigin($this->element, $this->
id);
3496 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3497 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3499 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3506 $old_statut = $this->statut;
3507 $this->brouillon = 1;
3512 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3515 $this->statut = $old_statut;
3516 $this->status = $old_statut;
3517 $this->brouillon = 0;
3521 $this->
db->rollback();
3526 $this->
db->commit();
3529 $this->
db->rollback();
3533 $this->error = $this->
db->error();
3534 $this->
db->rollback();
3589 $remise_percent = 0,
3594 $fk_remise_except =
'',
3595 $price_base_type =
'HT',
3602 $fk_parent_line = 0,
3603 $fk_fournprice =
null,
3607 $situation_percent = 100,
3612 $noupdateafterinsertline = 0
3616 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3620 global $mysoc, $conf, $langs;
3622 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);
3624 if ($this->statut == self::STATUS_DRAFT) {
3625 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3628 if (empty($remise_percent)) {
3629 $remise_percent = 0;
3634 if (empty($info_bits)) {
3640 if (empty($ventil)) {
3643 if (empty($txtva)) {
3646 if (empty($txlocaltax1)) {
3649 if (empty($txlocaltax2)) {
3652 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3653 $fk_parent_line = 0;
3655 if (empty($fk_prev_id)) {
3656 $fk_prev_id =
'null';
3658 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3659 $situation_percent = 100;
3661 if (empty($ref_ext)) {
3665 $remise_percent =
price2num($remise_percent);
3668 $pu_ht_devise =
price2num($pu_ht_devise);
3671 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3677 if ($price_base_type ==
'HT') {
3688 if ($date_start && $date_end && $date_start > $date_end) {
3689 $langs->load(
"errors");
3690 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3696 $product_type = $type;
3697 if (!empty($fk_product) && $fk_product > 0) {
3699 $result = $product->fetch($fk_product);
3700 $product_type = $product->type;
3702 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3703 $langs->load(
"errors");
3704 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3705 $this->
db->rollback();
3715 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3716 $vat_src_code = $reg[1];
3717 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3725 $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);
3727 $total_ht = $tabprice[0];
3728 $total_tva = $tabprice[1];
3729 $total_ttc = $tabprice[2];
3730 $total_localtax1 = $tabprice[9];
3731 $total_localtax2 = $tabprice[10];
3732 $pu_ht = $tabprice[3];
3735 $multicurrency_total_ht = $tabprice[16];
3736 $multicurrency_total_tva = $tabprice[17];
3737 $multicurrency_total_ttc = $tabprice[18];
3738 $pu_ht_devise = $tabprice[19];
3742 if ($ranktouse == -1) {
3743 $rangmax = $this->
line_max($fk_parent_line);
3744 $ranktouse = $rangmax + 1;
3750 $this->line->context = $this->context;
3752 $this->line->fk_facture = $this->id;
3753 $this->line->label = $label;
3754 $this->line->desc = $desc;
3755 $this->line->ref_ext = $ref_ext;
3757 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty);
3758 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
3760 $this->line->vat_src_code = $vat_src_code;
3761 $this->line->tva_tx = $txtva;
3762 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3763 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3764 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
3765 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
3767 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
3768 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
3769 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
3770 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
3771 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
3773 $this->line->fk_product = $fk_product;
3774 $this->line->product_type = $product_type;
3775 $this->line->remise_percent = $remise_percent;
3776 $this->line->date_start = $date_start;
3777 $this->line->date_end = $date_end;
3778 $this->line->ventil = $ventil;
3779 $this->line->rang = $ranktouse;
3780 $this->line->info_bits = $info_bits;
3781 $this->line->fk_remise_except = $fk_remise_except;
3783 $this->line->special_code = $special_code;
3784 $this->line->fk_parent_line = $fk_parent_line;
3785 $this->line->origin = $origin;
3786 $this->line->origin_id = $origin_id;
3787 $this->line->situation_percent = $situation_percent;
3788 $this->line->fk_prev_id = $fk_prev_id;
3789 $this->line->fk_unit = $fk_unit;
3792 $this->line->fk_fournprice = $fk_fournprice;
3793 $this->line->pa_ht = $pa_ht;
3796 $this->line->fk_multicurrency = $this->fk_multicurrency;
3797 $this->line->multicurrency_code = $this->multicurrency_code;
3798 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
3800 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
3801 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
3802 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
3804 if (is_array($array_options) && count($array_options) > 0) {
3805 $this->line->array_options = $array_options;
3808 $result = $this->line->insert();
3811 if (!empty($fk_parent_line)) {
3813 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
3814 $linecount = count($this->lines);
3815 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
3821 if (empty($noupdateafterinsertline)) {
3826 $this->
db->commit();
3827 return $this->line->id;
3829 $this->error = $this->
db->lasterror();
3830 $this->
db->rollback();
3834 $this->error = $this->line->error;
3835 $this->errors = $this->line->errors;
3836 $this->
db->rollback();
3840 $this->errors[]=
'status of invoice must be Draft to allow use of ->addline()';
3841 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3877 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)
3879 global $conf, $user;
3882 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3885 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3887 global $mysoc, $langs;
3889 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);
3891 if ($this->statut == self::STATUS_DRAFT) {
3894 if (!$this->error) {
3895 $this->error = $langs->trans(
'invoiceLineProgressError');
3901 if ($date_start && $date_end && $date_start > $date_end) {
3902 $langs->load(
"errors");
3903 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3913 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3914 $fk_parent_line = 0;
3916 if (empty($special_code) || $special_code == 3) {
3919 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3920 $situation_percent = 100;
3922 if (empty($ref_ext)) {
3926 $remise_percent =
price2num($remise_percent);
3929 $pu_ht_devise =
price2num($pu_ht_devise);
3931 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3951 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3952 $vat_src_code = $reg[1];
3953 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3956 $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);
3958 $total_ht = $tabprice[0];
3959 $total_tva = $tabprice[1];
3960 $total_ttc = $tabprice[2];
3961 $total_localtax1 = $tabprice[9];
3962 $total_localtax2 = $tabprice[10];
3963 $pu_ht = $tabprice[3];
3964 $pu_tva = $tabprice[4];
3965 $pu_ttc = $tabprice[5];
3968 $multicurrency_total_ht = $tabprice[16];
3969 $multicurrency_total_tva = $tabprice[17];
3970 $multicurrency_total_ttc = $tabprice[18];
3971 $pu_ht_devise = $tabprice[19];
3976 if ($remise_percent > 0) {
3977 $remise = round(($pu * $remise_percent / 100), 2);
3978 $price = ($pu - $remise);
3984 $line->fetch($rowid);
3985 $line->fetch_optionals();
3987 if (!empty($line->fk_product)) {
3989 $result = $product->fetch($line->fk_product);
3990 $product_type = $product->type;
3992 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3993 $langs->load(
"errors");
3994 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3995 $this->
db->rollback();
4000 $staticline = clone $line;
4002 $line->oldline = $staticline;
4003 $this->line = $line;
4004 $this->line->context = $this->context;
4005 $this->line->rang = $rang;
4008 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4009 $rangmax = $this->
line_max($fk_parent_line);
4010 $this->line->rang = $rangmax + 1;
4013 $this->line->id = $rowid;
4014 $this->line->rowid = $rowid;
4015 $this->line->label = $label;
4016 $this->line->desc = $desc;
4017 $this->line->ref_ext = $ref_ext;
4018 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty);
4020 $this->line->vat_src_code = $vat_src_code;
4021 $this->line->tva_tx = $txtva;
4022 $this->line->localtax1_tx = $txlocaltax1;
4023 $this->line->localtax2_tx = $txlocaltax2;
4024 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
4025 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
4027 $this->line->remise_percent = $remise_percent;
4028 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht);
4029 $this->line->date_start = $date_start;
4030 $this->line->date_end = $date_end;
4031 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht);
4032 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
4033 $this->line->total_localtax1 = $total_localtax1;
4034 $this->line->total_localtax2 = $total_localtax2;
4035 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
4036 $this->line->info_bits = $info_bits;
4037 $this->line->special_code = $special_code;
4038 $this->line->product_type = $type;
4039 $this->line->fk_parent_line = $fk_parent_line;
4040 $this->line->skip_update_total = $skip_update_total;
4041 $this->line->situation_percent = $situation_percent;
4042 $this->line->fk_unit = $fk_unit;
4044 $this->line->fk_fournprice = $fk_fournprice;
4045 $this->line->pa_ht = $pa_ht;
4048 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise);
4049 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht);
4050 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
4051 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4053 if (is_array($array_options) && count($array_options) > 0) {
4055 foreach ($array_options as $key => $value) {
4056 $this->line->array_options[$key] = $array_options[$key];
4060 $result = $this->line->update($user, $notrigger);
4063 if (!empty($fk_parent_line)) {
4069 $this->
db->commit();
4072 $this->error = $this->line->error;
4073 $this->
db->rollback();
4077 $this->error =
"Invoice statut makes operation forbidden";
4091 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4092 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4093 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4095 $result = $this->
db->query($sql);
4097 $this->error = $this->
db->error();
4101 $obj = $this->
db->fetch_object($result);
4103 if ($obj ===
null) {
4106 return $situation_percent < $obj->situation_percent;
4122 global $mysoc, $user;
4125 if (($line->info_bits & 2) == 2) {
4129 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4132 if ($percent > 100) {
4135 $line->situation_percent = $percent;
4136 $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);
4137 $line->total_ht = $tabprice[0];
4138 $line->total_tva = $tabprice[1];
4139 $line->total_ttc = $tabprice[2];
4140 $line->total_localtax1 = $tabprice[9];
4141 $line->total_localtax2 = $tabprice[10];
4142 $line->multicurrency_total_ht = $tabprice[16];
4143 $line->multicurrency_total_tva = $tabprice[17];
4144 $line->multicurrency_total_ttc = $tabprice[18];
4145 $line->update($user);
4148 if ($update_price) {
4163 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4165 if ($this->statut != self::STATUS_DRAFT) {
4166 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4173 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
4174 $sql .=
' SET fk_facture_line = NULL';
4175 $sql .=
' WHERE fk_facture_line = '.((int) $rowid);
4177 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
4178 $result = $this->
db->query($sql);
4180 $this->error = $this->
db->error();
4181 $this->
db->rollback();
4187 $line->context = $this->context;
4190 $result = $line->fetch($rowid);
4191 if (!($result > 0)) {
4195 if ($line->delete($user) > 0) {
4199 $this->
db->commit();
4202 $this->
db->rollback();
4203 $this->error = $this->
db->lasterror();
4207 $this->
db->rollback();
4208 $this->error = $line->error;
4227 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4228 return $this->
setDiscount($user, $remise, $notrigger);
4242 if (empty($remise)) {
4246 if ($user->rights->facture->creer) {
4253 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4254 $sql .=
' SET remise_percent = '.((float) $remise);
4255 $sql .=
" WHERE rowid = ".((int) $this->
id);
4256 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4261 $this->errors[] = $this->
db->error();
4265 if (!$notrigger && empty($error)) {
4275 $this->remise_percent = $remise;
4278 $this->
db->commit();
4281 foreach ($this->errors as $errmsg) {
4282 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4283 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4285 $this->
db->rollback();
4304 if (empty($remise)) {
4308 if ($user->rights->facture->creer) {
4315 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4316 $sql .=
' SET remise_absolue = '.((float) $remise);
4317 $sql .=
" WHERE rowid = ".((int) $this->
id);
4318 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4323 $this->errors[] = $this->
db->error();
4328 $this->oldcopy = clone $this;
4329 $this->remise_absolue = $remise;
4333 if (!$notrigger && empty($error)) {
4343 $this->
db->commit();
4346 foreach ($this->errors as $errmsg) {
4347 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4348 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4350 $this->
db->rollback();
4366 global $conf, $langs;
4368 if ($this->module_source ==
'takepos') {
4369 $langs->load(
'cashdesk');
4371 $moduleName =
'takepos';
4372 $moduleSourceName =
'Takepos';
4373 $addonConstName =
'TAKEPOS_REF_ADDON';
4376 if (empty($conf->global->TAKEPOS_REF_ADDON)) {
4377 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4380 $addon = $conf->global->TAKEPOS_REF_ADDON;
4382 $langs->load(
'bills');
4384 $moduleName =
'facture';
4385 $moduleSourceName =
'Invoice';
4386 $addonConstName =
'FACTURE_ADDON';
4389 if (empty($conf->global->FACTURE_ADDON)) {
4390 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4391 } elseif ($conf->global->FACTURE_ADDON ==
'terre') {
4392 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4393 } elseif ($conf->global->FACTURE_ADDON ==
'mercure') {
4394 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4397 $addon = $conf->global->FACTURE_ADDON;
4400 if (!empty($addon)) {
4401 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = ".$conf->global->FACTURE_ADDON.
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4405 $file = $addon.
'.php';
4406 $classname = $addon;
4410 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4411 foreach ($dirmodels as $reldir) {
4412 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4415 if (is_file($dir.$file) && is_readable($dir.$file)) {
4416 $mybool |= include_once $dir.$file;
4422 $file = $addon.
'/'.$addon.
'.modules.php';
4423 $classname =
'mod_'.$moduleName.
'_'.$addon;
4424 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4426 foreach ($conf->file->dol_document_root as $dirroot) {
4427 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4430 if (is_file($dir.$file) && is_readable($dir.$file)) {
4431 $mybool |= include_once $dir.$file;
4441 $obj =
new $classname();
4443 $numref = $obj->getNextValue($soc, $this, $mode);
4450 if ($mode !=
'last' && !$numref) {
4451 $this->error = $obj->error;
4457 $langs->load(
'errors');
4458 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4471 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4472 $sql .=
' date_closing as dateclosing,';
4473 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4474 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4475 $sql .=
' WHERE c.rowid = '.((int) $id);
4477 $result = $this->
db->query($sql);
4479 if ($this->
db->num_rows($result)) {
4480 $obj = $this->
db->fetch_object($result);
4481 $this->
id = $obj->rowid;
4482 if ($obj->fk_user_author) {
4483 $cuser =
new User($this->
db);
4484 $cuser->fetch($obj->fk_user_author);
4485 $this->user_creation = $cuser;
4487 if ($obj->fk_user_valid) {
4488 $vuser =
new User($this->
db);
4489 $vuser->fetch($obj->fk_user_valid);
4490 $this->user_validation = $vuser;
4492 if ($obj->fk_user_closing) {
4493 $cluser =
new User($this->
db);
4494 $cluser->fetch($obj->fk_user_closing);
4495 $this->user_closing = $cluser;
4498 $this->date_creation = $this->
db->jdate($obj->datec);
4499 $this->date_modification = $this->
db->jdate($obj->datem);
4500 $this->date_validation = $this->
db->jdate($obj->datev);
4501 $this->date_closing = $this->
db->jdate($obj->dateclosing);
4503 $this->
db->free($result);
4524 public function liste_array($shortlist = 0, $draft = 0, $excluser =
'', $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4527 global $conf, $user;
4531 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4532 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4533 if (empty($user->rights->societe->client->voir) && !$socid) {
4534 $sql .=
", sc.fk_soc, sc.fk_user";
4536 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4537 if (empty($user->rights->societe->client->voir) && !$socid) {
4538 $sql .=
", ".MAIN_DB_PREFIX.
"societe_commerciaux as sc";
4540 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4541 $sql .=
" AND f.fk_soc = s.rowid";
4542 if (empty($user->rights->societe->client->voir) && !$socid) {
4543 $sql .=
" AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4546 $sql .=
" AND s.rowid = ".((int) $socid);
4549 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4551 if (is_object($excluser)) {
4552 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4554 $sql .= $this->
db->order($sortfield, $sortorder);
4555 $sql .= $this->
db->plimit($limit, $offset);
4557 $result = $this->
db->query($sql);
4559 $numc = $this->
db->num_rows($result);
4562 while ($i < $numc) {
4563 $obj = $this->
db->fetch_object($result);
4565 if ($shortlist == 1) {
4566 $ga[$obj->fid] = $obj->ref;
4567 } elseif ($shortlist == 2) {
4568 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4570 $ga[$i][
'id'] = $obj->fid;
4571 $ga[$i][
'ref'] = $obj->ref;
4572 $ga[$i][
'name'] = $obj->name;
4601 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4602 $sql .=
" ff.rowid as rowidnext";
4604 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4605 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4606 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4607 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4608 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4609 $sql .=
" AND f.paye = 0";
4610 $sql .=
" AND pf.fk_paiement IS NULL";
4611 $sql .=
" AND ff.fk_statut IS NULL";
4613 $sql .=
" AND f.fk_soc = ".((int) $socid);
4616 $sql .=
" ORDER BY f.ref";
4618 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4621 while ($obj = $this->
db->fetch_object(
$resql)) {
4622 $return[$obj->rowid] = array(
4623 'id' => $obj->rowid,
4625 'status' => $obj->status,
4626 'paid' => $obj->paid,
4633 $this->error = $this->
db->error();
4656 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
4657 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4658 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4659 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4660 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4661 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4665 $sql .=
" AND ff.type IS NULL";
4666 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4668 if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4670 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4671 $sql .=
'(SELECT MAX(fs.rowid)';
4672 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4673 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4674 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4675 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4677 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4679 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4682 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4686 $sql .=
" AND f.fk_soc = ".((int) $socid);
4688 $sql .=
" ORDER BY f.ref";
4690 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4693 while ($obj = $this->
db->fetch_object(
$resql)) {
4695 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4698 if ($obj->fk_statut == self::STATUS_CLOSED) {
4703 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4704 $return[$obj->rowid] = array(
'ref'=>$obj->ref,
'status'=>$obj->fk_statut,
'type'=>$obj->type,
'paye'=>$obj->paye,
'paymentornot'=>$paymentornot);
4710 $this->error = $this->
db->error();
4726 global $conf, $langs;
4730 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
4731 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4732 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4733 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4734 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4737 $sql .= $clause.
" f.paye=0";
4738 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4739 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
4741 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
4746 $langs->load(
"bills");
4750 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4751 $response->label = $langs->trans(
"CustomerBillsUnpaid");
4752 $response->labelShort = $langs->trans(
"Unpaid");
4753 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4756 $generic_facture =
new Facture($this->
db);
4758 while ($obj = $this->
db->fetch_object(
$resql)) {
4759 $generic_facture->date_lim_reglement = $this->
db->jdate($obj->datefin);
4760 $generic_facture->statut = $obj->fk_statut;
4762 $response->nbtodo++;
4763 $response->total += $obj->total_ht;
4765 if ($generic_facture->hasDelay()) {
4766 $response->nbtodolate++;
4767 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4775 $this->error = $this->
db->error();
4814 global $conf, $langs, $user;
4818 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
4823 $sql =
"SELECT rowid";
4824 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
4825 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
4826 $sql .= $this->
db->plimit(100);
4830 $num_prods = $this->
db->num_rows(
$resql);
4832 while ($i < $num_prods) {
4834 $row = $this->
db->fetch_row(
$resql);
4835 $prodids[$i] = $row[0];
4839 if (empty($num_prods)) {
4846 $this->
ref =
'SPECIMEN';
4847 $this->specimen = 1;
4849 $this->date = $nownotime;
4850 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4851 $this->cond_reglement_id = 1;
4852 $this->cond_reglement_code =
'RECEP';
4854 $this->mode_reglement_id = 0;
4855 $this->mode_reglement_code =
'';
4857 $this->note_public =
'This is a comment (public)';
4858 $this->note_private =
'This is a comment (private)';
4859 $this->note =
'This is a comment (private)';
4861 $this->fk_user_author = $user->id;
4863 $this->multicurrency_tx = 1;
4864 $this->multicurrency_code = $conf->currency;
4866 $this->fk_incoterms = 0;
4867 $this->location_incoterms =
'';
4869 if (empty($option) || $option !=
'nolines') {
4873 while ($xnbp < $nbp) {
4875 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
4877 $line->subprice = 100;
4878 $line->tva_tx = 19.6;
4879 $line->localtax1_tx = 0;
4880 $line->localtax2_tx = 0;
4881 $line->remise_percent = 0;
4883 $prodid = mt_rand(1, $num_prods);
4884 $line->fk_product = $prodids[$prodid];
4886 $line->total_ht = -100;
4887 $line->total_ttc = -119.6;
4888 $line->total_tva = -19.6;
4889 $line->multicurrency_total_ht = -200;
4890 $line->multicurrency_total_ttc = -239.2;
4891 $line->multicurrency_total_tva = -39.2;
4892 } elseif ($xnbp == 2) {
4893 $line->subprice = -100;
4894 $line->total_ht = -100;
4895 $line->total_ttc = -119.6;
4896 $line->total_tva = -19.6;
4897 $line->remise_percent = 0;
4898 $line->multicurrency_total_ht = -200;
4899 $line->multicurrency_total_ttc = -239.2;
4900 $line->multicurrency_total_tva = -39.2;
4901 } elseif ($xnbp == 3) {
4902 $prodid = mt_rand(1, $num_prods);
4903 $line->fk_product = $prodids[$prodid];
4904 $line->total_ht = 50;
4905 $line->total_ttc = 59.8;
4906 $line->total_tva = 9.8;
4907 $line->multicurrency_total_ht = 100;
4908 $line->multicurrency_total_ttc = 119.6;
4909 $line->multicurrency_total_tva = 19.6;
4910 $line->remise_percent = 50;
4913 $prodid = mt_rand(1, $num_prods);
4914 $line->fk_product = $prodids[$prodid];
4915 $line->total_ht = 100;
4916 $line->total_ttc = 119.6;
4917 $line->total_tva = 19.6;
4918 $line->multicurrency_total_ht = 200;
4919 $line->multicurrency_total_ttc = 239.2;
4920 $line->multicurrency_total_tva = 39.2;
4921 $line->remise_percent = 0;
4924 $this->lines[$xnbp] = $line;
4927 $this->total_ht += $line->total_ht;
4928 $this->total_tva += $line->total_tva;
4929 $this->total_ttc += $line->total_ttc;
4931 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4932 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4933 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4937 $this->revenuestamp = 0;
4941 $line->desc = $langs->trans(
"Description").
" (offered line)";
4943 $line->subprice = 100;
4944 $line->tva_tx = 19.6;
4945 $line->localtax1_tx = 0;
4946 $line->localtax2_tx = 0;
4947 $line->remise_percent = 100;
4948 $line->total_ht = 0;
4949 $line->total_ttc = 0;
4950 $line->total_tva = 0;
4951 $line->multicurrency_total_ht = 0;
4952 $line->multicurrency_total_ttc = 0;
4953 $line->multicurrency_total_tva = 0;
4954 $prodid = mt_rand(1, $num_prods);
4955 $line->fk_product = $prodids[$prodid];
4957 $this->lines[$xnbp] = $line;
4971 global $conf, $user;
4973 $this->nb = array();
4977 $sql =
"SELECT count(f.rowid) as nb";
4978 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4979 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
4980 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4981 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4982 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4985 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
4989 while ($obj = $this->
db->fetch_object(
$resql)) {
4990 $this->nb[
"invoices"] = $obj->nb;
4996 $this->error = $this->
db->error();
5022 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5024 global $conf, $langs;
5026 $outputlangs->loadLangs(array(
"bills",
"products"));
5030 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5032 if (!empty($this->model_pdf)) {
5033 $modele = $this->model_pdf;
5034 } elseif (!empty($this->modelpdf)) {
5035 $modele = $this->modelpdf;
5036 } elseif (!empty($conf->global->$thisTypeConfName)) {
5037 $modele = $conf->global->$thisTypeConfName;
5038 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
5039 $modele = $conf->global->FACTURE_ADDON_PDF;
5043 $modelpath =
"core/modules/facture/doc/";
5045 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5055 $sql =
'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.
'facture as f';
5056 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5059 if ($this->
db->num_rows(
$resql) > 0) {
5060 $res = $this->
db->fetch_array(
$resql);
5061 $ref = $res[
'max(situation_cycle_ref)'];
5069 $this->error = $this->
db->lasterror();
5070 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5084 return ($this->situation_counter == 1);
5098 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5099 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5100 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5101 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5105 while ($row = $this->
db->fetch_object(
$resql)) {
5108 $situation->fetch($id);
5109 $res[] = $situation;
5112 $this->error = $this->
db->error();
5113 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5133 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5138 $this->errors[] = $this->
db->error();
5142 if (!$notrigger && empty($error)) {
5152 $this->
db->commit();
5155 foreach ($this->errors as $errmsg) {
5156 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5157 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5159 $this->
db->rollback();
5175 if (!empty($this->situation_cycle_ref)) {
5177 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5178 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5179 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5183 $res = $this->
db->fetch_array(
$resql);
5184 $last = $res[
'max(situation_counter)'];
5185 return ($last == $this->situation_counter);
5187 $this->error = $this->
db->lasterror();
5188 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5246 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5247 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5249 $totalpaid = floatval($totalpaid);
5251 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5252 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5254 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5277 $displayWarranty =
false;
5278 if (!empty($this->retained_warranty)) {
5279 $displayWarranty =
true;
5283 $displayWarranty =
false;
5284 if (!empty($this->situation_final)) {
5285 $displayWarranty =
true;
5288 $displayWarranty =
true;
5290 foreach ($this->lines as $i => $line) {
5291 if ($line->product_type < 2 && $line->situation_percent < 100) {
5292 $displayWarranty =
false;
5300 return $displayWarranty;
5310 if (empty($this->retained_warranty)) {
5314 $retainedWarrantyAmount = 0;
5318 $displayWarranty =
true;
5320 if (!empty($this->lines)) {
5321 foreach ($this->lines as $i => $line) {
5322 if ($line->product_type < 2 && $line->situation_percent < 100) {
5323 $displayWarranty =
false;
5329 if ($displayWarranty && !empty($this->situation_final)) {
5331 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5334 foreach ($TPreviousIncoice as &$fac) {
5335 $total2BillWT += $fac->total_ttc;
5337 $total2BillWT += $this->total_ttc;
5339 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5345 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5348 if ($rounding < 0) {
5349 $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5352 if ($rounding > 0) {
5353 return round($retainedWarrantyAmount, $rounding);
5356 return $retainedWarrantyAmount;
5367 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5369 if ($this->statut >= 0) {
5370 $fieldname =
'retained_warranty';
5371 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5372 $sql .=
" SET ".$fieldname.
" = ".((
float) $value);
5373 $sql .=
' WHERE rowid='.((int) $this->
id);
5375 if ($this->
db->query($sql)) {
5376 $this->retained_warranty = floatval($value);
5379 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5380 $this->error = $this->
db->error();
5384 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5385 $this->error =
'Status of the object is incompatible '.$this->statut;
5400 if (!$timestamp && $dateYmd) {
5401 $timestamp = $this->
db->jdate($dateYmd);
5405 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5406 if ($this->statut >= 0) {
5407 $fieldname =
'retained_warranty_date_limit';
5408 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5409 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5410 $sql .=
' WHERE rowid = '.((int) $this->
id);
5412 if ($this->
db->query($sql)) {
5413 $this->retained_warranty_date_limit = $timestamp;
5416 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5417 $this->error = $this->
db->error();
5421 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5422 $this->error =
'Status of the object is incompatible '.$this->statut;
5440 global $conf, $langs, $user;
5446 $errorsMsg = array();
5448 $langs->load(
"bills");
5451 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5461 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5462 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5463 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5474 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5475 if (!empty($paymentmode) && $paymentmode !=
'all') {
5476 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5478 $sql .=
" WHERE f.paye = 0";
5479 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5480 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5481 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
5482 if (!empty($paymentmode) && $paymentmode !=
'all') {
5483 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5486 $sql .= $this->
db->order(
"date_lim_reglement",
"ASC");
5491 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5492 if (!empty($paymentmode) && $paymentmode !=
'all') {
5493 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5495 $this->output .=
'<br>';
5498 while ($obj = $this->
db->fetch_object(
$resql)) {
5501 $res = $tmpinvoice->fetch($obj->id);
5503 $tmpinvoice->fetch_thirdparty();
5505 $outputlangs =
new Translate(
'', $conf);
5506 if ($tmpinvoice->thirdparty->default_lang) {
5507 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5508 $outputlangs->loadLangs(array(
"main",
"bills"));
5510 $outputlangs = $langs;
5514 $arraymessage = $formmail->getEMailTemplate($this->
db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5515 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5516 $langs->load(
"errors");
5517 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5530 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5533 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5539 if ($forcerecipient) {
5540 $to = array($forcerecipient);
5542 $res = $tmpinvoice->fetch_thirdparty();
5543 $recipient = $tmpinvoice->thirdparty;
5545 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
5546 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5547 foreach ($tmparraycontact as $data_email) {
5548 if (!empty($data_email[
'email'])) {
5549 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
5553 if (empty($to) && !empty($recipient->email)) {
5554 $to[] = $recipient->email;
5557 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
5561 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5568 if (!empty($arraymessage->email_from)) {
5569 $from = $arraymessage->email_from;
5572 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5576 if (!$error && !empty($to)) {
5579 $to = implode(
',', $to);
5580 if (!empty($arraymessage->email_to)) {
5581 $to = $to.
','.$arraymessage->email_to;
5585 $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
5587 $trackid =
'inv'.$tmpinvoice->id;
5588 $sendcontext =
'standard';
5591 if (!empty($arraymessage->email_tocc)) {
5592 $email_tocc = $arraymessage->email_tocc;
5596 if (!empty($arraymessage->email_tobcc)) {
5597 $email_tobcc = $arraymessage->email_tobcc;
5604 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5605 $joinFile[] = DOL_DATA_ROOT.$tmpinvoice->last_main_doc;
5606 $joinFileName[] = basename($tmpinvoice->last_main_doc);
5607 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.$tmpinvoice->last_main_doc);
5611 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5614 if ($cMailFile->sendfile()) {
5618 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5623 $actioncomm->type_code =
'AC_OTH_AUTO';
5624 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5625 $actioncomm->contact_id = 0;
5627 $actioncomm->code =
'AC_EMAIL';
5628 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK';
5629 $actioncomm->note_private = $sendContent;
5630 $actioncomm->fk_project = $tmpinvoice->fk_project;
5631 $actioncomm->datep =
dol_now();
5632 $actioncomm->datef = $actioncomm->datep;
5633 $actioncomm->percentage = -1;
5634 $actioncomm->authorid = $user->id;
5635 $actioncomm->userownerid = $user->id;
5637 $actioncomm->email_msgid = $cMailFile->msgid;
5638 $actioncomm->email_from = $from;
5639 $actioncomm->email_sender =
'';
5640 $actioncomm->email_to = $to;
5644 $actioncomm->errors_to = $errors_to;
5646 $actioncomm->elementtype =
'invoice';
5647 $actioncomm->fk_element = $tmpinvoice->id;
5651 $actioncomm->create($user);
5653 $errormesg = $cMailFile->error.
' : '.$to;
5657 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5662 $actioncomm->type_code =
'AC_OTH_AUTO';
5663 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5664 $actioncomm->contact_id = 0;
5666 $actioncomm->code =
'AC_EMAIL';
5667 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5668 $actioncomm->note_private = $errormesg;
5669 $actioncomm->fk_project = $tmpinvoice->fk_project;
5670 $actioncomm->datep =
dol_now();
5671 $actioncomm->datef = $actioncomm->datep;
5672 $actioncomm->percentage = -1;
5673 $actioncomm->authorid = $user->id;
5674 $actioncomm->userownerid = $user->id;
5676 $actioncomm->email_msgid = $cMailFile->msgid;
5677 $actioncomm->email_from = $from;
5678 $actioncomm->email_sender =
'';
5679 $actioncomm->email_to = $to;
5683 $actioncomm->errors_to = $errors_to;
5687 $actioncomm->create($user);
5690 $this->
db->commit();
5694 $errorsMsg[] = $errormesg;
5697 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
5707 $this->output .=
'Nb of emails sent : '.$nbMailSend;
5710 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg)) ? join(
', ', $errorsMsg) : $error;
5724 $sql =
"SELECT datef";
5725 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
5726 $sql .=
" WHERE type = " . (int) $this->
type ;
5727 $sql .=
" AND date_valid IS NOT NULL";
5728 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
5729 $sql .=
" ORDER BY datef DESC LIMIT 1";
5731 $result = $this->
db->query($sql);
5734 if ($this->
db->num_rows($result)) {
5735 $obj = $this->
db->fetch_object($result);
5736 $last_date = $this->
db->jdate($obj->datef);
5737 $invoice_date = $this->date;
5739 $is_last_of_same_type = $invoice_date >= $last_date;
5740 if ($allow_validated_drafts) {
5741 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->
ref,
'PROV') && $this->status ==
self::STATUS_DRAFT);
5744 return array($is_last_of_same_type, $last_date);
5764 public $element =
'facturedet';
5769 public $table_element =
'facturedet';
5783 public $localtax1_type;
5784 public $localtax2_type;
5785 public $fk_remise_except;
5788 public $fk_fournprice;
5793 public $remise_percent;
5795 public $special_code;
5803 public $fk_code_ventilation = 0;
5808 public $skip_update_total;
5813 public $situation_percent;
5821 public $fk_multicurrency;
5822 public $multicurrency_code;
5823 public $multicurrency_subprice;
5824 public $multicurrency_total_ht;
5825 public $multicurrency_total_tva;
5826 public $multicurrency_total_ttc;
5836 $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,';
5837 $sql .=
' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
5838 $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,';
5839 $sql .=
' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
5840 $sql .=
' fd.fk_code_ventilation,';
5841 $sql .=
' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
5842 $sql .=
' fd.situation_percent, fd.fk_prev_id,';
5843 $sql .=
' fd.multicurrency_subprice,';
5844 $sql .=
' fd.multicurrency_total_ht,';
5845 $sql .=
' fd.multicurrency_total_tva,';
5846 $sql .=
' fd.multicurrency_total_ttc,';
5847 $sql .=
' p.ref as product_ref, p.label as product_label, p.description as product_desc';
5848 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as fd';
5849 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON fd.fk_product = p.rowid';
5850 $sql .=
' WHERE fd.rowid = '.((int) $rowid);
5852 $result = $this->
db->query($sql);
5854 $objp = $this->
db->fetch_object($result);
5857 $this->error =
'InvoiceLine with id '. $rowid .
' not found sql='.$sql;
5861 $this->
rowid = $objp->rowid;
5862 $this->
id = $objp->rowid;
5863 $this->fk_facture = $objp->fk_facture;
5864 $this->fk_parent_line = $objp->fk_parent_line;
5865 $this->label = $objp->custom_label;
5866 $this->desc = $objp->description;
5867 $this->qty = $objp->qty;
5868 $this->subprice = $objp->subprice;
5869 $this->ref_ext = $objp->ref_ext;
5870 $this->vat_src_code = $objp->vat_src_code;
5871 $this->tva_tx = $objp->tva_tx;
5872 $this->localtax1_tx = $objp->localtax1_tx;
5873 $this->localtax2_tx = $objp->localtax2_tx;
5874 $this->remise_percent = $objp->remise_percent;
5875 $this->fk_remise_except = $objp->fk_remise_except;
5876 $this->fk_product = $objp->fk_product;
5877 $this->product_type = $objp->product_type;
5878 $this->date_start = $this->
db->jdate($objp->date_start);
5879 $this->date_end = $this->
db->jdate($objp->date_end);
5880 $this->info_bits = $objp->info_bits;
5881 $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
5882 $this->special_code = $objp->special_code;
5883 $this->total_ht = $objp->total_ht;
5884 $this->total_tva = $objp->total_tva;
5885 $this->total_localtax1 = $objp->total_localtax1;
5886 $this->total_localtax2 = $objp->total_localtax2;
5887 $this->total_ttc = $objp->total_ttc;
5888 $this->fk_code_ventilation = $objp->fk_code_ventilation;
5889 $this->rang = $objp->rang;
5890 $this->fk_fournprice = $objp->fk_fournprice;
5891 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
5892 $this->pa_ht = $marginInfos[0];
5893 $this->marge_tx = $marginInfos[1];
5894 $this->marque_tx = $marginInfos[2];
5896 $this->
ref = $objp->product_ref;
5898 $this->product_ref = $objp->product_ref;
5899 $this->product_label = $objp->product_label;
5900 $this->product_desc = $objp->product_desc;
5902 $this->fk_unit = $objp->fk_unit;
5903 $this->fk_user_modif = $objp->fk_user_modif;
5904 $this->fk_user_author = $objp->fk_user_author;
5906 $this->situation_percent = $objp->situation_percent;
5907 $this->fk_prev_id = $objp->fk_prev_id;
5909 $this->multicurrency_subprice = $objp->multicurrency_subprice;
5910 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
5911 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
5912 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
5914 $this->
db->free($result);
5918 $this->error = $this->
db->lasterror();
5930 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
5932 global $langs, $user, $conf;
5936 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
5938 dol_syslog(get_class($this).
"::insert rang=".$this->rang, LOG_DEBUG);
5941 $this->desc = trim($this->desc);
5942 if (empty($this->tva_tx)) {
5945 if (empty($this->localtax1_tx)) {
5946 $this->localtax1_tx = 0;
5948 if (empty($this->localtax2_tx)) {
5949 $this->localtax2_tx = 0;
5951 if (empty($this->localtax1_type)) {
5952 $this->localtax1_type = 0;
5954 if (empty($this->localtax2_type)) {
5955 $this->localtax2_type = 0;
5957 if (empty($this->total_localtax1)) {
5958 $this->total_localtax1 = 0;
5960 if (empty($this->total_localtax2)) {
5961 $this->total_localtax2 = 0;
5963 if (empty($this->rang)) {
5966 if (empty($this->remise_percent)) {
5967 $this->remise_percent = 0;
5969 if (empty($this->info_bits)) {
5970 $this->info_bits = 0;
5972 if (empty($this->subprice)) {
5973 $this->subprice = 0;
5975 if (empty($this->ref_ext)) {
5976 $this->ref_ext =
'';
5978 if (empty($this->special_code)) {
5979 $this->special_code = 0;
5981 if (empty($this->fk_parent_line)) {
5982 $this->fk_parent_line = 0;
5984 if (empty($this->fk_prev_id)) {
5985 $this->fk_prev_id = 0;
5987 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
5988 $this->situation_percent = 100;
5991 if (empty($this->pa_ht)) {
5994 if (empty($this->multicurrency_subprice)) {
5995 $this->multicurrency_subprice = 0;
5997 if (empty($this->multicurrency_total_ht)) {
5998 $this->multicurrency_total_ht = 0;
6000 if (empty($this->multicurrency_total_tva)) {
6001 $this->multicurrency_total_tva = 0;
6003 if (empty($this->multicurrency_total_ttc)) {
6004 $this->multicurrency_total_ttc = 0;
6008 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6009 if (($result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
6012 $this->pa_ht = $result;
6017 if ($this->product_type < 0) {
6018 $this->error =
'ErrorProductTypeMustBe0orMore';
6021 if (!empty($this->fk_product) && $this->fk_product > 0) {
6025 $this->error =
'ErrorProductIdDoesNotExists';
6026 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6034 $sql =
'INSERT INTO '.MAIN_DB_PREFIX.
'facturedet';
6035 $sql .=
' (fk_facture, fk_parent_line, label, description, qty,';
6036 $sql .=
' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6037 $sql .=
' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6038 $sql .=
' date_start, date_end, fk_code_ventilation, ';
6039 $sql .=
' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6040 $sql .=
' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6041 $sql .=
' situation_percent, fk_prev_id,';
6042 $sql .=
' fk_unit, fk_user_author, fk_user_modif,';
6043 $sql .=
' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
6045 $sql .=
" VALUES (".$this->fk_facture.
",";
6046 $sql .=
" ".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null").
",";
6047 $sql .=
" ".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null").
",";
6048 $sql .=
" '".$this->db->escape($this->desc).
"',";
6049 $sql .=
" ".price2num($this->qty).
",";
6050 $sql .=
" ".(empty($this->vat_src_code) ?
"''" :
"'".$this->db->escape($this->vat_src_code).
"'").
",";
6051 $sql .=
" ".price2num($this->tva_tx).
",";
6052 $sql .=
" ".price2num($this->localtax1_tx).
",";
6053 $sql .=
" ".price2num($this->localtax2_tx).
",";
6054 $sql .=
" '".$this->db->escape($this->localtax1_type).
"',";
6055 $sql .=
" '".$this->db->escape($this->localtax2_type).
"',";
6056 $sql .=
' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product :
"null").
',';
6057 $sql .=
" ".((int) $this->product_type).
",";
6058 $sql .=
" ".price2num($this->remise_percent).
",";
6059 $sql .=
" ".price2num($this->subprice).
",";
6060 $sql .=
" '".$this->db->escape($this->ref_ext).
"',";
6061 $sql .=
' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except :
"null").
',';
6062 $sql .=
" ".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null").
",";
6063 $sql .=
" ".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null").
",";
6064 $sql .=
' '.((int) $this->fk_code_ventilation).
',';
6065 $sql .=
' '.((int) $this->rang).
',';
6066 $sql .=
' '.((int) $this->special_code).
',';
6067 $sql .=
' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice :
"null").
',';
6068 $sql .=
' '.price2num($this->pa_ht).
',';
6069 $sql .=
" '".$this->db->escape($this->info_bits).
"',";
6070 $sql .=
" ".price2num($this->total_ht).
",";
6071 $sql .=
" ".price2num($this->total_tva).
",";
6072 $sql .=
" ".price2num($this->total_ttc).
",";
6073 $sql .=
" ".price2num($this->total_localtax1).
",";
6074 $sql .=
" ".price2num($this->total_localtax2);
6075 $sql .=
", ".((float) $this->situation_percent);
6076 $sql .=
", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id :
"null");
6077 $sql .=
", ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6078 $sql .=
", ".((int) $user->id);
6079 $sql .=
", ".((int) $user->id);
6080 $sql .=
", ".(int) $this->fk_multicurrency;
6081 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
6082 $sql .=
", ".price2num($this->multicurrency_subprice);
6083 $sql .=
", ".price2num($this->multicurrency_total_ht);
6084 $sql .=
", ".price2num($this->multicurrency_total_tva);
6085 $sql .=
", ".price2num($this->multicurrency_total_ttc);
6088 dol_syslog(get_class($this).
"::insert", LOG_DEBUG);
6091 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facturedet');
6092 $this->
rowid = $this->id;
6103 if ($this->fk_remise_except) {
6105 $result = $discount->fetch($this->fk_remise_except);
6110 if ($discount->fk_facture_line > 0) {
6111 if (empty($noerrorifdiscountalreadylinked)) {
6112 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed", $discount->id);
6113 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6114 $this->
db->rollback();
6118 $result = $discount->link_to_invoice($this->
rowid, 0);
6120 $this->error = $discount->error;
6121 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6122 $this->
db->rollback();
6127 $this->error = $langs->trans(
"ErrorADiscountThatHasBeenRemovedIsIncluded");
6128 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6129 $this->
db->rollback();
6133 $this->error = $discount->error;
6134 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6135 $this->
db->rollback();
6142 $result = $this->
call_trigger(
'LINEBILL_INSERT', $user);
6144 $this->
db->rollback();
6150 $this->
db->commit();
6153 $this->error = $this->
db->lasterror();
6154 $this->
db->rollback();
6166 public function update($user =
'', $notrigger = 0)
6168 global $user, $conf;
6172 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6175 $this->desc = trim($this->desc);
6176 if (empty($this->ref_ext)) {
6177 $this->ref_ext =
'';
6179 if (empty($this->tva_tx)) {
6182 if (empty($this->localtax1_tx)) {
6183 $this->localtax1_tx = 0;
6185 if (empty($this->localtax2_tx)) {
6186 $this->localtax2_tx = 0;
6188 if (empty($this->localtax1_type)) {
6189 $this->localtax1_type = 0;
6191 if (empty($this->localtax2_type)) {
6192 $this->localtax2_type = 0;
6194 if (empty($this->total_localtax1)) {
6195 $this->total_localtax1 = 0;
6197 if (empty($this->total_localtax2)) {
6198 $this->total_localtax2 = 0;
6200 if (empty($this->remise_percent)) {
6201 $this->remise_percent = 0;
6203 if (empty($this->info_bits)) {
6204 $this->info_bits = 0;
6206 if (empty($this->special_code)) {
6207 $this->special_code = 0;
6209 if (empty($this->product_type)) {
6210 $this->product_type = 0;
6212 if (empty($this->fk_parent_line)) {
6213 $this->fk_parent_line = 0;
6215 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6216 $this->situation_percent = 100;
6218 if (empty($this->pa_ht)) {
6222 if (empty($this->multicurrency_subprice)) {
6223 $this->multicurrency_subprice = 0;
6225 if (empty($this->multicurrency_total_ht)) {
6226 $this->multicurrency_total_ht = 0;
6228 if (empty($this->multicurrency_total_tva)) {
6229 $this->multicurrency_total_tva = 0;
6231 if (empty($this->multicurrency_total_ttc)) {
6232 $this->multicurrency_total_ttc = 0;
6236 if ($this->product_type < 0) {
6241 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6243 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6247 $this->pa_ht = $result;
6254 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6255 $sql .=
" description='".$this->db->escape($this->desc).
"'";
6256 $sql .=
", ref_ext='".$this->db->escape($this->ref_ext).
"'";
6257 $sql .=
", label=".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null");
6258 $sql .=
", subprice=".price2num($this->subprice);
6259 $sql .=
", remise_percent=".price2num($this->remise_percent);
6260 if ($this->fk_remise_except) {
6261 $sql .=
", fk_remise_except=".$this->fk_remise_except;
6263 $sql .=
", fk_remise_except=null";
6265 $sql .=
", vat_src_code = '".(empty($this->vat_src_code) ?
'' : $this->
db->escape($this->vat_src_code)).
"'";
6266 $sql .=
", tva_tx=".price2num($this->tva_tx);
6267 $sql .=
", localtax1_tx=".price2num($this->localtax1_tx);
6268 $sql .=
", localtax2_tx=".price2num($this->localtax2_tx);
6269 $sql .=
", localtax1_type='".$this->db->escape($this->localtax1_type).
"'";
6270 $sql .=
", localtax2_type='".$this->db->escape($this->localtax2_type).
"'";
6271 $sql .=
", qty=".price2num($this->qty);
6272 $sql .=
", date_start=".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null");
6273 $sql .=
", date_end=".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null");
6274 $sql .=
", product_type=".$this->product_type;
6275 $sql .=
", info_bits='".$this->db->escape($this->info_bits).
"'";
6276 $sql .=
", special_code='".$this->db->escape($this->special_code).
"'";
6277 if (empty($this->skip_update_total)) {
6278 $sql .=
", total_ht=".price2num($this->total_ht);
6279 $sql .=
", total_tva=".price2num($this->total_tva);
6280 $sql .=
", total_ttc=".price2num($this->total_ttc);
6281 $sql .=
", total_localtax1=".price2num($this->total_localtax1);
6282 $sql .=
", total_localtax2=".price2num($this->total_localtax2);
6284 $sql .=
", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ?
"'".$this->db->escape($this->fk_fournprice).
"'" :
"null");
6285 $sql .=
", buy_price_ht=".(($this->pa_ht || (string) $this->pa_ht ===
'0') ?
price2num($this->pa_ht) :
"null");
6286 $sql .=
", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null");
6287 if (!empty($this->rang)) {
6288 $sql .=
", rang=".((int) $this->rang);
6290 $sql .=
", situation_percent = ".((float) $this->situation_percent);
6291 $sql .=
", fk_unit = ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6292 $sql .=
", fk_user_modif = ".((int) $user->id);
6295 $sql .=
", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6296 $sql .=
", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6297 $sql .=
", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6298 $sql .=
", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6300 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6302 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
6306 $this->
id = $this->rowid;
6313 if (!$error && !$notrigger) {
6315 $result = $this->
call_trigger(
'LINEBILL_MODIFY', $user);
6317 $this->
db->rollback();
6322 $this->
db->commit();
6325 $this->error = $this->
db->error();
6326 $this->
db->rollback();
6338 public function delete($tmpuser =
null, $notrigger =
false)
6345 if (empty($notrigger)) {
6346 $result = $this->
call_trigger(
'LINEBILL_DELETE', $user);
6348 $this->
db->rollback();
6357 $this->
db->rollback();
6361 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->
rowid);
6363 if ($this->
db->query($sql)) {
6364 $this->
db->commit();
6367 $this->error = $this->
db->error().
" sql=".$sql;
6368 $this->
db->rollback();
6384 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6387 if (empty($this->total_localtax1)) {
6388 $this->total_localtax1 = 0;
6390 if (empty($this->total_localtax2)) {
6391 $this->total_localtax2 = 0;
6395 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6396 $sql .=
" total_ht=".price2num($this->total_ht).
"";
6397 $sql .=
",total_tva=".price2num($this->total_tva).
"";
6398 $sql .=
",total_localtax1=".price2num($this->total_localtax1).
"";
6399 $sql .=
",total_localtax2=".price2num($this->total_localtax2).
"";
6400 $sql .=
",total_ttc=".price2num($this->total_ttc).
"";
6401 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6403 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6407 $this->
db->commit();
6410 $this->error = $this->
db->error();
6411 $this->
db->rollback();
6428 global $invoicecache;
6430 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6434 if (!isset($invoicecache[$invoiceid])) {
6435 $invoicecache[$invoiceid] =
new Facture($this->
db);
6436 $invoicecache[$invoiceid]->fetch($invoiceid);
6442 $sql =
"SELECT situation_percent FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->fk_prev_id);
6445 $res = $this->
db->fetch_array(
$resql);
6447 $returnPercent = floatval($res[
'situation_percent']);
6449 if ($include_credit_note) {
6450 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6451 $sql .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6452 $sql .=
" WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6453 $sql .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6454 $sql .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6456 $res = $this->
db->query($sql);
6458 while ($obj = $this->
db->fetch_object($res)) {
6459 $returnPercent = $returnPercent + floatval($obj->situation_percent);
6466 return $returnPercent;
6468 $this->error = $this->
db->error();
6469 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6470 $this->
db->rollback();
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoices classes.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
Parent class of all other business classes for details of elements (invoices, contracts,...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
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...
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
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).
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage shipments.
Class to manage invoices.
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
setDraft($user, $idwarehouse=-1)
Set draft status.
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $forcerecipient='')
Send reminders by emails for invoices that are due CAN BE A CRON TASK.
$fk_facture_source
id of source invoice if replacement invoice or credit note
getIdShippingContact()
Retourne id des contacts clients de livraison.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
deleteline($rowid)
Delete line in database.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
fetch($rowid, $ref='', $ref_ext='', $notused='', $fetch_situation=false)
Get object from database.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
load_state_board()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines.
update(User $user, $notrigger=0)
Update database.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this->lines.
$fk_fac_rec_source
id of template invoice when generated from a template invoice
getIdBillingContact()
Retourne id des contacts clients de facturation.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
setRetainedWarrantyDateLimit($timestamp, $dateYmd=false)
Change the retained_warranty_date_limit.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
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)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
$paye
1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code)
updatePriceNextInvoice(&$langs)
Update price of next invoice.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
$pos_source
key of pos source ('0', '1', ...)
info($id)
Load miscellaneous information for tab "Info".
const TYPE_PROFORMA
Proforma invoice (should not be used.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setRetainedWarranty($value)
Change the retained warranty.
get_prev_sits()
Returns an array containing the previous situations as Facture objects.
set_remise_absolue($user, $remise, $notrigger=0)
Set absolute discount.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
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.
newCycle()
Gets the smallest reference available for a new cycle.
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.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getNextNumRef($soc, $mode='next')
Return next reference of customer invoice not already used (or last reference) according to numbering...
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
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).
const STATUS_VALIDATED
Validated (need to be paid)
hasDelay()
Is the customer invoice delayed?
getLinesArray()
Create an array of invoice lines.
set_unpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
const TYPE_DEPOSIT
Deposit invoice.
set_paid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
const STATUS_ABANDONED
Classified abandoned and no payment done.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
setPaid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed.
const TYPE_CREDIT_NOTE
Credit note invoice.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
initAsSpecimen($option='')
Initialise an instance with random values.
getRetainedWarrantyAmount($rounding=-1)
create(User $user, $notrigger=0, $forceduedate=0)
Create invoice in database.
$module_source
key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos',...
setUnpaid($user)
Tag la facture comme non payee completement + appel trigger BILL_UNPAYED Fonction utilisee quand un p...
const STATUS_CLOSED
Classified paid.
Class to manage invoice lines.
$fk_parent_line
Id parent line.
insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
Insert line into database.
get_prev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of the previous line.
fetch($rowid)
Load invoice line from database.
update($user='', $notrigger=0)
Update line into database.
$fk_facture
From llx_facturedet Id facture.
update_total()
Update DB line fields total_xxx Used by migration.
Class to manage invoice templates.
Class to manage stock movements.
static getIdFromCode($dbs, $code)
Get id of currency from code.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("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->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
dol_get_next_month($month, $year)
Return next month.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
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)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
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.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isModEnabled($module)
Is Dolibarr module enabled.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $paht)
Return an array with margins information of a line.
div float
Buy price without taxes.
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.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
$conf db
API class for accounts.