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_user_author' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'enabled'=>1,
'visible'=>-1,
'position'=>165),
335 'fk_user_modif' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'enabled'=>1,
'visible'=>-2,
'notnull'=>-1,
'position'=>166),
336 'fk_user_valid' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>167),
337 'fk_user_closing' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserClosing',
'enabled'=>1,
'visible'=>-1,
'position'=>168),
338 'fk_facture_source' =>array(
'type'=>
'integer',
'label'=>
'SourceInvoice',
'enabled'=>1,
'visible'=>-1,
'position'=>170),
339 'fk_projet' =>array(
'type'=>
'integer:Project:projet/class/project.class.php:1:fk_statut=1',
'label'=>
'Project',
'enabled'=>1,
'visible'=>-1,
'position'=>175),
340 'fk_account' =>array(
'type'=>
'integer',
'label'=>
'Fk account',
'enabled'=>1,
'visible'=>-1,
'position'=>180),
341 'fk_currency' =>array(
'type'=>
'varchar(3)',
'label'=>
'CurrencyCode',
'enabled'=>1,
'visible'=>-1,
'position'=>185),
342 'fk_cond_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentTerm',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>190),
343 'fk_mode_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentMode',
'enabled'=>1,
'visible'=>-1,
'position'=>195),
344 'note_private' =>array(
'type'=>
'text',
'label'=>
'NotePrivate',
'enabled'=>1,
'visible'=>0,
'position'=>205),
345 'note_public' =>array(
'type'=>
'text',
'label'=>
'NotePublic',
'enabled'=>1,
'visible'=>0,
'position'=>210),
346 'model_pdf' =>array(
'type'=>
'varchar(255)',
'label'=>
'Model pdf',
'enabled'=>1,
'visible'=>0,
'position'=>215),
347 'extraparams' =>array(
'type'=>
'varchar(255)',
'label'=>
'Extraparams',
'enabled'=>1,
'visible'=>-1,
'position'=>225),
348 'situation_cycle_ref' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation cycle ref',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>230),
349 'situation_counter' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation counter',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>235),
350 'situation_final' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation final',
'enabled'=>
'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1',
'visible'=>-1,
'position'=>240),
351 'retained_warranty' =>array(
'type'=>
'double',
'label'=>
'Retained warranty',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>245),
352 'retained_warranty_date_limit' =>array(
'type'=>
'date',
'label'=>
'Retained warranty date limit',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>250),
353 '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),
354 'fk_incoterms' =>array(
'type'=>
'integer',
'label'=>
'IncotermCode',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>260),
355 'location_incoterms' =>array(
'type'=>
'varchar(255)',
'label'=>
'IncotermLabel',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>265),
356 'date_pointoftax' =>array(
'type'=>
'date',
'label'=>
'DatePointOfTax',
'enabled'=>
'$conf->global->INVOICE_POINTOFTAX_DATE',
'visible'=>-1,
'position'=>270),
357 'fk_multicurrency' =>array(
'type'=>
'integer',
'label'=>
'MulticurrencyID',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>275),
358 'multicurrency_code' =>array(
'type'=>
'varchar(255)',
'label'=>
'Currency',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>280),
359 'multicurrency_tx' =>array(
'type'=>
'double(24,8)',
'label'=>
'CurrencyRate',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>285,
'isameasure'=>1),
360 'multicurrency_total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountHT',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>290,
'isameasure'=>1),
361 'multicurrency_total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountVAT',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>291,
'isameasure'=>1),
362 'multicurrency_total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountTTC',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>292,
'isameasure'=>1),
363 'fk_fac_rec_source' =>array(
'type'=>
'integer',
'label'=>
'RecurringInvoiceSource',
'enabled'=>1,
'visible'=>-1,
'position'=>305),
364 'last_main_doc' =>array(
'type'=>
'varchar(255)',
'label'=>
'LastMainDoc',
'enabled'=>1,
'visible'=>-1,
'position'=>310),
365 'module_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSModule',
'enabled'=>1,
'visible'=>-1,
'position'=>315),
366 'pos_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSTerminal',
'enabled'=>1,
'visible'=>-1,
'position'=>320),
367 'datec' =>array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'enabled'=>1,
'visible'=>-1,
'position'=>500),
368 'tms' =>array(
'type'=>
'timestamp',
'label'=>
'DateModificationShort',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>500),
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);
522 $originaldatewhen =
null;
523 $nextdatewhen =
null;
524 $previousdaynextdatewhen =
null;
527 if ($this->fac_rec > 0) {
528 $this->fk_fac_rec_source = $this->fac_rec;
530 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
532 $result = $_facrec->fetch($this->fac_rec);
533 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
536 $originaldatewhen = $_facrec->date_when;
537 $nextdatewhen =
null; $previousdaynextdatewhen =
null;
538 if ($originaldatewhen) {
539 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
543 if (!empty($_facrec->frequency)) {
544 $this->socid = $_facrec->socid;
546 $this->entity = $_facrec->entity;
549 $this->fk_project =
GETPOST(
'projectid',
'int') > 0 ? ((int)
GETPOST(
'projectid',
'int')) : $_facrec->fk_project;
550 $this->note_public =
GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
551 $this->note_private =
GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
552 $this->model_pdf =
GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
553 $this->cond_reglement_id =
GETPOST(
'cond_reglement_id',
'int') > 0 ? ((int)
GETPOST(
'cond_reglement_id',
'int')) : $_facrec->cond_reglement_id;
554 $this->mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int') > 0 ? ((int)
GETPOST(
'mode_reglement_id',
'int')) : $_facrec->mode_reglement_id;
555 $this->fk_account =
GETPOST(
'fk_account') > 0 ? ((int)
GETPOST(
'fk_account')) : $_facrec->fk_account;
558 $this->total_ht = $_facrec->total_ht;
559 $this->total_ttc = $_facrec->total_ttc;
562 $this->remise_absolue = $_facrec->remise_absolue;
563 $this->remise_percent = $_facrec->remise_percent;
564 $this->fk_incoterms = $_facrec->fk_incoterms;
565 $this->location_incoterms = $_facrec->location_incoterms;
571 $this->ref_client = trim($this->ref_client);
572 $this->note_public = trim($this->note_public);
573 $this->note_private = trim($this->note_private);
574 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
576 $this->array_options = $_facrec->array_options;
578 if (!$this->mode_reglement_id) {
579 $this->mode_reglement_id = 0;
581 $this->brouillon = 1;
585 $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($now).
"'";
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_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,
1054 $_facrec->lines[$i]->situation_percent,
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;
1162 $facture->lines = $this->lines;
1163 $facture->situation_counter = $this->situation_counter;
1164 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1165 $facture->situation_final = $this->situation_final;
1167 $facture->retained_warranty = $this->retained_warranty;
1168 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1169 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1171 $facture->fk_user_author = $user->id;
1175 foreach ($facture->lines as $i => $tmpline) {
1176 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1177 if ($invertdetail) {
1178 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1179 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1180 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1181 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1182 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1183 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1184 $facture->lines[$i]->ref_ext =
'';
1188 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1190 $facid = $facture->create($user);
1192 $this->error = $facture->error;
1193 $this->errors = $facture->errors;
1194 } elseif ($this->
type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
1197 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1198 foreach ($Tfk_object as $fk_object) {
1199 $facture->add_object_linked($typeObject, $fk_object);
1203 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1219 global $conf, $hookmanager;
1227 $object->fetch($fromid);
1230 $objFrom = clone $object;
1233 if (!empty($this->socid) && $this->socid != $object->socid) {
1236 if ($objsoc->fetch($this->socid) > 0) {
1237 $object->socid = $objsoc->id;
1238 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1239 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1240 $object->fk_project =
'';
1241 $object->fk_delivery_address =
'';
1252 $object->date = (empty($this->date) ?
dol_now() : $this->date);
1253 $object->user_author = $user->id;
1254 $object->user_valid =
null;
1255 $object->fk_user_author = $user->id;
1256 $object->fk_user_valid =
null;
1257 $object->fk_facture_source = 0;
1258 $object->date_creation =
'';
1259 $object->date_modification =
'';
1260 $object->date_validation =
'';
1261 $object->ref_client =
'';
1262 $object->close_code =
'';
1263 $object->close_note =
'';
1264 if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) {
1265 $object->note_private =
'';
1266 $object->note_public =
'';
1270 foreach ($object->lines as $i => $line) {
1271 if (($object->lines[$i]->info_bits & 0x02) == 0x02) {
1272 unset($object->lines[$i]);
1278 if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
1290 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1291 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1295 $object->lines[$i]->date_start = $newFirst;
1296 $object->lines[$i]->date_end = $newLast;
1300 $object->lines[$i]->ref_ext =
'';
1304 $object->context[
'createfromclone'] =
'createfromclone';
1305 $result = $object->create($user);
1308 $this->error = $object->error;
1309 $this->errors = $object->errors;
1312 if ($object->copy_linked_contact($objFrom,
'internal') < 0) {
1314 $this->error = $object->error;
1315 $this->errors = $object->errors;
1316 } elseif ($object->socid == $objFrom->socid) {
1318 if ($object->copy_linked_contact($objFrom,
'external') < 0) {
1320 $this->error = $object->error;
1321 $this->errors = $object->errors;
1328 if (is_object($hookmanager)) {
1329 $parameters = array(
'objFrom'=>$objFrom);
1331 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $object, $action);
1338 unset($object->context[
'createfromclone']);
1342 $this->
db->commit();
1345 $this->
db->rollback();
1359 global $conf, $hookmanager;
1367 $num = count($object->lines);
1368 for ($i = 0; $i < $num; $i++) {
1371 $line->libelle = $object->lines[$i]->libelle;
1372 $line->label = $object->lines[$i]->label;
1373 $line->desc = $object->lines[$i]->desc;
1374 $line->subprice = $object->lines[$i]->subprice;
1375 $line->total_ht = $object->lines[$i]->total_ht;
1376 $line->total_tva = $object->lines[$i]->total_tva;
1377 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1378 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1379 $line->total_ttc = $object->lines[$i]->total_ttc;
1380 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1381 $line->tva_tx = $object->lines[$i]->tva_tx;
1382 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1383 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1384 $line->qty = $object->lines[$i]->qty;
1385 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1386 $line->remise_percent = $object->lines[$i]->remise_percent;
1387 $line->fk_product = $object->lines[$i]->fk_product;
1388 $line->info_bits = $object->lines[$i]->info_bits;
1389 $line->product_type = $object->lines[$i]->product_type;
1390 $line->rang = $object->lines[$i]->rang;
1391 $line->special_code = $object->lines[$i]->special_code;
1392 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1393 $line->fk_unit = $object->lines[$i]->fk_unit;
1394 $line->date_start = $object->lines[$i]->date_start;
1395 $line->date_end = $object->lines[$i]->date_end;
1398 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1399 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1400 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1401 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1402 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1403 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1405 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1406 $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);
1407 $line->pa_ht = $marginInfos[0];
1410 $object->lines[$i]->fetch_optionals();
1411 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1412 $line->array_options[$options_key] = $value;
1415 $this->lines[$i] = $line;
1418 $this->socid = $object->socid;
1419 $this->fk_project = $object->fk_project;
1420 $this->fk_account = $object->fk_account;
1421 $this->cond_reglement_id = $object->cond_reglement_id;
1422 $this->mode_reglement_id = $object->mode_reglement_id;
1423 $this->availability_id = $object->availability_id;
1424 $this->demand_reason_id = $object->demand_reason_id;
1425 $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
1426 $this->date_livraison = $object->delivery_date;
1427 $this->fk_delivery_address = $object->fk_delivery_address;
1428 $this->contact_id = $object->contact_id;
1429 $this->ref_client = $object->ref_client;
1431 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1432 $this->note_private = $object->note_private;
1433 $this->note_public = $object->note_public;
1436 $this->module_source = $object->module_source;
1437 $this->pos_source = $object->pos_source;
1439 $this->origin = $object->element;
1440 $this->origin_id = $object->id;
1442 $this->fk_user_author = $user->id;
1445 $object->fetch_optionals();
1446 foreach ($object->array_options as $options_key => $value) {
1447 $this->array_options[$options_key] = $value;
1451 $this->linked_objects[$this->origin] = $this->origin_id;
1452 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1453 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1456 $ret = $this->
create($user);
1460 $hookmanager->initHooks(array(
'invoicedao'));
1462 $parameters = array(
'objFrom'=>$object);
1464 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1493 global $conf, $langs, $hookmanager, $action;
1495 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1496 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1501 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1505 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1507 if ($date > (
dol_get_last_hour(
dol_now(
'tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1508 $origin->error =
'ErrorDateIsInFuture';
1512 if ($payment_terms_id <= 0) {
1513 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1517 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1519 if (empty($payment_conditions_deposit_percent)) {
1520 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1524 if (empty($origin->deposit_percent)) {
1525 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1529 $deposit =
new self($origin->db);
1530 $deposit->socid = $origin->socid;
1532 $deposit->fk_project = $origin->fk_project;
1533 $deposit->ref_client = $origin->ref_client;
1534 $deposit->date = $date;
1535 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1536 $deposit->cond_reglement_id = $payment_terms_id;
1537 $deposit->availability_id = $origin->availability_id;
1538 $deposit->demand_reason_id = $origin->demand_reason_id;
1539 $deposit->fk_account = $origin->fk_account;
1540 $deposit->fk_incoterms = $origin->fk_incoterms;
1541 $deposit->location_incoterms = $origin->location_incoterms;
1542 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1543 $deposit->multicurrency_code = $origin->multicurrency_code;
1544 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1545 $deposit->module_source = $origin->module_source;
1546 $deposit->pos_source = $origin->pos_source;
1547 $deposit->model_pdf =
'crabe';
1549 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1551 if (!empty($conf->global->$modelByTypeConfName)) {
1552 $deposit->model_pdf = $conf->global->$modelByTypeConfName;
1553 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
1554 $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
1557 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1558 $deposit->note_private = $origin->note_private;
1559 $deposit->note_public = $origin->note_public;
1562 $deposit->origin = $origin->element;
1563 $deposit->origin_id = $origin->id;
1565 $origin->fetch_optionals();
1567 foreach ($origin->array_options as $extrakey => $value) {
1568 $deposit->array_options[$extrakey] = $value;
1571 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1573 foreach ($overrideFields as $key => $value) {
1574 $deposit->$key = $value;
1577 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1579 $origin->db->begin();
1582 $createReturn = $deposit->create($user, $notrigger);
1584 if ($createReturn <= 0) {
1585 $origin->db->rollback();
1586 $origin->error = $deposit->error;
1587 $origin->errors = $deposit->errors;
1591 $amount_ttc_diff = 0;
1592 $amountdeposit = array();
1593 $descriptions = array();
1595 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1596 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1598 $TTotalByTva = array();
1599 foreach ($origin->lines as &$line) {
1600 if (!empty($line->special_code)) {
1603 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1604 $descriptions[$line->tva_tx] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1605 $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1606 $descriptions[$line->tva_tx] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1607 $descriptions[$line->tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1610 foreach ($TTotalByTva as $tva => &$total) {
1611 $coef = $total / $origin->total_ttc;
1612 $am = $amount * $coef;
1613 $amount_ttc_diff += $am;
1614 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1618 $lines = $origin->lines;
1619 $numlines = count($lines);
1620 for ($i = 0; $i < $numlines; $i++) {
1621 if (empty($lines[$i]->qty)) {
1624 if (!empty($lines[$i]->special_code)) {
1628 $totalamount += $lines[$i]->total_ht;
1629 $tva_tx = $lines[$i]->tva_tx;
1630 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1631 $descriptions[$tva_tx] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1632 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1633 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1634 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1637 if ($totalamount == 0) {
1638 $amountdeposit[0] = 0;
1641 $amount_ttc_diff = $amountdeposit[0];
1644 foreach ($amountdeposit as $tva => $amount) {
1645 if (empty($amount)) {
1649 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1652 if (!empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && !empty($descriptions[$tva])) {
1653 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1656 $addlineResult = $deposit->addline(
1663 (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1683 if ($addlineResult < 0) {
1684 $origin->db->rollback();
1685 $origin->error = $deposit->error;
1686 $origin->errors = $deposit->errors;
1691 $diff = $deposit->total_ttc - $amount_ttc_diff;
1693 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1694 $deposit->fetch_lines();
1695 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1697 $updatelineResult = $deposit->updateline(
1698 $deposit->lines[0]->id,
1699 $deposit->lines[0]->desc,
1701 $deposit->lines[0]->qty,
1702 $deposit->lines[0]->remise_percent,
1703 $deposit->lines[0]->date_start,
1704 $deposit->lines[0]->date_end,
1705 $deposit->lines[0]->tva_tx,
1709 $deposit->lines[0]->info_bits,
1710 $deposit->lines[0]->product_type,
1714 $deposit->lines[0]->pa_ht,
1715 $deposit->lines[0]->label,
1721 if ($updatelineResult < 0) {
1722 $origin->db->rollback();
1723 $origin->error = $deposit->error;
1724 $origin->errors = $deposit->errors;
1730 if (! is_object($hookmanager)) {
1731 require_once DOL_DOCUMENT_ROOT .
'/core/class/hookmanager.class.php';
1735 $hookmanager->initHooks(array(
'invoicedao'));
1737 $parameters = array(
'objFrom' => $origin);
1738 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1741 $origin->db->rollback();
1742 $origin->error = $hookmanager->error;
1743 $origin->errors = $hookmanager->errors;
1747 if (!empty($autoValidateDeposit)) {
1748 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1750 if ($validateReturn < 0) {
1751 $origin->db->rollback();
1752 $origin->error = $deposit->error;
1753 $origin->errors = $deposit->errors;
1758 unset($deposit->context[
'createdepositfromorigin']);
1760 $origin->db->commit();
1779 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
1781 global $langs, $conf, $user, $mysoc;
1783 if (!empty($conf->dol_no_mouse_hover)) {
1789 if ($option ==
'withdraw') {
1790 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
1792 $url = DOL_URL_ROOT.
'/compta/facture/card.php?facid='.$this->id;
1795 if (!$user->hasRight(
"facture",
"read")) {
1799 if ($option !==
'nolink') {
1801 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1802 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
1803 $add_save_lastsearch_values = 1;
1805 if ($add_save_lastsearch_values) {
1806 $url .=
'&save_lastsearch_values=1';
1814 $picto = $this->picto;
1815 if ($this->
type == self::TYPE_REPLACEMENT) {
1818 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1821 if ($this->
type == self::TYPE_DEPOSIT) {
1826 if ($user->hasRight(
"facture",
"read")) {
1827 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1828 if (isset($this->statut) && isset($this->alreadypaid)) {
1829 $label .=
' '.$this->getLibStatut(5, $this->alreadypaid);
1831 $label .=
' '.$this->getLibType(1);
1832 if (!empty($this->
ref)) {
1833 $label .=
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
1835 if (!empty($this->ref_client)) {
1836 $label .=
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_client;
1838 if (!empty($this->date)) {
1839 $label .=
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
1841 if (!empty($this->total_ht)) {
1842 $label .=
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1844 if (!empty($this->total_tva)) {
1845 $label .=
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1847 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1848 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1850 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1851 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1853 if (!empty($this->total_ttc)) {
1854 $label .=
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1857 $label .=
' - '.$moretitle;
1861 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
1862 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
1863 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1864 $label = $langs->trans(
"Invoice");
1865 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
1867 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
1868 $linkclose .=
' class="classfortooltip"';
1871 $linkstart =
'<a href="'.$url.
'"';
1872 $linkstart .= $linkclose.
'>';
1875 if ($option ==
'nolink') {
1880 $result .= $linkstart;
1882 $result .=
img_object(($notooltip ?
'' : $label), $picto, ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1884 if ($withpicto != 2) {
1885 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
1887 $result .= $linkend;
1889 if ($addlinktonotes) {
1890 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1893 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
1894 $result .=
' <span class="note inline-block">';
1895 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
1900 $result .=
'</span>';
1904 global $action, $hookmanager;
1905 $hookmanager->initHooks(array(
'invoicedao'));
1906 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value'=> $save_lastsearch_value,
'target' => $target);
1907 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
1909 $result = $hookmanager->resPrint;
1911 $result .= $hookmanager->resPrint;
1927 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused =
'', $fetch_situation =
false)
1929 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
1933 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.fk_soc';
1934 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
1935 $sql .=
', f.remise_percent, f.remise_absolue, f.remise';
1936 $sql .=
', f.datef as df, f.date_pointoftax';
1937 $sql .=
', f.date_lim_reglement as dlr';
1938 $sql .=
', f.datec as datec';
1939 $sql .=
', f.date_valid as datev';
1940 $sql .=
', f.tms as datem';
1941 $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';
1942 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
1943 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1944 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1945 $sql .=
', f.fk_account';
1946 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1947 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1948 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1949 $sql .=
', f.fk_incoterms, f.location_incoterms';
1950 $sql .=
', f.module_source, f.pos_source';
1951 $sql .=
", i.libelle as label_incoterms";
1952 $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";
1953 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
1954 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
1955 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
1956 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
1959 $sql .=
" WHERE f.rowid = ".((int) $rowid);
1961 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
1963 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
1966 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
1970 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
1974 $obj = $this->
db->fetch_object(
$resql);
1976 $this->
id = $obj->rowid;
1977 $this->entity = $obj->entity;
1979 $this->
ref = $obj->ref;
1980 $this->ref_client = $obj->ref_client;
1981 $this->ref_customer = $obj->ref_client;
1982 $this->ref_ext = $obj->ref_ext;
1983 $this->
type = $obj->type;
1984 $this->date = $this->
db->jdate($obj->df);
1985 $this->date_pointoftax = $this->
db->jdate($obj->date_pointoftax);
1986 $this->date_creation = $this->
db->jdate($obj->datec);
1987 $this->date_validation = $this->
db->jdate($obj->datev);
1988 $this->date_modification = $this->
db->jdate($obj->datem);
1989 $this->datem = $this->
db->jdate($obj->datem);
1990 $this->remise_percent = $obj->remise_percent;
1991 $this->remise_absolue = $obj->remise_absolue;
1992 $this->total_ht = $obj->total_ht;
1993 $this->total_tva = $obj->total_tva;
1994 $this->total_localtax1 = $obj->localtax1;
1995 $this->total_localtax2 = $obj->localtax2;
1996 $this->total_ttc = $obj->total_ttc;
1997 $this->revenuestamp = $obj->revenuestamp;
1998 $this->paye = $obj->paye;
1999 $this->close_code = $obj->close_code;
2000 $this->close_note = $obj->close_note;
2002 $this->socid = $obj->fk_soc;
2003 $this->thirdparty =
null;
2005 $this->fk_project = $obj->fk_project;
2006 $this->project =
null;
2008 $this->statut = $obj->fk_statut;
2009 $this->status = $obj->fk_statut;
2011 $this->date_lim_reglement = $this->
db->jdate($obj->dlr);
2012 $this->mode_reglement_id = $obj->fk_mode_reglement;
2013 $this->mode_reglement_code = $obj->mode_reglement_code;
2014 $this->mode_reglement = $obj->mode_reglement_libelle;
2015 $this->cond_reglement_id = $obj->fk_cond_reglement;
2016 $this->cond_reglement_code = $obj->cond_reglement_code;
2017 $this->cond_reglement = $obj->cond_reglement_libelle;
2018 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2019 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2020 $this->fk_facture_source = $obj->fk_facture_source;
2021 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2022 $this->note = $obj->note_private;
2023 $this->note_private = $obj->note_private;
2024 $this->note_public = $obj->note_public;
2025 $this->user_author = $obj->fk_user_author;
2026 $this->user_valid = $obj->fk_user_valid;
2027 $this->user_modification = $obj->fk_user_modif;
2028 $this->fk_user_author = $obj->fk_user_author;
2029 $this->fk_user_valid = $obj->fk_user_valid;
2030 $this->fk_user_modif = $obj->fk_user_modif;
2031 $this->model_pdf = $obj->model_pdf;
2032 $this->modelpdf = $obj->model_pdf;
2033 $this->last_main_doc = $obj->last_main_doc;
2034 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2035 $this->situation_counter = $obj->situation_counter;
2036 $this->situation_final = $obj->situation_final;
2037 $this->retained_warranty = $obj->retained_warranty;
2038 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2039 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2041 $this->extraparams = (array) json_decode($obj->extraparams,
true);
2044 $this->fk_incoterms = $obj->fk_incoterms;
2045 $this->location_incoterms = $obj->location_incoterms;
2046 $this->label_incoterms = $obj->label_incoterms;
2048 $this->module_source = $obj->module_source;
2049 $this->pos_source = $obj->pos_source;
2052 $this->fk_multicurrency = $obj->fk_multicurrency;
2053 $this->multicurrency_code = $obj->multicurrency_code;
2054 $this->multicurrency_tx = $obj->multicurrency_tx;
2055 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2056 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2057 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2059 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2063 if ($this->status == self::STATUS_DRAFT) {
2064 $this->brouillon = 1;
2072 $this->lines = array();
2076 $this->error = $this->
db->error();
2084 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2086 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2090 $this->error = $this->
db->lasterror();
2105 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2108 global $langs, $conf;
2110 $this->lines = array();
2112 $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,';
2113 $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,';
2114 $sql .=
' l.situation_percent, l.fk_prev_id,';
2115 $sql .=
' l.rang, l.special_code,';
2116 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2117 $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,';
2118 $sql .=
' l.fk_unit,';
2119 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2120 $sql .=
' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2121 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2122 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2123 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2124 $sql .=
' ORDER BY l.rang, l.rowid';
2126 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2127 $result = $this->
db->query($sql);
2129 $num = $this->
db->num_rows($result);
2132 $objp = $this->
db->fetch_object($result);
2135 $line->id = $objp->rowid;
2136 $line->rowid = $objp->rowid;
2137 $line->fk_facture = $objp->fk_facture;
2138 $line->label = $objp->custom_label;
2139 $line->desc = $objp->description;
2140 $line->description = $objp->description;
2141 $line->product_type = $objp->product_type;
2142 $line->ref = $objp->product_ref;
2143 $line->product_ref = $objp->product_ref;
2144 $line->libelle = $objp->product_label;
2145 $line->product_label = $objp->product_label;
2146 $line->product_desc = $objp->product_desc;
2147 $line->fk_product_type = $objp->fk_product_type;
2148 $line->qty = $objp->qty;
2149 $line->subprice = $objp->subprice;
2150 $line->ref_ext = $objp->ref_ext;
2152 $line->vat_src_code = $objp->vat_src_code;
2153 $line->tva_tx = $objp->tva_tx;
2154 $line->localtax1_tx = $objp->localtax1_tx;
2155 $line->localtax2_tx = $objp->localtax2_tx;
2156 $line->localtax1_type = $objp->localtax1_type;
2157 $line->localtax2_type = $objp->localtax2_type;
2158 $line->remise_percent = $objp->remise_percent;
2159 $line->fk_remise_except = $objp->fk_remise_except;
2160 $line->fk_product = $objp->fk_product;
2161 $line->date_start = $this->
db->jdate($objp->date_start);
2162 $line->date_end = $this->
db->jdate($objp->date_end);
2163 $line->date_start = $this->
db->jdate($objp->date_start);
2164 $line->date_end = $this->
db->jdate($objp->date_end);
2165 $line->info_bits = $objp->info_bits;
2166 $line->total_ht = $objp->total_ht;
2167 $line->total_tva = $objp->total_tva;
2168 $line->total_localtax1 = $objp->total_localtax1;
2169 $line->total_localtax2 = $objp->total_localtax2;
2170 $line->total_ttc = $objp->total_ttc;
2171 $line->code_ventilation = $objp->fk_code_ventilation;
2172 $line->fk_fournprice = $objp->fk_fournprice;
2173 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2174 $line->pa_ht = $marginInfos[0];
2175 $line->marge_tx = $marginInfos[1];
2176 $line->marque_tx = $marginInfos[2];
2177 $line->rang = $objp->rang;
2178 $line->special_code = $objp->special_code;
2179 $line->fk_parent_line = $objp->fk_parent_line;
2180 $line->situation_percent = $objp->situation_percent;
2181 $line->fk_prev_id = $objp->fk_prev_id;
2182 $line->fk_unit = $objp->fk_unit;
2185 $line->fk_accounting_account = $objp->fk_code_ventilation;
2188 $line->fk_multicurrency = $objp->fk_multicurrency;
2189 $line->multicurrency_code = $objp->multicurrency_code;
2190 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2191 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2192 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2193 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2195 $line->fetch_optionals();
2198 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2200 $tmpproduct->fetch($objp->fk_product);
2201 $tmpproduct->getMultiLangs();
2203 $line->multilangs = $tmpproduct->multilangs;
2206 $this->lines[$i] = $line;
2210 $this->
db->free($result);
2213 $this->error = $this->
db->error();
2228 $this->tab_previous_situation_invoice = array();
2229 $this->tab_next_situation_invoice = array();
2231 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2232 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2233 $sql .=
' AND entity = '.((int) $this->entity);
2234 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2235 $sql .=
' ORDER BY situation_counter ASC';
2237 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2238 $result = $this->
db->query($sql);
2239 if ($result && $this->
db->num_rows($result) > 0) {
2240 while ($objp = $this->
db->fetch_object($result)) {
2242 if ($invoice->fetch($objp->rowid) > 0) {
2243 if ($objp->situation_counter < $this->situation_counter
2244 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2246 $this->tab_previous_situation_invoice[] = $invoice;
2248 $this->tab_next_situation_invoice[] = $invoice;
2269 if (empty($this->
type)) {
2272 if (isset($this->
ref)) {
2273 $this->
ref = trim($this->
ref);
2275 if (isset($this->ref_ext)) {
2276 $this->ref_ext = trim($this->ref_ext);
2278 if (isset($this->ref_client)) {
2279 $this->ref_client = trim($this->ref_client);
2281 if (isset($this->increment)) {
2282 $this->increment = trim($this->increment);
2284 if (isset($this->close_code)) {
2285 $this->close_code = trim($this->close_code);
2287 if (isset($this->close_note)) {
2288 $this->close_note = trim($this->close_note);
2290 if (isset($this->note) || isset($this->note_private)) {
2291 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2293 if (isset($this->note) || isset($this->note_private)) {
2294 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2296 if (isset($this->note_public)) {
2297 $this->note_public = trim($this->note_public);
2299 if (isset($this->model_pdf)) {
2300 $this->model_pdf = trim($this->model_pdf);
2302 if (isset($this->import_key)) {
2303 $this->import_key = trim($this->import_key);
2305 if (isset($this->retained_warranty)) {
2306 $this->retained_warranty = floatval($this->retained_warranty);
2314 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2315 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2316 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2317 $sql .=
" type=".(isset($this->
type) ? $this->
db->escape($this->
type) :
"null").
",";
2318 $sql .=
" ref_client=".(isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null").
",";
2319 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2320 $sql .=
" fk_soc=".(isset($this->socid) ? $this->
db->escape($this->socid) :
"null").
",";
2321 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2322 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2323 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2324 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2325 $sql .=
" paye=".(isset($this->paye) ? $this->
db->escape($this->paye) : 0).
",";
2326 $sql .=
" remise_percent=".(isset($this->remise_percent) ? $this->
db->escape($this->remise_percent) :
"null").
",";
2327 $sql .=
" remise_absolue=".(isset($this->remise_absolue) ? $this->
db->escape($this->remise_absolue) :
"null").
",";
2328 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2329 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2330 $sql .=
" total_tva=".(isset($this->total_tva) ? $this->total_tva :
"null").
",";
2331 $sql .=
" localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 :
"null").
",";
2332 $sql .=
" localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 :
"null").
",";
2333 $sql .=
" total_ht=".(isset($this->total_ht) ? $this->total_ht :
"null").
",";
2334 $sql .=
" total_ttc=".(isset($this->total_ttc) ? $this->total_ttc :
"null").
",";
2335 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? $this->
db->escape($this->revenuestamp) :
"null").
",";
2336 $sql .=
" fk_statut=".(isset($this->statut) ? $this->
db->escape($this->statut) :
"null").
",";
2337 $sql .=
" fk_user_author=".(isset($this->user_author) ? $this->
db->escape($this->user_author) :
"null").
",";
2338 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? $this->
db->escape($this->fk_user_valid) :
"null").
",";
2339 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? $this->
db->escape($this->fk_facture_source) :
"null").
",";
2340 $sql .=
" fk_projet=".(isset($this->fk_project) ? $this->
db->escape($this->fk_project) :
"null").
",";
2341 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->
db->escape($this->cond_reglement_id) :
"null").
",";
2342 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->
db->escape($this->mode_reglement_id) :
"null").
",";
2343 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2344 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2345 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2346 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2347 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2348 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : $this->
db->escape($this->situation_cycle_ref)).
",";
2349 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : $this->
db->escape($this->situation_counter)).
",";
2350 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : $this->
db->escape($this->situation_final)).
",";
2351 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty)).
",";
2352 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2353 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) :
"null");
2354 $sql .=
" WHERE rowid=".((int) $this->
id);
2358 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2362 $this->errors[] =
"Error ".$this->db->lasterror();
2372 if (!$error && !$notrigger) {
2383 foreach ($this->errors as $errmsg) {
2384 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2385 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2387 $this->
db->rollback();
2390 $this->
db->commit();
2406 global $conf, $langs;
2408 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2409 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2414 $result = $remise->fetch($idremise);
2417 if ($remise->fk_facture) {
2418 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2419 $this->
db->rollback();
2424 $facligne->fk_facture = $this->id;
2425 $facligne->fk_remise_except = $remise->id;
2426 $facligne->desc = $remise->description;
2427 $facligne->vat_src_code = $remise->vat_src_code;
2428 $facligne->tva_tx = $remise->tva_tx;
2429 $facligne->subprice = -$remise->amount_ht;
2430 $facligne->fk_product = 0;
2432 $facligne->remise_percent = 0;
2433 $facligne->rang = -1;
2434 $facligne->info_bits = 2;
2436 if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
2437 $facligne->rang = 1;
2438 $linecount = count($this->lines);
2439 for ($ii = 1; $ii <= $linecount; $ii++) {
2445 if ($remise->fk_facture_source > 0) {
2447 $srcinvoice->fetch($remise->fk_facture_source);
2448 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2450 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2451 $facligne->pa_ht = $arraytmp[
'pa_total'];
2454 $facligne->total_ht = -$remise->amount_ht;
2455 $facligne->total_tva = -$remise->amount_tva;
2456 $facligne->total_ttc = -$remise->amount_ttc;
2458 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2459 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2460 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2461 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2463 $lineid = $facligne->insert();
2468 $result = $remise->link_to_invoice($lineid, 0);
2470 $this->error = $remise->error;
2471 $this->
db->rollback();
2475 $this->
db->commit();
2478 $this->error = $facligne->error;
2479 $this->
db->rollback();
2483 $this->error = $facligne->error;
2484 $this->
db->rollback();
2488 $this->
db->rollback();
2510 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2511 if (empty($ref_client)) {
2512 $sql .=
' SET ref_client = NULL';
2514 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2516 $sql .=
" WHERE rowid = ".((int) $this->
id);
2518 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2521 $this->errors[] = $this->
db->error();
2526 $this->ref_client = $ref_client;
2529 if (!$notrigger && empty($error)) {
2539 $this->ref_client = $ref_client;
2541 $this->
db->commit();
2544 foreach ($this->errors as $errmsg) {
2545 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2546 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2548 $this->
db->rollback();
2561 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2563 global $langs, $conf;
2564 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2568 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2581 if (!$error && !$notrigger) {
2595 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2609 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2610 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2611 $sql .=
' AND fk_facture_line IS NULL';
2616 $list_rowid_det = array();
2617 foreach ($this->lines as $key => $invoiceline) {
2618 $list_rowid_det[] = $invoiceline->id;
2622 if (count($list_rowid_det)) {
2623 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2624 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2625 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(join(
',', $list_rowid_det)).
')';
2627 if (!$this->
db->query($sql)) {
2628 $this->error = $this->
db->error().
" sql=".$sql;
2629 $this->errors[] = $this->error;
2630 $this->
db->rollback();
2637 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2638 $sql .=
' SET fk_invoice = NULL';
2639 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2641 if (!$this->
db->query($sql)) {
2642 $this->error = $this->
db->error().
" sql=".$sql;
2643 $this->errors[] = $this->error;
2644 $this->
db->rollback();
2648 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'projet_task_time';
2649 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2650 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2652 if (!$this->
db->query($sql)) {
2653 $this->error = $this->
db->error().
" sql=".$sql;
2654 $this->errors[] = $this->error;
2655 $this->
db->rollback();
2660 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
2661 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2662 $langs->load(
"agenda");
2664 $num = count($this->lines);
2665 for ($i = 0; $i < $num; $i++) {
2666 if ($this->lines[$i]->fk_product > 0) {
2668 $mouvP->origin = &$this;
2669 $mouvP->setOrigin($this->element, $this->
id);
2671 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2672 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2674 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2681 $main = MAIN_DB_PREFIX.
'facturedet';
2682 $ef = $main.
"_extrafields";
2683 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2685 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2688 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2697 if ($conf->facture->dir_output && !empty($this->
ref)) {
2698 $dir = $conf->facture->dir_output.
"/".$ref;
2699 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2700 if (file_exists($file)) {
2704 $langs->load(
"errors");
2705 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2706 $this->errors[] = $this->error;
2707 $this->
db->rollback();
2711 if (file_exists($dir)) {
2713 $langs->load(
"errors");
2714 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2715 $this->errors[] = $this->error;
2716 $this->
db->rollback();
2722 $this->
db->commit();
2725 $this->error = $this->
db->lasterror().
" sql=".$sql;
2726 $this->errors[] = $this->error;
2727 $this->
db->rollback();
2731 $this->error = $this->
db->lasterror().
" sql=".$sql;
2732 $this->errors[] = $this->error;
2733 $this->
db->rollback();
2737 $this->
db->rollback();
2754 public function set_paid($user, $close_code =
'', $close_note =
'')
2757 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2758 return $this->
setPaid($user, $close_code, $close_note);
2770 public function setPaid($user, $close_code =
'', $close_note =
'')
2774 if ($this->paye != 1) {
2779 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
2781 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2782 $sql .=
' fk_statut='.self::STATUS_CLOSED;
2787 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2790 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2792 $sql .=
', fk_user_closing = '.((int) $user->id);
2793 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
2794 $sql .=
" WHERE rowid = ".((int) $this->
id);
2806 $this->error = $this->
db->lasterror();
2810 $this->
db->commit();
2813 $this->
db->rollback();
2836 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
2854 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2855 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
2856 $sql .=
' date_closing=null,';
2857 $sql .=
' fk_user_closing=null';
2858 $sql .=
" WHERE rowid = ".((int) $this->
id);
2860 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
2871 $this->error = $this->
db->error();
2876 $this->
db->commit();
2879 $this->
db->rollback();
2901 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
2902 return $this->
setCanceled($user, $close_code, $close_note);
2915 public function setCanceled($user, $close_code =
'', $close_note =
'')
2917 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
2921 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2922 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
2924 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2927 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2929 $sql .=
" WHERE rowid = ".((int) $this->
id);
2935 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2936 $sql .=
' SET fk_facture = NULL';
2937 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
2944 $this->
db->rollback();
2949 $this->
db->commit();
2952 $this->error = $this->
db->error().
" sql=".$sql;
2953 $this->
db->rollback();
2957 $this->error = $this->
db->error().
" sql=".$sql;
2958 $this->
db->rollback();
2974 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
2976 global $conf, $langs, $mysoc;
2977 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2979 $productStatic =
null;
2980 $warehouseStatic =
null;
2981 if ($batch_rule > 0) {
2982 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2983 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
2984 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
2985 $productStatic =
new Product($this->
db);
2987 $productbatch =
new ProductBatch($this->
db);
2993 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3000 if ($this->statut != self::STATUS_DRAFT) {
3001 dol_syslog(get_class($this).
"::validate status is not draft. operation canceled.", LOG_WARNING);
3004 if (count($this->lines) <= 0) {
3005 $langs->load(
"errors");
3006 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3009 if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
3010 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
3011 $this->error =
'Permission denied';
3012 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
3015 if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
3017 if (!$last_of_type[0]) {
3018 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3024 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3025 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3026 foreach ($array_to_check as $key) {
3027 $keymin = strtolower($key);
3028 if (!property_exists($this->thirdparty, $keymin)) {
3031 $vallabel = $this->thirdparty->$keymin;
3033 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3035 if ($this->thirdparty->isACompany()) {
3037 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3038 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3039 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3040 $langs->load(
"errors");
3041 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3042 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3048 if ($key ==
'EMAIL') {
3050 if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
3051 $langs->load(
"errors");
3052 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3053 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3057 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3059 if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
3060 $langs->load(
"errors");
3061 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3062 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3071 $array_to_check = array(
'REF_CLIENT'=>
'RefCustomer');
3072 foreach ($array_to_check as $key => $val) {
3073 $keymin = strtolower($key);
3074 $vallabel = $this->$keymin;
3077 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3078 if (!$vallabel && !empty($conf->global->$keymandatory)) {
3079 $langs->load(
"errors");
3081 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val)),
null,
'errors');
3088 if ($this->
type == self::TYPE_REPLACEMENT) {
3090 if ($this->fk_facture_source <= 0) {
3091 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3092 $this->
db->rollback();
3098 $result = $facreplaced->fetch($this->fk_facture_source);
3100 $this->error = $langs->trans(
"ErrorBadInvoice");
3101 $this->
db->rollback();
3106 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3107 if ($idreplacement && $idreplacement != $this->
id) {
3108 $facreplacement =
new Facture($this->
db);
3109 $facreplacement->fetch($idreplacement);
3110 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3111 $this->
db->rollback();
3115 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3117 $this->error = $facreplaced->error;
3118 $this->
db->rollback();
3124 if ($force_number) {
3125 $num = $force_number;
3126 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3127 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3142 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3143 $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).
"'";
3144 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3145 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3146 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3148 $sql .=
" WHERE rowid = ".((int) $this->
id);
3150 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3158 if (!$error && (preg_match(
'/^[\(]?PROV/i', $this->
ref))) {
3164 $result = $this->thirdparty->set_as_client();
3167 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
3168 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3169 $langs->load(
"agenda");
3172 $cpt = count($this->lines);
3173 for ($i = 0; $i < $cpt; $i++) {
3174 if ($this->lines[$i]->fk_product > 0) {
3176 $mouvP->origin = &$this;
3177 $mouvP->setOrigin($this->element, $this->
id);
3179 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3180 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3183 $this->error = $mouvP->error;
3186 $is_batch_line =
false;
3187 if ($batch_rule > 0) {
3188 $productStatic->fetch($this->lines[$i]->fk_product);
3189 if ($productStatic->hasbatch()) {
3190 $is_batch_line =
true;
3191 $product_qty_remain = $this->lines[$i]->qty;
3197 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3198 $sortorder =
'ASC,ASC,ASC,ASC';
3201 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ?
null : 0), $sortfield, $sortorder);
3202 if (!is_array($resBatchList)) {
3204 $this->error = $this->
db->lasterror();
3208 $batchList = $resBatchList;
3209 if (empty($batchList)) {
3211 $langs->load(
'errors');
3212 $warehouseStatic->fetch($idwarehouse);
3213 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3214 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3217 foreach ($batchList as $batch) {
3218 if ($batch->qty <= 0) {
3223 if ($batch->qty >= $product_qty_remain) {
3224 $product_batch_qty = $product_qty_remain;
3227 $product_batch_qty = $batch->qty;
3229 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3232 $this->error = $mouvP->error;
3236 $product_qty_remain -= $product_batch_qty;
3238 if ($product_qty_remain <= 0) {
3243 if (!$error && $product_qty_remain > 0) {
3244 if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
3246 $batch = $batchList[0];
3247 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3250 $this->error = $mouvP->error;
3254 $langs->load(
'errors');
3255 $warehouseStatic->fetch($idwarehouse);
3256 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3257 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3264 if (!$is_batch_line) {
3265 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3268 $this->error = $mouvP->error;
3281 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3282 $invoice_situation =
new Facture($this->
db);
3283 $result = $invoice_situation->fetch($this->fk_facture_source);
3284 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3285 $invoice_situation->situation_final = 0;
3287 $result = $invoice_situation->setFinal($user, 1);
3290 $this->error = $invoice_situation->error;
3291 $this->errors = $invoice_situation->errors;
3297 if (!$error && !$notrigger) {
3307 $this->oldref = $this->ref;
3310 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3312 $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).
"'";
3313 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->
db->escape($this->
ref).
"' and entity = ".$conf->entity;
3317 $this->error = $this->
db->lasterror();
3323 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3324 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3325 if (!$error && file_exists($dirsource)) {
3326 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3328 if (@rename($dirsource, $dirdest)) {
3331 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3332 foreach ($listoffiles as $fileentry) {
3333 $dirsource = $fileentry[
'name'];
3334 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3335 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3336 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3337 @rename($dirsource, $dirdest);
3356 $this->brouillon = 0;
3357 $this->date_validation = $now;
3360 if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3362 $nboflines = count($this->lines);
3363 while (($i < $nboflines) && $final) {
3364 $final = ($this->lines[$i]->situation_percent == 100);
3368 if (empty($final)) {
3369 $this->situation_final = 0;
3371 $this->situation_final = 1;
3382 $this->
db->commit();
3385 $this->
db->rollback();
3398 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3399 $is_last = $next_invoice->is_last_in_cycle();
3401 if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
3402 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3406 $next_invoice->brouillon = 1;
3408 foreach ($next_invoice->lines as $line) {
3409 $result = $next_invoice->updateline(
3414 $line->remise_percent,
3418 $line->localtax1_tx,
3419 $line->localtax2_tx,
3422 $line->product_type,
3423 $line->fk_parent_line,
3425 $line->fk_fournprice,
3428 $line->special_code,
3429 $line->array_options,
3430 $line->situation_percent,
3435 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3456 global $conf, $langs;
3460 if ($this->statut == self::STATUS_DRAFT) {
3461 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3469 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3470 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3471 $sql .=
" WHERE rowid = ".((int) $this->
id);
3473 $result = $this->
db->query($sql);
3476 $this->oldcopy = clone $this;
3480 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3481 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3482 $langs->load(
"agenda");
3484 $num = count($this->lines);
3485 for ($i = 0; $i < $num; $i++) {
3486 if ($this->lines[$i]->fk_product > 0) {
3488 $mouvP->origin = &$this;
3489 $mouvP->setOrigin($this->element, $this->
id);
3491 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3492 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3494 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3501 $old_statut = $this->statut;
3502 $this->brouillon = 1;
3507 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3510 $this->statut = $old_statut;
3511 $this->status = $old_statut;
3512 $this->brouillon = 0;
3516 $this->
db->rollback();
3521 $this->
db->commit();
3524 $this->
db->rollback();
3528 $this->error = $this->
db->error();
3529 $this->
db->rollback();
3583 $remise_percent = 0,
3588 $fk_remise_except =
'',
3589 $price_base_type =
'HT',
3596 $fk_parent_line = 0,
3597 $fk_fournprice =
null,
3601 $situation_percent = 100,
3606 $noupdateafterinsertline = 0
3610 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3614 global $mysoc, $conf, $langs;
3616 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);
3618 if ($this->statut == self::STATUS_DRAFT) {
3619 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3622 if (empty($remise_percent)) {
3623 $remise_percent = 0;
3628 if (empty($info_bits)) {
3634 if (empty($ventil)) {
3637 if (empty($txtva)) {
3640 if (empty($txlocaltax1)) {
3643 if (empty($txlocaltax2)) {
3646 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3647 $fk_parent_line = 0;
3649 if (empty($fk_prev_id)) {
3650 $fk_prev_id =
'null';
3652 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3653 $situation_percent = 100;
3655 if (empty($ref_ext)) {
3659 $remise_percent =
price2num($remise_percent);
3662 $pu_ht_devise =
price2num($pu_ht_devise);
3665 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3671 if ($price_base_type ==
'HT') {
3682 if ($date_start && $date_end && $date_start > $date_end) {
3683 $langs->load(
"errors");
3684 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3690 $product_type = $type;
3691 if (!empty($fk_product) && $fk_product > 0) {
3693 $result = $product->fetch($fk_product);
3694 $product_type = $product->type;
3696 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3697 $langs->load(
"errors");
3698 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3699 $this->
db->rollback();
3709 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3710 $vat_src_code = $reg[1];
3711 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3719 $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);
3721 $total_ht = $tabprice[0];
3722 $total_tva = $tabprice[1];
3723 $total_ttc = $tabprice[2];
3724 $total_localtax1 = $tabprice[9];
3725 $total_localtax2 = $tabprice[10];
3726 $pu_ht = $tabprice[3];
3729 $multicurrency_total_ht = $tabprice[16];
3730 $multicurrency_total_tva = $tabprice[17];
3731 $multicurrency_total_ttc = $tabprice[18];
3732 $pu_ht_devise = $tabprice[19];
3736 if ($ranktouse == -1) {
3737 $rangmax = $this->
line_max($fk_parent_line);
3738 $ranktouse = $rangmax + 1;
3744 $this->line->context = $this->context;
3746 $this->line->fk_facture = $this->id;
3747 $this->line->label = $label;
3748 $this->line->desc = $desc;
3749 $this->line->ref_ext = $ref_ext;
3751 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty);
3752 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
3754 $this->line->vat_src_code = $vat_src_code;
3755 $this->line->tva_tx = $txtva;
3756 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3757 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3758 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
3759 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
3761 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
3762 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
3763 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
3764 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
3765 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
3767 $this->line->fk_product = $fk_product;
3768 $this->line->product_type = $product_type;
3769 $this->line->remise_percent = $remise_percent;
3770 $this->line->date_start = $date_start;
3771 $this->line->date_end = $date_end;
3772 $this->line->ventil = $ventil;
3773 $this->line->rang = $ranktouse;
3774 $this->line->info_bits = $info_bits;
3775 $this->line->fk_remise_except = $fk_remise_except;
3777 $this->line->special_code = $special_code;
3778 $this->line->fk_parent_line = $fk_parent_line;
3779 $this->line->origin = $origin;
3780 $this->line->origin_id = $origin_id;
3781 $this->line->situation_percent = $situation_percent;
3782 $this->line->fk_prev_id = $fk_prev_id;
3783 $this->line->fk_unit = $fk_unit;
3786 $this->line->fk_fournprice = $fk_fournprice;
3787 $this->line->pa_ht = $pa_ht;
3790 $this->line->fk_multicurrency = $this->fk_multicurrency;
3791 $this->line->multicurrency_code = $this->multicurrency_code;
3792 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
3794 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
3795 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
3796 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
3798 if (is_array($array_options) && count($array_options) > 0) {
3799 $this->line->array_options = $array_options;
3802 $result = $this->line->insert();
3805 if (!empty($fk_parent_line)) {
3807 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
3808 $linecount = count($this->lines);
3809 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
3815 if (empty($noupdateafterinsertline)) {
3820 $this->
db->commit();
3821 return $this->line->id;
3823 $this->error = $this->
db->lasterror();
3824 $this->
db->rollback();
3828 $this->error = $this->line->error;
3829 $this->errors = $this->line->errors;
3830 $this->
db->rollback();
3834 $this->errors[]=
'status of invoice must be Draft to allow use of ->addline()';
3835 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3871 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)
3873 global $conf, $user;
3876 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3879 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3881 global $mysoc, $langs;
3883 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);
3885 if ($this->statut == self::STATUS_DRAFT) {
3888 if (!$this->error) {
3889 $this->error = $langs->trans(
'invoiceLineProgressError');
3895 if ($date_start && $date_end && $date_start > $date_end) {
3896 $langs->load(
"errors");
3897 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3907 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3908 $fk_parent_line = 0;
3910 if (empty($special_code) || $special_code == 3) {
3913 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3914 $situation_percent = 100;
3916 if (empty($ref_ext)) {
3920 $remise_percent =
price2num($remise_percent);
3923 $pu_ht_devise =
price2num($pu_ht_devise);
3925 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3945 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3946 $vat_src_code = $reg[1];
3947 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3950 $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);
3952 $total_ht = $tabprice[0];
3953 $total_tva = $tabprice[1];
3954 $total_ttc = $tabprice[2];
3955 $total_localtax1 = $tabprice[9];
3956 $total_localtax2 = $tabprice[10];
3957 $pu_ht = $tabprice[3];
3958 $pu_tva = $tabprice[4];
3959 $pu_ttc = $tabprice[5];
3962 $multicurrency_total_ht = $tabprice[16];
3963 $multicurrency_total_tva = $tabprice[17];
3964 $multicurrency_total_ttc = $tabprice[18];
3965 $pu_ht_devise = $tabprice[19];
3970 if ($remise_percent > 0) {
3971 $remise = round(($pu * $remise_percent / 100), 2);
3972 $price = ($pu - $remise);
3978 $line->fetch($rowid);
3979 $line->fetch_optionals();
3981 if (!empty($line->fk_product)) {
3983 $result = $product->fetch($line->fk_product);
3984 $product_type = $product->type;
3986 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3987 $langs->load(
"errors");
3988 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3989 $this->
db->rollback();
3994 $staticline = clone $line;
3996 $line->oldline = $staticline;
3997 $this->line = $line;
3998 $this->line->context = $this->context;
3999 $this->line->rang = $rang;
4002 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4003 $rangmax = $this->
line_max($fk_parent_line);
4004 $this->line->rang = $rangmax + 1;
4007 $this->line->id = $rowid;
4008 $this->line->rowid = $rowid;
4009 $this->line->label = $label;
4010 $this->line->desc = $desc;
4011 $this->line->ref_ext = $ref_ext;
4012 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty);
4014 $this->line->vat_src_code = $vat_src_code;
4015 $this->line->tva_tx = $txtva;
4016 $this->line->localtax1_tx = $txlocaltax1;
4017 $this->line->localtax2_tx = $txlocaltax2;
4018 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
4019 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
4021 $this->line->remise_percent = $remise_percent;
4022 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht);
4023 $this->line->date_start = $date_start;
4024 $this->line->date_end = $date_end;
4025 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht);
4026 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
4027 $this->line->total_localtax1 = $total_localtax1;
4028 $this->line->total_localtax2 = $total_localtax2;
4029 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
4030 $this->line->info_bits = $info_bits;
4031 $this->line->special_code = $special_code;
4032 $this->line->product_type = $type;
4033 $this->line->fk_parent_line = $fk_parent_line;
4034 $this->line->skip_update_total = $skip_update_total;
4035 $this->line->situation_percent = $situation_percent;
4036 $this->line->fk_unit = $fk_unit;
4038 $this->line->fk_fournprice = $fk_fournprice;
4039 $this->line->pa_ht = $pa_ht;
4042 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise);
4043 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht);
4044 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
4045 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4047 if (is_array($array_options) && count($array_options) > 0) {
4049 foreach ($array_options as $key => $value) {
4050 $this->line->array_options[$key] = $array_options[$key];
4054 $result = $this->line->update($user, $notrigger);
4057 if (!empty($fk_parent_line)) {
4063 $this->
db->commit();
4066 $this->error = $this->line->error;
4067 $this->
db->rollback();
4071 $this->error =
"Invoice statut makes operation forbidden";
4085 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4086 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4087 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4089 $result = $this->
db->query($sql);
4091 $this->error = $this->
db->error();
4095 $obj = $this->
db->fetch_object($result);
4097 if ($obj ===
null) {
4100 return $situation_percent < $obj->situation_percent;
4116 global $mysoc, $user;
4119 if (($line->info_bits & 2) == 2) {
4123 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4126 if ($percent > 100) {
4129 $line->situation_percent = $percent;
4130 $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);
4131 $line->total_ht = $tabprice[0];
4132 $line->total_tva = $tabprice[1];
4133 $line->total_ttc = $tabprice[2];
4134 $line->total_localtax1 = $tabprice[9];
4135 $line->total_localtax2 = $tabprice[10];
4136 $line->multicurrency_total_ht = $tabprice[16];
4137 $line->multicurrency_total_tva = $tabprice[17];
4138 $line->multicurrency_total_ttc = $tabprice[18];
4139 $line->update($user);
4142 if ($update_price) {
4158 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4160 if ($this->statut != self::STATUS_DRAFT) {
4161 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4167 $line->context = $this->context;
4170 $result = $line->fetch($rowid);
4171 if (!($result > 0)) {
4176 if ($id > 0 && $line->fk_facture != $id) {
4177 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4184 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
4185 $sql .=
' SET fk_facture_line = NULL';
4186 $sql .=
' WHERE fk_facture_line = '.((int) $rowid);
4188 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
4189 $result = $this->
db->query($sql);
4191 $this->error = $this->
db->error();
4192 $this->
db->rollback();
4197 $staticline = clone $line;
4198 $line->oldline = $staticline;
4200 if ($line->delete($user) > 0) {
4204 $this->
db->commit();
4207 $this->
db->rollback();
4208 $this->error = $this->
db->lasterror();
4212 $this->
db->rollback();
4213 $this->error = $line->error;
4232 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4233 return $this->
setDiscount($user, $remise, $notrigger);
4247 if (empty($remise)) {
4251 if ($user->rights->facture->creer) {
4258 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4259 $sql .=
' SET remise_percent = '.((float) $remise);
4260 $sql .=
" WHERE rowid = ".((int) $this->
id);
4261 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4266 $this->errors[] = $this->
db->error();
4270 if (!$notrigger && empty($error)) {
4280 $this->remise_percent = $remise;
4283 $this->
db->commit();
4286 foreach ($this->errors as $errmsg) {
4287 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4288 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4290 $this->
db->rollback();
4309 if (empty($remise)) {
4313 if ($user->rights->facture->creer) {
4320 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4321 $sql .=
' SET remise_absolue = '.((float) $remise);
4322 $sql .=
" WHERE rowid = ".((int) $this->
id);
4323 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4328 $this->errors[] = $this->
db->error();
4333 $this->oldcopy = clone $this;
4334 $this->remise_absolue = $remise;
4338 if (!$notrigger && empty($error)) {
4348 $this->
db->commit();
4351 foreach ($this->errors as $errmsg) {
4352 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4353 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4355 $this->
db->rollback();
4371 global $conf, $langs;
4373 if ($this->module_source ==
'takepos') {
4374 $langs->load(
'cashdesk');
4376 $moduleName =
'takepos';
4377 $moduleSourceName =
'Takepos';
4378 $addonConstName =
'TAKEPOS_REF_ADDON';
4381 if (empty($conf->global->TAKEPOS_REF_ADDON)) {
4382 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4385 $addon = $conf->global->TAKEPOS_REF_ADDON;
4387 $langs->load(
'bills');
4389 $moduleName =
'facture';
4390 $moduleSourceName =
'Invoice';
4391 $addonConstName =
'FACTURE_ADDON';
4394 if (empty($conf->global->FACTURE_ADDON)) {
4395 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4396 } elseif ($conf->global->FACTURE_ADDON ==
'terre') {
4397 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4398 } elseif ($conf->global->FACTURE_ADDON ==
'mercure') {
4399 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4402 $addon = $conf->global->FACTURE_ADDON;
4405 if (!empty($addon)) {
4406 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = ".$conf->global->FACTURE_ADDON.
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4410 $file = $addon.
'.php';
4411 $classname = $addon;
4415 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4416 foreach ($dirmodels as $reldir) {
4417 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4420 if (is_file($dir.$file) && is_readable($dir.$file)) {
4421 $mybool |= include_once $dir.$file;
4427 $file = $addon.
'/'.$addon.
'.modules.php';
4428 $classname =
'mod_'.$moduleName.
'_'.$addon;
4429 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4431 foreach ($conf->file->dol_document_root as $dirroot) {
4432 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4435 if (is_file($dir.$file) && is_readable($dir.$file)) {
4436 $mybool |= include_once $dir.$file;
4446 $obj =
new $classname();
4448 $numref = $obj->getNextValue($soc, $this, $mode);
4455 if ($mode !=
'last' && !$numref) {
4456 $this->error = $obj->error;
4462 $langs->load(
'errors');
4463 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4476 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4477 $sql .=
' date_closing as dateclosing,';
4478 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4479 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4480 $sql .=
' WHERE c.rowid = '.((int) $id);
4482 $result = $this->
db->query($sql);
4484 if ($this->
db->num_rows($result)) {
4485 $obj = $this->
db->fetch_object($result);
4486 $this->
id = $obj->rowid;
4487 if ($obj->fk_user_author) {
4488 $cuser =
new User($this->
db);
4489 $cuser->fetch($obj->fk_user_author);
4490 $this->user_creation = $cuser;
4492 if ($obj->fk_user_valid) {
4493 $vuser =
new User($this->
db);
4494 $vuser->fetch($obj->fk_user_valid);
4495 $this->user_validation = $vuser;
4497 if ($obj->fk_user_closing) {
4498 $cluser =
new User($this->
db);
4499 $cluser->fetch($obj->fk_user_closing);
4500 $this->user_closing = $cluser;
4503 $this->date_creation = $this->
db->jdate($obj->datec);
4504 $this->date_modification = $this->
db->jdate($obj->datem);
4505 $this->date_validation = $this->
db->jdate($obj->datev);
4506 $this->date_closing = $this->
db->jdate($obj->dateclosing);
4508 $this->
db->free($result);
4529 public function liste_array($shortlist = 0, $draft = 0, $excluser =
'', $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4532 global $conf, $user;
4536 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4537 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4538 if (empty($user->rights->societe->client->voir) && !$socid) {
4539 $sql .=
", sc.fk_soc, sc.fk_user";
4541 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4542 if (empty($user->rights->societe->client->voir) && !$socid) {
4543 $sql .=
", ".MAIN_DB_PREFIX.
"societe_commerciaux as sc";
4545 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4546 $sql .=
" AND f.fk_soc = s.rowid";
4547 if (empty($user->rights->societe->client->voir) && !$socid) {
4548 $sql .=
" AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4551 $sql .=
" AND s.rowid = ".((int) $socid);
4554 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4556 if (is_object($excluser)) {
4557 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4559 $sql .= $this->
db->order($sortfield, $sortorder);
4560 $sql .= $this->
db->plimit($limit, $offset);
4562 $result = $this->
db->query($sql);
4564 $numc = $this->
db->num_rows($result);
4567 while ($i < $numc) {
4568 $obj = $this->
db->fetch_object($result);
4570 if ($shortlist == 1) {
4571 $ga[$obj->fid] = $obj->ref;
4572 } elseif ($shortlist == 2) {
4573 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4575 $ga[$i][
'id'] = $obj->fid;
4576 $ga[$i][
'ref'] = $obj->ref;
4577 $ga[$i][
'name'] = $obj->name;
4606 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4607 $sql .=
" ff.rowid as rowidnext";
4609 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4610 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4611 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4612 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4613 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4614 $sql .=
" AND f.paye = 0";
4615 $sql .=
" AND pf.fk_paiement IS NULL";
4616 $sql .=
" AND ff.fk_statut IS NULL";
4618 $sql .=
" AND f.fk_soc = ".((int) $socid);
4621 $sql .=
" ORDER BY f.ref";
4623 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4626 while ($obj = $this->
db->fetch_object(
$resql)) {
4627 $return[$obj->rowid] = array(
4628 'id' => $obj->rowid,
4630 'status' => $obj->status,
4631 'paid' => $obj->paid,
4638 $this->error = $this->
db->error();
4661 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
4662 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4663 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4664 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4665 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4666 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4670 $sql .=
" AND ff.type IS NULL";
4671 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4673 if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4675 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4676 $sql .=
'(SELECT MAX(fs.rowid)';
4677 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4678 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4679 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4680 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4682 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4684 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4687 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4691 $sql .=
" AND f.fk_soc = ".((int) $socid);
4693 $sql .=
" ORDER BY f.ref";
4695 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4698 while ($obj = $this->
db->fetch_object(
$resql)) {
4700 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4703 if ($obj->fk_statut == self::STATUS_CLOSED) {
4708 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4709 $return[$obj->rowid] = array(
'ref'=>$obj->ref,
'status'=>$obj->fk_statut,
'type'=>$obj->type,
'paye'=>$obj->paye,
'paymentornot'=>$paymentornot);
4715 $this->error = $this->
db->error();
4731 global $conf, $langs;
4735 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
4736 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4737 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4738 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4739 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4742 $sql .= $clause.
" f.paye=0";
4743 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4744 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
4746 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
4751 $langs->load(
"bills");
4755 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4756 $response->label = $langs->trans(
"CustomerBillsUnpaid");
4757 $response->labelShort = $langs->trans(
"Unpaid");
4758 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4761 $generic_facture =
new Facture($this->
db);
4763 while ($obj = $this->
db->fetch_object(
$resql)) {
4764 $generic_facture->date_lim_reglement = $this->
db->jdate($obj->datefin);
4765 $generic_facture->statut = $obj->fk_statut;
4767 $response->nbtodo++;
4768 $response->total += $obj->total_ht;
4770 if ($generic_facture->hasDelay()) {
4771 $response->nbtodolate++;
4772 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4780 $this->error = $this->
db->error();
4819 global $conf, $langs, $user;
4823 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
4828 $sql =
"SELECT rowid";
4829 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
4830 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
4831 $sql .= $this->
db->plimit(100);
4835 $num_prods = $this->
db->num_rows(
$resql);
4837 while ($i < $num_prods) {
4839 $row = $this->
db->fetch_row(
$resql);
4840 $prodids[$i] = $row[0];
4844 if (empty($num_prods)) {
4851 $this->
ref =
'SPECIMEN';
4852 $this->specimen = 1;
4854 $this->date = $nownotime;
4855 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4856 $this->cond_reglement_id = 1;
4857 $this->cond_reglement_code =
'RECEP';
4859 $this->mode_reglement_id = 0;
4860 $this->mode_reglement_code =
'';
4862 $this->note_public =
'This is a comment (public)';
4863 $this->note_private =
'This is a comment (private)';
4864 $this->note =
'This is a comment (private)';
4866 $this->fk_user_author = $user->id;
4868 $this->multicurrency_tx = 1;
4869 $this->multicurrency_code = $conf->currency;
4871 $this->fk_incoterms = 0;
4872 $this->location_incoterms =
'';
4874 if (empty($option) || $option !=
'nolines') {
4878 while ($xnbp < $nbp) {
4880 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
4882 $line->subprice = 100;
4883 $line->tva_tx = 19.6;
4884 $line->localtax1_tx = 0;
4885 $line->localtax2_tx = 0;
4886 $line->remise_percent = 0;
4888 $prodid = mt_rand(1, $num_prods);
4889 $line->fk_product = $prodids[$prodid];
4891 $line->total_ht = -100;
4892 $line->total_ttc = -119.6;
4893 $line->total_tva = -19.6;
4894 $line->multicurrency_total_ht = -200;
4895 $line->multicurrency_total_ttc = -239.2;
4896 $line->multicurrency_total_tva = -39.2;
4897 } elseif ($xnbp == 2) {
4898 $line->subprice = -100;
4899 $line->total_ht = -100;
4900 $line->total_ttc = -119.6;
4901 $line->total_tva = -19.6;
4902 $line->remise_percent = 0;
4903 $line->multicurrency_total_ht = -200;
4904 $line->multicurrency_total_ttc = -239.2;
4905 $line->multicurrency_total_tva = -39.2;
4906 } elseif ($xnbp == 3) {
4907 $prodid = mt_rand(1, $num_prods);
4908 $line->fk_product = $prodids[$prodid];
4909 $line->total_ht = 50;
4910 $line->total_ttc = 59.8;
4911 $line->total_tva = 9.8;
4912 $line->multicurrency_total_ht = 100;
4913 $line->multicurrency_total_ttc = 119.6;
4914 $line->multicurrency_total_tva = 19.6;
4915 $line->remise_percent = 50;
4918 $prodid = mt_rand(1, $num_prods);
4919 $line->fk_product = $prodids[$prodid];
4920 $line->total_ht = 100;
4921 $line->total_ttc = 119.6;
4922 $line->total_tva = 19.6;
4923 $line->multicurrency_total_ht = 200;
4924 $line->multicurrency_total_ttc = 239.2;
4925 $line->multicurrency_total_tva = 39.2;
4926 $line->remise_percent = 0;
4929 $this->lines[$xnbp] = $line;
4932 $this->total_ht += $line->total_ht;
4933 $this->total_tva += $line->total_tva;
4934 $this->total_ttc += $line->total_ttc;
4936 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4937 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4938 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4942 $this->revenuestamp = 0;
4946 $line->desc = $langs->trans(
"Description").
" (offered line)";
4948 $line->subprice = 100;
4949 $line->tva_tx = 19.6;
4950 $line->localtax1_tx = 0;
4951 $line->localtax2_tx = 0;
4952 $line->remise_percent = 100;
4953 $line->total_ht = 0;
4954 $line->total_ttc = 0;
4955 $line->total_tva = 0;
4956 $line->multicurrency_total_ht = 0;
4957 $line->multicurrency_total_ttc = 0;
4958 $line->multicurrency_total_tva = 0;
4959 $prodid = mt_rand(1, $num_prods);
4960 $line->fk_product = $prodids[$prodid];
4962 $this->lines[$xnbp] = $line;
4976 global $conf, $user;
4978 $this->nb = array();
4982 $sql =
"SELECT count(f.rowid) as nb";
4983 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4984 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
4985 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4986 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4987 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4990 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
4994 while ($obj = $this->
db->fetch_object(
$resql)) {
4995 $this->nb[
"invoices"] = $obj->nb;
5001 $this->error = $this->
db->error();
5027 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5029 global $conf, $langs;
5031 $outputlangs->loadLangs(array(
"bills",
"products"));
5035 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5037 if (!empty($this->model_pdf)) {
5038 $modele = $this->model_pdf;
5039 } elseif (!empty($this->modelpdf)) {
5040 $modele = $this->modelpdf;
5041 } elseif (!empty($conf->global->$thisTypeConfName)) {
5042 $modele = $conf->global->$thisTypeConfName;
5043 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
5044 $modele = $conf->global->FACTURE_ADDON_PDF;
5048 $modelpath =
"core/modules/facture/doc/";
5050 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5060 $sql =
'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.
'facture as f';
5061 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5064 if ($this->
db->num_rows(
$resql) > 0) {
5065 $res = $this->
db->fetch_array(
$resql);
5066 $ref = $res[
'max(situation_cycle_ref)'];
5074 $this->error = $this->
db->lasterror();
5075 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5089 return ($this->situation_counter == 1);
5103 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5104 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5105 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5106 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5110 while ($row = $this->
db->fetch_object(
$resql)) {
5113 $situation->fetch($id);
5114 $res[] = $situation;
5117 $this->error = $this->
db->error();
5118 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5138 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5143 $this->errors[] = $this->
db->error();
5147 if (!$notrigger && empty($error)) {
5157 $this->
db->commit();
5160 foreach ($this->errors as $errmsg) {
5161 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5162 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5164 $this->
db->rollback();
5180 if (!empty($this->situation_cycle_ref)) {
5182 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5183 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5184 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5188 $res = $this->
db->fetch_array(
$resql);
5189 $last = $res[
'max(situation_counter)'];
5190 return ($last == $this->situation_counter);
5192 $this->error = $this->
db->lasterror();
5193 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5251 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5252 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5254 $totalpaid = floatval($totalpaid);
5256 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5257 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5259 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5282 $displayWarranty =
false;
5283 if (!empty($this->retained_warranty)) {
5284 $displayWarranty =
true;
5288 $displayWarranty =
false;
5289 if (!empty($this->situation_final)) {
5290 $displayWarranty =
true;
5293 $displayWarranty =
true;
5295 foreach ($this->lines as $i => $line) {
5296 if ($line->product_type < 2 && $line->situation_percent < 100) {
5297 $displayWarranty =
false;
5305 return $displayWarranty;
5315 if (empty($this->retained_warranty)) {
5319 $retainedWarrantyAmount = 0;
5323 $displayWarranty =
true;
5325 if (!empty($this->lines)) {
5326 foreach ($this->lines as $i => $line) {
5327 if ($line->product_type < 2 && $line->situation_percent < 100) {
5328 $displayWarranty =
false;
5334 if ($displayWarranty && !empty($this->situation_final)) {
5336 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5339 foreach ($TPreviousIncoice as &$fac) {
5340 $total2BillWT += $fac->total_ttc;
5342 $total2BillWT += $this->total_ttc;
5344 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5350 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5353 if ($rounding < 0) {
5354 $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5357 if ($rounding > 0) {
5358 return round($retainedWarrantyAmount, $rounding);
5361 return $retainedWarrantyAmount;
5372 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5374 if ($this->statut >= 0) {
5375 $fieldname =
'retained_warranty';
5376 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5377 $sql .=
" SET ".$fieldname.
" = ".((
float) $value);
5378 $sql .=
' WHERE rowid='.((int) $this->
id);
5380 if ($this->
db->query($sql)) {
5381 $this->retained_warranty = floatval($value);
5384 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5385 $this->error = $this->
db->error();
5389 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5390 $this->error =
'Status of the object is incompatible '.$this->statut;
5405 if (!$timestamp && $dateYmd) {
5406 $timestamp = $this->
db->jdate($dateYmd);
5410 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5411 if ($this->statut >= 0) {
5412 $fieldname =
'retained_warranty_date_limit';
5413 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5414 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5415 $sql .=
' WHERE rowid = '.((int) $this->
id);
5417 if ($this->
db->query($sql)) {
5418 $this->retained_warranty_date_limit = $timestamp;
5421 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5422 $this->error = $this->
db->error();
5426 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5427 $this->error =
'Status of the object is incompatible '.$this->statut;
5445 global $conf, $langs, $user;
5451 $errorsMsg = array();
5453 $langs->load(
"bills");
5456 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5466 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5467 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5468 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5479 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5480 if (!empty($paymentmode) && $paymentmode !=
'all') {
5481 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5483 $sql .=
" WHERE f.paye = 0";
5484 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5485 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5486 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
5487 if (!empty($paymentmode) && $paymentmode !=
'all') {
5488 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5491 $sql .= $this->
db->order(
"date_lim_reglement",
"ASC");
5496 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5497 if (!empty($paymentmode) && $paymentmode !=
'all') {
5498 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5500 $this->output .=
'<br>';
5503 while ($obj = $this->
db->fetch_object(
$resql)) {
5506 $res = $tmpinvoice->fetch($obj->id);
5508 $tmpinvoice->fetch_thirdparty();
5510 $outputlangs =
new Translate(
'', $conf);
5511 if ($tmpinvoice->thirdparty->default_lang) {
5512 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5513 $outputlangs->loadLangs(array(
"main",
"bills"));
5515 $outputlangs = $langs;
5519 $arraymessage = $formmail->getEMailTemplate($this->
db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5520 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5521 $langs->load(
"errors");
5522 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5535 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5538 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5544 if ($forcerecipient) {
5545 $to = array($forcerecipient);
5547 $res = $tmpinvoice->fetch_thirdparty();
5548 $recipient = $tmpinvoice->thirdparty;
5550 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
5551 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5552 foreach ($tmparraycontact as $data_email) {
5553 if (!empty($data_email[
'email'])) {
5554 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
5558 if (empty($to) && !empty($recipient->email)) {
5559 $to[] = $recipient->email;
5561 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for user.";
5565 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5572 if (!empty($arraymessage->email_from)) {
5573 $from = $arraymessage->email_from;
5576 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5580 if (!$error && !empty($to)) {
5583 $to = implode(
',', $to);
5584 if (!empty($arraymessage->email_to)) {
5585 $to = $to.
','.$arraymessage->email_to;
5589 $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
5591 $trackid =
'inv'.$tmpinvoice->id;
5592 $sendcontext =
'standard';
5595 if (!empty($arraymessage->email_tocc)) {
5596 $email_tocc = $arraymessage->email_tocc;
5600 if (!empty($arraymessage->email_tobcc)) {
5601 $email_tobcc = $arraymessage->email_tobcc;
5605 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5608 if ($cMailFile->sendfile()) {
5612 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5617 $actioncomm->type_code =
'AC_OTH_AUTO';
5618 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5619 $actioncomm->contact_id = 0;
5621 $actioncomm->code =
'AC_EMAIL';
5622 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK';
5623 $actioncomm->note_private = $sendContent;
5624 $actioncomm->fk_project = $tmpinvoice->fk_project;
5625 $actioncomm->datep =
dol_now();
5626 $actioncomm->datef = $actioncomm->datep;
5627 $actioncomm->percentage = -1;
5628 $actioncomm->authorid = $user->id;
5629 $actioncomm->userownerid = $user->id;
5631 $actioncomm->email_msgid = $cMailFile->msgid;
5632 $actioncomm->email_from = $from;
5633 $actioncomm->email_sender =
'';
5634 $actioncomm->email_to = $to;
5638 $actioncomm->errors_to = $errors_to;
5640 $actioncomm->elementtype =
'invoice';
5641 $actioncomm->fk_element = $tmpinvoice->id;
5645 $actioncomm->create($user);
5647 $errormesg = $cMailFile->error.
' : '.$to;
5651 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5656 $actioncomm->type_code =
'AC_OTH_AUTO';
5657 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5658 $actioncomm->contact_id = 0;
5660 $actioncomm->code =
'AC_EMAIL';
5661 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5662 $actioncomm->note_private = $errormesg;
5663 $actioncomm->fk_project = $tmpinvoice->fk_project;
5664 $actioncomm->datep =
dol_now();
5665 $actioncomm->datef = $actioncomm->datep;
5666 $actioncomm->percentage = -1;
5667 $actioncomm->authorid = $user->id;
5668 $actioncomm->userownerid = $user->id;
5670 $actioncomm->email_msgid = $cMailFile->msgid;
5671 $actioncomm->email_from = $from;
5672 $actioncomm->email_sender =
'';
5673 $actioncomm->email_to = $to;
5677 $actioncomm->errors_to = $errors_to;
5681 $actioncomm->create($user);
5684 $this->
db->commit();
5688 $errorsMsg[] = $errormesg;
5691 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
5701 $this->output .=
'Nb of emails sent : '.$nbMailSend;
5704 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg)) ? join(
', ', $errorsMsg) : $error;
5718 $sql =
"SELECT datef";
5719 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
5720 $sql .=
" WHERE type = " . (int) $this->
type ;
5721 $sql .=
" AND date_valid IS NOT NULL";
5722 $sql .=
" ORDER BY datef DESC LIMIT 1";
5724 $result = $this->
db->query($sql);
5727 if ($this->
db->num_rows($result)) {
5728 $obj = $this->
db->fetch_object($result);
5729 $last_date = $this->
db->jdate($obj->datef);
5730 $invoice_date = $this->date;
5732 $is_last_of_same_type = $invoice_date >= $last_date;
5733 if ($allow_validated_drafts) {
5734 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->
ref,
'PROV') && $this->status ==
self::STATUS_DRAFT);
5737 return array($is_last_of_same_type, $last_date);
5757 public $element =
'facturedet';
5762 public $table_element =
'facturedet';
5776 public $localtax1_type;
5777 public $localtax2_type;
5778 public $fk_remise_except;
5781 public $fk_fournprice;
5786 public $remise_percent;
5788 public $special_code;
5796 public $fk_code_ventilation = 0;
5801 public $skip_update_total;
5806 public $situation_percent;
5814 public $fk_multicurrency;
5815 public $multicurrency_code;
5816 public $multicurrency_subprice;
5817 public $multicurrency_total_ht;
5818 public $multicurrency_total_tva;
5819 public $multicurrency_total_ttc;
5829 $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,';
5830 $sql .=
' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
5831 $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,';
5832 $sql .=
' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
5833 $sql .=
' fd.fk_code_ventilation,';
5834 $sql .=
' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
5835 $sql .=
' fd.situation_percent, fd.fk_prev_id,';
5836 $sql .=
' fd.multicurrency_subprice,';
5837 $sql .=
' fd.multicurrency_total_ht,';
5838 $sql .=
' fd.multicurrency_total_tva,';
5839 $sql .=
' fd.multicurrency_total_ttc,';
5840 $sql .=
' p.ref as product_ref, p.label as product_label, p.description as product_desc';
5841 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as fd';
5842 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON fd.fk_product = p.rowid';
5843 $sql .=
' WHERE fd.rowid = '.((int) $rowid);
5845 $result = $this->
db->query($sql);
5847 $objp = $this->
db->fetch_object($result);
5850 $this->error =
'InvoiceLine with id '. $rowid .
' not found sql='.$sql;
5854 $this->
rowid = $objp->rowid;
5855 $this->
id = $objp->rowid;
5856 $this->fk_facture = $objp->fk_facture;
5857 $this->fk_parent_line = $objp->fk_parent_line;
5858 $this->label = $objp->custom_label;
5859 $this->desc = $objp->description;
5860 $this->qty = $objp->qty;
5861 $this->subprice = $objp->subprice;
5862 $this->ref_ext = $objp->ref_ext;
5863 $this->vat_src_code = $objp->vat_src_code;
5864 $this->tva_tx = $objp->tva_tx;
5865 $this->localtax1_tx = $objp->localtax1_tx;
5866 $this->localtax2_tx = $objp->localtax2_tx;
5867 $this->remise_percent = $objp->remise_percent;
5868 $this->fk_remise_except = $objp->fk_remise_except;
5869 $this->fk_product = $objp->fk_product;
5870 $this->product_type = $objp->product_type;
5871 $this->date_start = $this->
db->jdate($objp->date_start);
5872 $this->date_end = $this->
db->jdate($objp->date_end);
5873 $this->info_bits = $objp->info_bits;
5874 $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
5875 $this->special_code = $objp->special_code;
5876 $this->total_ht = $objp->total_ht;
5877 $this->total_tva = $objp->total_tva;
5878 $this->total_localtax1 = $objp->total_localtax1;
5879 $this->total_localtax2 = $objp->total_localtax2;
5880 $this->total_ttc = $objp->total_ttc;
5881 $this->fk_code_ventilation = $objp->fk_code_ventilation;
5882 $this->rang = $objp->rang;
5883 $this->fk_fournprice = $objp->fk_fournprice;
5884 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
5885 $this->pa_ht = $marginInfos[0];
5886 $this->marge_tx = $marginInfos[1];
5887 $this->marque_tx = $marginInfos[2];
5889 $this->
ref = $objp->product_ref;
5891 $this->product_ref = $objp->product_ref;
5892 $this->product_label = $objp->product_label;
5893 $this->product_desc = $objp->product_desc;
5895 $this->fk_unit = $objp->fk_unit;
5896 $this->fk_user_modif = $objp->fk_user_modif;
5897 $this->fk_user_author = $objp->fk_user_author;
5899 $this->situation_percent = $objp->situation_percent;
5900 $this->fk_prev_id = $objp->fk_prev_id;
5902 $this->multicurrency_subprice = $objp->multicurrency_subprice;
5903 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
5904 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
5905 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
5907 $this->
db->free($result);
5911 $this->error = $this->
db->lasterror();
5923 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
5925 global $langs, $user, $conf;
5929 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
5931 dol_syslog(get_class($this).
"::insert rang=".$this->rang, LOG_DEBUG);
5934 $this->desc = trim($this->desc);
5935 if (empty($this->tva_tx)) {
5938 if (empty($this->localtax1_tx)) {
5939 $this->localtax1_tx = 0;
5941 if (empty($this->localtax2_tx)) {
5942 $this->localtax2_tx = 0;
5944 if (empty($this->localtax1_type)) {
5945 $this->localtax1_type = 0;
5947 if (empty($this->localtax2_type)) {
5948 $this->localtax2_type = 0;
5950 if (empty($this->total_localtax1)) {
5951 $this->total_localtax1 = 0;
5953 if (empty($this->total_localtax2)) {
5954 $this->total_localtax2 = 0;
5956 if (empty($this->rang)) {
5959 if (empty($this->remise_percent)) {
5960 $this->remise_percent = 0;
5962 if (empty($this->info_bits)) {
5963 $this->info_bits = 0;
5965 if (empty($this->subprice)) {
5966 $this->subprice = 0;
5968 if (empty($this->ref_ext)) {
5969 $this->ref_ext =
'';
5971 if (empty($this->special_code)) {
5972 $this->special_code = 0;
5974 if (empty($this->fk_parent_line)) {
5975 $this->fk_parent_line = 0;
5977 if (empty($this->fk_prev_id)) {
5978 $this->fk_prev_id = 0;
5980 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
5981 $this->situation_percent = 100;
5984 if (empty($this->pa_ht)) {
5987 if (empty($this->multicurrency_subprice)) {
5988 $this->multicurrency_subprice = 0;
5990 if (empty($this->multicurrency_total_ht)) {
5991 $this->multicurrency_total_ht = 0;
5993 if (empty($this->multicurrency_total_tva)) {
5994 $this->multicurrency_total_tva = 0;
5996 if (empty($this->multicurrency_total_ttc)) {
5997 $this->multicurrency_total_ttc = 0;
6001 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6002 if (($result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
6005 $this->pa_ht = $result;
6010 if ($this->product_type < 0) {
6011 $this->error =
'ErrorProductTypeMustBe0orMore';
6014 if (!empty($this->fk_product) && $this->fk_product > 0) {
6018 $this->error =
'ErrorProductIdDoesNotExists';
6019 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6027 $sql =
'INSERT INTO '.MAIN_DB_PREFIX.
'facturedet';
6028 $sql .=
' (fk_facture, fk_parent_line, label, description, qty,';
6029 $sql .=
' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6030 $sql .=
' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6031 $sql .=
' date_start, date_end, fk_code_ventilation, ';
6032 $sql .=
' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6033 $sql .=
' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6034 $sql .=
' situation_percent, fk_prev_id,';
6035 $sql .=
' fk_unit, fk_user_author, fk_user_modif,';
6036 $sql .=
' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
6038 $sql .=
" VALUES (".$this->fk_facture.
",";
6039 $sql .=
" ".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null").
",";
6040 $sql .=
" ".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null").
",";
6041 $sql .=
" '".$this->db->escape($this->desc).
"',";
6042 $sql .=
" ".price2num($this->qty).
",";
6043 $sql .=
" ".(empty($this->vat_src_code) ?
"''" :
"'".$this->db->escape($this->vat_src_code).
"'").
",";
6044 $sql .=
" ".price2num($this->tva_tx).
",";
6045 $sql .=
" ".price2num($this->localtax1_tx).
",";
6046 $sql .=
" ".price2num($this->localtax2_tx).
",";
6047 $sql .=
" '".$this->db->escape($this->localtax1_type).
"',";
6048 $sql .=
" '".$this->db->escape($this->localtax2_type).
"',";
6049 $sql .=
' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product :
"null").
',';
6050 $sql .=
" ".((int) $this->product_type).
",";
6051 $sql .=
" ".price2num($this->remise_percent).
",";
6052 $sql .=
" ".price2num($this->subprice).
",";
6053 $sql .=
" '".$this->db->escape($this->ref_ext).
"',";
6054 $sql .=
' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except :
"null").
',';
6055 $sql .=
" ".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null").
",";
6056 $sql .=
" ".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null").
",";
6057 $sql .=
' '.((int) $this->fk_code_ventilation).
',';
6058 $sql .=
' '.((int) $this->rang).
',';
6059 $sql .=
' '.((int) $this->special_code).
',';
6060 $sql .=
' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice :
"null").
',';
6061 $sql .=
' '.price2num($this->pa_ht).
',';
6062 $sql .=
" '".$this->db->escape($this->info_bits).
"',";
6063 $sql .=
" ".price2num($this->total_ht).
",";
6064 $sql .=
" ".price2num($this->total_tva).
",";
6065 $sql .=
" ".price2num($this->total_ttc).
",";
6066 $sql .=
" ".price2num($this->total_localtax1).
",";
6067 $sql .=
" ".price2num($this->total_localtax2);
6068 $sql .=
", ".((float) $this->situation_percent);
6069 $sql .=
", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id :
"null");
6070 $sql .=
", ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6071 $sql .=
", ".((int) $user->id);
6072 $sql .=
", ".((int) $user->id);
6073 $sql .=
", ".(int) $this->fk_multicurrency;
6074 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
6075 $sql .=
", ".price2num($this->multicurrency_subprice);
6076 $sql .=
", ".price2num($this->multicurrency_total_ht);
6077 $sql .=
", ".price2num($this->multicurrency_total_tva);
6078 $sql .=
", ".price2num($this->multicurrency_total_ttc);
6081 dol_syslog(get_class($this).
"::insert", LOG_DEBUG);
6084 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facturedet');
6085 $this->
rowid = $this->id;
6096 if ($this->fk_remise_except) {
6098 $result = $discount->fetch($this->fk_remise_except);
6103 if ($discount->fk_facture_line > 0) {
6104 if (empty($noerrorifdiscountalreadylinked)) {
6105 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed", $discount->id);
6106 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6107 $this->
db->rollback();
6111 $result = $discount->link_to_invoice($this->
rowid, 0);
6113 $this->error = $discount->error;
6114 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6115 $this->
db->rollback();
6120 $this->error = $langs->trans(
"ErrorADiscountThatHasBeenRemovedIsIncluded");
6121 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6122 $this->
db->rollback();
6126 $this->error = $discount->error;
6127 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6128 $this->
db->rollback();
6135 $result = $this->
call_trigger(
'LINEBILL_INSERT', $user);
6137 $this->
db->rollback();
6143 $this->
db->commit();
6146 $this->error = $this->
db->lasterror();
6147 $this->
db->rollback();
6159 public function update($user =
'', $notrigger = 0)
6161 global $user, $conf;
6165 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6168 $this->desc = trim($this->desc);
6169 if (empty($this->ref_ext)) {
6170 $this->ref_ext =
'';
6172 if (empty($this->tva_tx)) {
6175 if (empty($this->localtax1_tx)) {
6176 $this->localtax1_tx = 0;
6178 if (empty($this->localtax2_tx)) {
6179 $this->localtax2_tx = 0;
6181 if (empty($this->localtax1_type)) {
6182 $this->localtax1_type = 0;
6184 if (empty($this->localtax2_type)) {
6185 $this->localtax2_type = 0;
6187 if (empty($this->total_localtax1)) {
6188 $this->total_localtax1 = 0;
6190 if (empty($this->total_localtax2)) {
6191 $this->total_localtax2 = 0;
6193 if (empty($this->remise_percent)) {
6194 $this->remise_percent = 0;
6196 if (empty($this->info_bits)) {
6197 $this->info_bits = 0;
6199 if (empty($this->special_code)) {
6200 $this->special_code = 0;
6202 if (empty($this->product_type)) {
6203 $this->product_type = 0;
6205 if (empty($this->fk_parent_line)) {
6206 $this->fk_parent_line = 0;
6208 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6209 $this->situation_percent = 100;
6211 if (empty($this->pa_ht)) {
6215 if (empty($this->multicurrency_subprice)) {
6216 $this->multicurrency_subprice = 0;
6218 if (empty($this->multicurrency_total_ht)) {
6219 $this->multicurrency_total_ht = 0;
6221 if (empty($this->multicurrency_total_tva)) {
6222 $this->multicurrency_total_tva = 0;
6224 if (empty($this->multicurrency_total_ttc)) {
6225 $this->multicurrency_total_ttc = 0;
6229 if ($this->product_type < 0) {
6234 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6236 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6240 $this->pa_ht = $result;
6247 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6248 $sql .=
" description='".$this->db->escape($this->desc).
"'";
6249 $sql .=
", ref_ext='".$this->db->escape($this->ref_ext).
"'";
6250 $sql .=
", label=".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null");
6251 $sql .=
", subprice=".price2num($this->subprice);
6252 $sql .=
", remise_percent=".price2num($this->remise_percent);
6253 if ($this->fk_remise_except) {
6254 $sql .=
", fk_remise_except=".$this->fk_remise_except;
6256 $sql .=
", fk_remise_except=null";
6258 $sql .=
", vat_src_code = '".(empty($this->vat_src_code) ?
'' : $this->
db->escape($this->vat_src_code)).
"'";
6259 $sql .=
", tva_tx=".price2num($this->tva_tx);
6260 $sql .=
", localtax1_tx=".price2num($this->localtax1_tx);
6261 $sql .=
", localtax2_tx=".price2num($this->localtax2_tx);
6262 $sql .=
", localtax1_type='".$this->db->escape($this->localtax1_type).
"'";
6263 $sql .=
", localtax2_type='".$this->db->escape($this->localtax2_type).
"'";
6264 $sql .=
", qty=".price2num($this->qty);
6265 $sql .=
", date_start=".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null");
6266 $sql .=
", date_end=".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null");
6267 $sql .=
", product_type=".$this->product_type;
6268 $sql .=
", info_bits='".$this->db->escape($this->info_bits).
"'";
6269 $sql .=
", special_code='".$this->db->escape($this->special_code).
"'";
6270 if (empty($this->skip_update_total)) {
6271 $sql .=
", total_ht=".price2num($this->total_ht);
6272 $sql .=
", total_tva=".price2num($this->total_tva);
6273 $sql .=
", total_ttc=".price2num($this->total_ttc);
6274 $sql .=
", total_localtax1=".price2num($this->total_localtax1);
6275 $sql .=
", total_localtax2=".price2num($this->total_localtax2);
6277 $sql .=
", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ?
"'".$this->db->escape($this->fk_fournprice).
"'" :
"null");
6278 $sql .=
", buy_price_ht=".(($this->pa_ht || (string) $this->pa_ht ===
'0') ?
price2num($this->pa_ht) :
"null");
6279 $sql .=
", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null");
6280 if (!empty($this->rang)) {
6281 $sql .=
", rang=".((int) $this->rang);
6283 $sql .=
", situation_percent = ".((float) $this->situation_percent);
6284 $sql .=
", fk_unit = ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6285 $sql .=
", fk_user_modif = ".((int) $user->id);
6288 $sql .=
", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6289 $sql .=
", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6290 $sql .=
", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6291 $sql .=
", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6293 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6295 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
6299 $this->
id = $this->rowid;
6306 if (!$error && !$notrigger) {
6308 $result = $this->
call_trigger(
'LINEBILL_MODIFY', $user);
6310 $this->
db->rollback();
6315 $this->
db->commit();
6318 $this->error = $this->
db->error();
6319 $this->
db->rollback();
6331 public function delete($tmpuser =
null, $notrigger =
false)
6338 if (empty($notrigger)) {
6339 $result = $this->
call_trigger(
'LINEBILL_DELETE', $user);
6341 $this->
db->rollback();
6350 $this->
db->rollback();
6354 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->
rowid);
6356 if ($this->
db->query($sql)) {
6357 $this->
db->commit();
6360 $this->error = $this->
db->error().
" sql=".$sql;
6361 $this->
db->rollback();
6377 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6380 if (empty($this->total_localtax1)) {
6381 $this->total_localtax1 = 0;
6383 if (empty($this->total_localtax2)) {
6384 $this->total_localtax2 = 0;
6388 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6389 $sql .=
" total_ht=".price2num($this->total_ht);
6390 $sql .=
",total_tva=".price2num($this->total_tva);
6391 $sql .=
",total_localtax1=".price2num($this->total_localtax1);
6392 $sql .=
",total_localtax2=".price2num($this->total_localtax2);
6393 $sql .=
",total_ttc=".price2num($this->total_ttc);
6394 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6396 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6400 $this->
db->commit();
6403 $this->error = $this->
db->error();
6404 $this->
db->rollback();
6421 global $invoicecache;
6422 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6426 if (!isset($invoicecache[$invoiceid])) {
6427 $invoicecache[$invoiceid] =
new Facture($this->
db);
6428 $invoicecache[$invoiceid]->fetch($invoiceid);
6434 $sql =
"SELECT situation_percent FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->fk_prev_id);
6437 $res = $this->
db->fetch_array(
$resql);
6439 $returnPercent = floatval($res[
'situation_percent']);
6441 if ($include_credit_note) {
6442 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6443 $sql .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6444 $sql .=
" WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6445 $sql .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6446 $sql .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6448 $res = $this->
db->query($sql);
6450 while ($obj = $this->
db->fetch_object($res)) {
6451 $returnPercent = $returnPercent + floatval($obj->situation_percent);
6458 return $returnPercent;
6460 $this->error = $this->
db->error();
6461 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6462 $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 commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty 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 commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts.
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 ivoices 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...
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
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.
deleteline($rowid, $id=0)
Delete line in database.
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.
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_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.