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'=>
'html',
'label'=>
'NotePrivate',
'enabled'=>1,
'visible'=>0,
'position'=>205),
345 'note_public' =>array(
'type'=>
'html',
'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;
723 $resql = $this->
db->query(
$sql);
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);
731 $resql = $this->
db->query(
$sql);
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 =
'';
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);
1339 unset($object->context[
'createfromclone']);
1343 $this->
db->commit();
1346 $this->
db->rollback();
1360 global $conf, $hookmanager;
1368 $num = count($object->lines);
1369 for ($i = 0; $i < $num; $i++) {
1372 $line->libelle = $object->lines[$i]->libelle;
1373 $line->label = $object->lines[$i]->label;
1374 $line->desc = $object->lines[$i]->desc;
1375 $line->subprice = $object->lines[$i]->subprice;
1376 $line->total_ht = $object->lines[$i]->total_ht;
1377 $line->total_tva = $object->lines[$i]->total_tva;
1378 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1379 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1380 $line->total_ttc = $object->lines[$i]->total_ttc;
1381 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1382 $line->tva_tx = $object->lines[$i]->tva_tx;
1383 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1384 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1385 $line->qty = $object->lines[$i]->qty;
1386 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1387 $line->remise_percent = $object->lines[$i]->remise_percent;
1388 $line->fk_product = $object->lines[$i]->fk_product;
1389 $line->info_bits = $object->lines[$i]->info_bits;
1390 $line->product_type = $object->lines[$i]->product_type;
1391 $line->rang = $object->lines[$i]->rang;
1392 $line->special_code = $object->lines[$i]->special_code;
1393 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1394 $line->fk_unit = $object->lines[$i]->fk_unit;
1395 $line->date_start = $object->lines[$i]->date_start;
1396 $line->date_end = $object->lines[$i]->date_end;
1399 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1400 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1401 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1402 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1403 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1404 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1406 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1407 $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);
1408 $line->pa_ht = $marginInfos[0];
1411 $object->lines[$i]->fetch_optionals();
1412 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1413 $line->array_options[$options_key] = $value;
1416 $this->lines[$i] = $line;
1419 $this->socid = $object->socid;
1420 $this->fk_project = $object->fk_project;
1421 $this->fk_account = $object->fk_account;
1422 $this->cond_reglement_id = $object->cond_reglement_id;
1423 $this->mode_reglement_id = $object->mode_reglement_id;
1424 $this->availability_id = $object->availability_id;
1425 $this->demand_reason_id = $object->demand_reason_id;
1426 $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
1427 $this->date_livraison = $object->delivery_date;
1428 $this->fk_delivery_address = $object->fk_delivery_address;
1429 $this->contact_id = $object->contact_id;
1430 $this->ref_client = $object->ref_client;
1432 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1433 $this->note_private = $object->note_private;
1434 $this->note_public = $object->note_public;
1437 $this->module_source = $object->module_source;
1438 $this->pos_source = $object->pos_source;
1440 $this->origin = $object->element;
1441 $this->origin_id = $object->id;
1443 $this->fk_user_author = $user->id;
1446 $object->fetch_optionals();
1447 foreach ($object->array_options as $options_key => $value) {
1448 $this->array_options[$options_key] = $value;
1452 $this->linked_objects[$this->origin] = $this->origin_id;
1453 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1454 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1457 $ret = $this->
create($user);
1461 $hookmanager->initHooks(array(
'invoicedao'));
1463 $parameters = array(
'objFrom'=>$object);
1465 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1495 global $conf, $langs, $hookmanager, $action;
1497 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1498 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1503 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1507 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1509 if ($date > (
dol_get_last_hour(
dol_now(
'tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1510 $origin->error =
'ErrorDateIsInFuture';
1514 if ($payment_terms_id <= 0) {
1515 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1519 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1521 if (empty($payment_conditions_deposit_percent)) {
1522 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1526 if (empty($origin->deposit_percent)) {
1527 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1531 $deposit =
new self($origin->db);
1532 $deposit->socid = $origin->socid;
1534 $deposit->fk_project = $origin->fk_project;
1535 $deposit->ref_client = $origin->ref_client;
1536 $deposit->date = $date;
1537 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1538 $deposit->cond_reglement_id = $payment_terms_id;
1539 $deposit->availability_id = $origin->availability_id;
1540 $deposit->demand_reason_id = $origin->demand_reason_id;
1541 $deposit->fk_account = $origin->fk_account;
1542 $deposit->fk_incoterms = $origin->fk_incoterms;
1543 $deposit->location_incoterms = $origin->location_incoterms;
1544 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1545 $deposit->multicurrency_code = $origin->multicurrency_code;
1546 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1547 $deposit->module_source = $origin->module_source;
1548 $deposit->pos_source = $origin->pos_source;
1549 $deposit->model_pdf =
'crabe';
1551 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1553 if (!empty($conf->global->$modelByTypeConfName)) {
1554 $deposit->model_pdf = $conf->global->$modelByTypeConfName;
1555 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
1556 $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
1559 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1560 $deposit->note_private = $origin->note_private;
1561 $deposit->note_public = $origin->note_public;
1564 $deposit->origin = $origin->element;
1565 $deposit->origin_id = $origin->id;
1567 $origin->fetch_optionals();
1569 foreach ($origin->array_options as $extrakey => $value) {
1570 $deposit->array_options[$extrakey] = $value;
1573 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1575 foreach ($overrideFields as $key => $value) {
1576 $deposit->$key = $value;
1579 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1581 $origin->db->begin();
1584 $createReturn = $deposit->create($user, $notrigger);
1586 if ($createReturn <= 0) {
1587 $origin->db->rollback();
1588 $origin->error = $deposit->error;
1589 $origin->errors = $deposit->errors;
1593 $amount_ttc_diff = 0;
1594 $amountdeposit = array();
1595 $descriptions = array();
1597 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1598 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1600 $TTotalByTva = array();
1601 foreach ($origin->lines as &$line) {
1602 if (!empty($line->special_code)) {
1605 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1606 $descriptions[$line->tva_tx] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1607 $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1608 $descriptions[$line->tva_tx] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1609 $descriptions[$line->tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1612 foreach ($TTotalByTva as $tva => &$total) {
1613 $coef = $total / $origin->total_ttc;
1614 $am = $amount * $coef;
1615 $amount_ttc_diff += $am;
1616 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1620 $lines = $origin->lines;
1621 $numlines = count($lines);
1622 for ($i = 0; $i < $numlines; $i++) {
1623 if (empty($lines[$i]->qty)) {
1626 if (!empty($lines[$i]->special_code)) {
1630 $totalamount += $lines[$i]->total_ht;
1631 $tva_tx = $lines[$i]->tva_tx;
1632 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1633 $descriptions[$tva_tx] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1634 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1635 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1636 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1639 if ($totalamount == 0) {
1640 $amountdeposit[0] = 0;
1643 $amount_ttc_diff = $amountdeposit[0];
1646 foreach ($amountdeposit as $tva => $amount) {
1647 if (empty($amount)) {
1651 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1654 if (!empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && !empty($descriptions[$tva])) {
1655 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1658 $addlineResult = $deposit->addline(
1665 (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1685 if ($addlineResult < 0) {
1686 $origin->db->rollback();
1687 $origin->error = $deposit->error;
1688 $origin->errors = $deposit->errors;
1693 $diff = $deposit->total_ttc - $amount_ttc_diff;
1695 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1696 $deposit->fetch_lines();
1697 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1699 $updatelineResult = $deposit->updateline(
1700 $deposit->lines[0]->id,
1701 $deposit->lines[0]->desc,
1703 $deposit->lines[0]->qty,
1704 $deposit->lines[0]->remise_percent,
1705 $deposit->lines[0]->date_start,
1706 $deposit->lines[0]->date_end,
1707 $deposit->lines[0]->tva_tx,
1711 $deposit->lines[0]->info_bits,
1712 $deposit->lines[0]->product_type,
1716 $deposit->lines[0]->pa_ht,
1717 $deposit->lines[0]->label,
1723 if ($updatelineResult < 0) {
1724 $origin->db->rollback();
1725 $origin->error = $deposit->error;
1726 $origin->errors = $deposit->errors;
1732 if (! is_object($hookmanager)) {
1733 require_once DOL_DOCUMENT_ROOT .
'/core/class/hookmanager.class.php';
1737 $hookmanager->initHooks(array(
'invoicedao'));
1739 $parameters = array(
'objFrom' => $origin);
1740 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1743 $origin->db->rollback();
1744 $origin->error = $hookmanager->error;
1745 $origin->errors = $hookmanager->errors;
1749 if (!empty($autoValidateDeposit)) {
1750 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1752 if ($validateReturn < 0) {
1753 $origin->db->rollback();
1754 $origin->error = $deposit->error;
1755 $origin->errors = $deposit->errors;
1760 unset($deposit->context[
'createdepositfromorigin']);
1762 $origin->db->commit();
1776 global $conf, $langs, $mysoc, $user;
1778 $langs->load(
'bills');
1781 $moretitle = $params[
'moretitle'] ??
'';
1782 $picto = $this->picto;
1783 if ($this->
type == self::TYPE_REPLACEMENT) {
1786 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1789 if ($this->
type == self::TYPE_DEPOSIT) {
1793 if ($user->hasRight(
"facture",
"read")) {
1794 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1795 if (isset($this->statut) && isset($this->alreadypaid)) {
1796 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->alreadypaid);
1798 $datas[
'picto'] .=
' '.$this->getLibType(1);
1800 $datas[
'picto'] =
' - '.$moretitle;
1802 if (!empty($this->
ref)) {
1803 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
1805 if (!empty($this->ref_customer)) {
1806 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
1808 if (!empty($this->date)) {
1809 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
1811 if (!empty($this->total_ht)) {
1812 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1814 if (!empty($this->total_tva)) {
1815 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1817 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1819 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1821 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1822 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1824 if (!empty($this->total_ttc)) {
1825 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1846 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
1848 global $langs, $conf, $user, $mysoc;
1850 if (!empty($conf->dol_no_mouse_hover)) {
1856 if ($option ==
'withdraw') {
1857 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
1859 $url = DOL_URL_ROOT.
'/compta/facture/card.php?facid='.$this->id;
1862 if (!$user->hasRight(
"facture",
"read")) {
1866 if ($option !==
'nolink') {
1868 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1869 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
1870 $add_save_lastsearch_values = 1;
1872 if ($add_save_lastsearch_values) {
1873 $url .=
'&save_lastsearch_values=1';
1881 $picto = $this->picto;
1882 if ($this->
type == self::TYPE_REPLACEMENT) {
1885 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1888 if ($this->
type == self::TYPE_DEPOSIT) {
1893 'objecttype' => $this->element,
1894 'moretitle' => $moretitle,
1895 'option' => $option,
1897 $classfortooltip =
'classfortooltip';
1900 $classfortooltip =
'classforajaxtooltip';
1901 $dataparams =
' data-params='.json_encode($params);
1906 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
1907 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
1908 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1909 $label = $langs->trans(
"Invoice");
1910 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
1913 $linkclose .=
' class="'.$classfortooltip.
'"';
1916 $linkstart =
'<a href="'.$url.
'"';
1917 $linkstart .= $linkclose.
'>';
1920 if ($option ==
'nolink') {
1925 $result .= $linkstart;
1927 $result .=
img_object(($notooltip ?
'' : $label), $picto, ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') : $dataparams.
' class="'.(($withpicto != 2) ?
'paddingright ' :
'').$classfortooltip.
'"'), 0, 0, $notooltip ? 0 : 1);
1929 if ($withpicto != 2) {
1930 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
1932 $result .= $linkend;
1934 if ($addlinktonotes) {
1935 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1938 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
1939 $result .=
' <span class="note inline-block">';
1940 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
1945 $result .=
'</span>';
1949 global $action, $hookmanager;
1950 $hookmanager->initHooks(array(
'invoicedao'));
1951 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value'=> $save_lastsearch_value,
'target' => $target);
1952 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
1954 $result = $hookmanager->resPrint;
1956 $result .= $hookmanager->resPrint;
1972 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused =
'', $fetch_situation =
false)
1974 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
1978 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.fk_soc';
1979 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
1980 $sql .=
', f.remise_percent, f.remise_absolue, f.remise';
1981 $sql .=
', f.datef as df, f.date_pointoftax';
1982 $sql .=
', f.date_lim_reglement as dlr';
1983 $sql .=
', f.datec as datec';
1984 $sql .=
', f.date_valid as datev';
1985 $sql .=
', f.tms as datem';
1986 $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';
1987 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
1988 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1989 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1990 $sql .=
', f.fk_account';
1991 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1992 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1993 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1994 $sql .=
', f.fk_incoterms, f.location_incoterms';
1995 $sql .=
', f.module_source, f.pos_source';
1996 $sql .=
", i.libelle as label_incoterms";
1997 $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";
1998 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
1999 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2000 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
2001 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2004 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2006 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2008 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2011 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2015 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2016 $resql = $this->
db->query(
$sql);
2018 if ($this->
db->num_rows($resql)) {
2019 $obj = $this->
db->fetch_object($resql);
2021 $this->
id = $obj->rowid;
2022 $this->entity = $obj->entity;
2024 $this->
ref = $obj->ref;
2025 $this->ref_client = $obj->ref_client;
2026 $this->ref_customer = $obj->ref_client;
2027 $this->ref_ext = $obj->ref_ext;
2028 $this->
type = $obj->type;
2029 $this->date = $this->
db->jdate($obj->df);
2030 $this->date_pointoftax = $this->
db->jdate($obj->date_pointoftax);
2031 $this->date_creation = $this->
db->jdate($obj->datec);
2032 $this->date_validation = $this->
db->jdate($obj->datev);
2033 $this->date_modification = $this->
db->jdate($obj->datem);
2034 $this->datem = $this->
db->jdate($obj->datem);
2035 $this->remise_percent = $obj->remise_percent;
2036 $this->remise_absolue = $obj->remise_absolue;
2037 $this->total_ht = $obj->total_ht;
2038 $this->total_tva = $obj->total_tva;
2039 $this->total_localtax1 = $obj->localtax1;
2040 $this->total_localtax2 = $obj->localtax2;
2041 $this->total_ttc = $obj->total_ttc;
2042 $this->revenuestamp = $obj->revenuestamp;
2043 $this->paye = $obj->paye;
2044 $this->close_code = $obj->close_code;
2045 $this->close_note = $obj->close_note;
2047 $this->socid = $obj->fk_soc;
2048 $this->thirdparty =
null;
2050 $this->fk_project = $obj->fk_project;
2051 $this->project =
null;
2053 $this->statut = $obj->fk_statut;
2054 $this->status = $obj->fk_statut;
2056 $this->date_lim_reglement = $this->
db->jdate($obj->dlr);
2057 $this->mode_reglement_id = $obj->fk_mode_reglement;
2058 $this->mode_reglement_code = $obj->mode_reglement_code;
2059 $this->mode_reglement = $obj->mode_reglement_libelle;
2060 $this->cond_reglement_id = $obj->fk_cond_reglement;
2061 $this->cond_reglement_code = $obj->cond_reglement_code;
2062 $this->cond_reglement = $obj->cond_reglement_libelle;
2063 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2064 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2065 $this->fk_facture_source = $obj->fk_facture_source;
2066 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2067 $this->note = $obj->note_private;
2068 $this->note_private = $obj->note_private;
2069 $this->note_public = $obj->note_public;
2070 $this->user_author = $obj->fk_user_author;
2071 $this->user_valid = $obj->fk_user_valid;
2072 $this->user_modification = $obj->fk_user_modif;
2073 $this->fk_user_author = $obj->fk_user_author;
2074 $this->fk_user_valid = $obj->fk_user_valid;
2075 $this->fk_user_modif = $obj->fk_user_modif;
2076 $this->model_pdf = $obj->model_pdf;
2077 $this->modelpdf = $obj->model_pdf;
2078 $this->last_main_doc = $obj->last_main_doc;
2079 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2080 $this->situation_counter = $obj->situation_counter;
2081 $this->situation_final = $obj->situation_final;
2082 $this->retained_warranty = $obj->retained_warranty;
2083 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2084 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2086 $this->extraparams = (array) json_decode($obj->extraparams,
true);
2089 $this->fk_incoterms = $obj->fk_incoterms;
2090 $this->location_incoterms = $obj->location_incoterms;
2091 $this->label_incoterms = $obj->label_incoterms;
2093 $this->module_source = $obj->module_source;
2094 $this->pos_source = $obj->pos_source;
2097 $this->fk_multicurrency = $obj->fk_multicurrency;
2098 $this->multicurrency_code = $obj->multicurrency_code;
2099 $this->multicurrency_tx = $obj->multicurrency_tx;
2100 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2101 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2102 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2104 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2108 if ($this->status == self::STATUS_DRAFT) {
2109 $this->brouillon = 1;
2117 $this->lines = array();
2121 $this->error = $this->
db->error();
2125 $this->
db->free($resql);
2129 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2131 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2135 $this->error = $this->
db->lasterror();
2150 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2153 global $langs, $conf;
2155 $this->lines = array();
2157 $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,';
2158 $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,';
2159 $sql .=
' l.situation_percent, l.fk_prev_id,';
2160 $sql .=
' l.rang, l.special_code,';
2161 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2162 $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,';
2163 $sql .=
' l.fk_unit,';
2164 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2165 $sql .=
' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2166 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2167 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2168 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2169 $sql .=
' ORDER BY l.rang, l.rowid';
2171 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2172 $result = $this->
db->query(
$sql);
2174 $num = $this->
db->num_rows($result);
2177 $objp = $this->
db->fetch_object($result);
2180 $line->id = $objp->rowid;
2181 $line->rowid = $objp->rowid;
2182 $line->fk_facture = $objp->fk_facture;
2183 $line->label = $objp->custom_label;
2184 $line->desc = $objp->description;
2185 $line->description = $objp->description;
2186 $line->product_type = $objp->product_type;
2187 $line->ref = $objp->product_ref;
2188 $line->product_ref = $objp->product_ref;
2189 $line->libelle = $objp->product_label;
2190 $line->product_label = $objp->product_label;
2191 $line->product_desc = $objp->product_desc;
2192 $line->fk_product_type = $objp->fk_product_type;
2193 $line->qty = $objp->qty;
2194 $line->subprice = $objp->subprice;
2195 $line->ref_ext = $objp->ref_ext;
2197 $line->vat_src_code = $objp->vat_src_code;
2198 $line->tva_tx = $objp->tva_tx;
2199 $line->localtax1_tx = $objp->localtax1_tx;
2200 $line->localtax2_tx = $objp->localtax2_tx;
2201 $line->localtax1_type = $objp->localtax1_type;
2202 $line->localtax2_type = $objp->localtax2_type;
2203 $line->remise_percent = $objp->remise_percent;
2204 $line->fk_remise_except = $objp->fk_remise_except;
2205 $line->fk_product = $objp->fk_product;
2206 $line->date_start = $this->
db->jdate($objp->date_start);
2207 $line->date_end = $this->
db->jdate($objp->date_end);
2208 $line->date_start = $this->
db->jdate($objp->date_start);
2209 $line->date_end = $this->
db->jdate($objp->date_end);
2210 $line->info_bits = $objp->info_bits;
2211 $line->total_ht = $objp->total_ht;
2212 $line->total_tva = $objp->total_tva;
2213 $line->total_localtax1 = $objp->total_localtax1;
2214 $line->total_localtax2 = $objp->total_localtax2;
2215 $line->total_ttc = $objp->total_ttc;
2216 $line->code_ventilation = $objp->fk_code_ventilation;
2217 $line->fk_fournprice = $objp->fk_fournprice;
2218 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2219 $line->pa_ht = $marginInfos[0];
2220 $line->marge_tx = $marginInfos[1];
2221 $line->marque_tx = $marginInfos[2];
2222 $line->rang = $objp->rang;
2223 $line->special_code = $objp->special_code;
2224 $line->fk_parent_line = $objp->fk_parent_line;
2225 $line->situation_percent = $objp->situation_percent;
2226 $line->fk_prev_id = $objp->fk_prev_id;
2227 $line->fk_unit = $objp->fk_unit;
2230 $line->fk_accounting_account = $objp->fk_code_ventilation;
2233 $line->fk_multicurrency = $objp->fk_multicurrency;
2234 $line->multicurrency_code = $objp->multicurrency_code;
2235 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2236 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2237 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2238 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2240 $line->fetch_optionals();
2243 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2245 $tmpproduct->fetch($objp->fk_product);
2246 $tmpproduct->getMultiLangs();
2248 $line->multilangs = $tmpproduct->multilangs;
2251 $this->lines[$i] = $line;
2255 $this->
db->free($result);
2258 $this->error = $this->
db->error();
2273 $this->tab_previous_situation_invoice = array();
2274 $this->tab_next_situation_invoice = array();
2276 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2277 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2278 $sql .=
' AND entity = '.((int) $this->entity);
2279 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2280 $sql .=
' ORDER BY situation_counter ASC';
2282 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2283 $result = $this->
db->query(
$sql);
2284 if ($result && $this->
db->num_rows($result) > 0) {
2285 while ($objp = $this->
db->fetch_object($result)) {
2287 if ($invoice->fetch($objp->rowid) > 0) {
2288 if ($objp->situation_counter < $this->situation_counter
2289 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2291 $this->tab_previous_situation_invoice[] = $invoice;
2293 $this->tab_next_situation_invoice[] = $invoice;
2314 if (empty($this->
type)) {
2317 if (isset($this->
ref)) {
2318 $this->
ref = trim($this->
ref);
2320 if (isset($this->ref_ext)) {
2321 $this->ref_ext = trim($this->ref_ext);
2323 if (isset($this->ref_client)) {
2324 $this->ref_client = trim($this->ref_client);
2326 if (isset($this->increment)) {
2327 $this->increment = trim($this->increment);
2329 if (isset($this->close_code)) {
2330 $this->close_code = trim($this->close_code);
2332 if (isset($this->close_note)) {
2333 $this->close_note = trim($this->close_note);
2335 if (isset($this->note) || isset($this->note_private)) {
2336 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2338 if (isset($this->note) || isset($this->note_private)) {
2339 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2341 if (isset($this->note_public)) {
2342 $this->note_public = trim($this->note_public);
2344 if (isset($this->model_pdf)) {
2345 $this->model_pdf = trim($this->model_pdf);
2347 if (isset($this->import_key)) {
2348 $this->import_key = trim($this->import_key);
2350 if (isset($this->retained_warranty)) {
2351 $this->retained_warranty = floatval($this->retained_warranty);
2359 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2360 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2361 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2362 $sql .=
" type=".(isset($this->
type) ? $this->
db->escape($this->
type) :
"null").
",";
2363 $sql .=
" ref_client=".(isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null").
",";
2364 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2365 $sql .=
" fk_soc=".(isset($this->socid) ? $this->
db->escape($this->socid) :
"null").
",";
2366 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2367 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2368 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2369 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2370 $sql .=
" paye=".(isset($this->paye) ? $this->
db->escape($this->paye) : 0).
",";
2371 $sql .=
" remise_percent=".(isset($this->remise_percent) ? $this->
db->escape($this->remise_percent) :
"null").
",";
2372 $sql .=
" remise_absolue=".(isset($this->remise_absolue) ? $this->
db->escape($this->remise_absolue) :
"null").
",";
2373 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2374 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2375 $sql .=
" total_tva=".(isset($this->total_tva) ? $this->total_tva :
"null").
",";
2376 $sql .=
" localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 :
"null").
",";
2377 $sql .=
" localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 :
"null").
",";
2378 $sql .=
" total_ht=".(isset($this->total_ht) ? $this->total_ht :
"null").
",";
2379 $sql .=
" total_ttc=".(isset($this->total_ttc) ? $this->total_ttc :
"null").
",";
2380 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? $this->
db->escape($this->revenuestamp) :
"null").
",";
2381 $sql .=
" fk_statut=".(isset($this->statut) ? $this->
db->escape($this->statut) :
"null").
",";
2382 $sql .=
" fk_user_author=".(isset($this->user_author) ? $this->
db->escape($this->user_author) :
"null").
",";
2383 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? $this->
db->escape($this->fk_user_valid) :
"null").
",";
2384 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? $this->
db->escape($this->fk_facture_source) :
"null").
",";
2385 $sql .=
" fk_projet=".(isset($this->fk_project) ? $this->
db->escape($this->fk_project) :
"null").
",";
2386 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->
db->escape($this->cond_reglement_id) :
"null").
",";
2387 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->
db->escape($this->mode_reglement_id) :
"null").
",";
2388 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2389 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2390 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2391 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2392 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2393 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : $this->
db->escape($this->situation_cycle_ref)).
",";
2394 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : $this->
db->escape($this->situation_counter)).
",";
2395 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : $this->
db->escape($this->situation_final)).
",";
2396 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty)).
",";
2397 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2398 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) :
"null");
2399 $sql .=
" WHERE rowid=".((int) $this->
id);
2403 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2404 $resql = $this->
db->query(
$sql);
2407 $this->errors[] =
"Error ".$this->db->lasterror();
2417 if (!$error && !$notrigger) {
2428 foreach ($this->errors as $errmsg) {
2429 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2430 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2432 $this->
db->rollback();
2435 $this->
db->commit();
2451 global $conf, $langs;
2453 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2454 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2459 $result = $remise->fetch($idremise);
2462 if ($remise->fk_facture) {
2463 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2464 $this->
db->rollback();
2469 $facligne->fk_facture = $this->id;
2470 $facligne->fk_remise_except = $remise->id;
2471 $facligne->desc = $remise->description;
2472 $facligne->vat_src_code = $remise->vat_src_code;
2473 $facligne->tva_tx = $remise->tva_tx;
2474 $facligne->subprice = -$remise->amount_ht;
2475 $facligne->fk_product = 0;
2477 $facligne->remise_percent = 0;
2478 $facligne->rang = -1;
2479 $facligne->info_bits = 2;
2481 if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
2482 $facligne->rang = 1;
2483 $linecount = count($this->lines);
2484 for ($ii = 1; $ii <= $linecount; $ii++) {
2490 if ($remise->fk_facture_source > 0) {
2492 $srcinvoice->fetch($remise->fk_facture_source);
2493 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2495 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2496 $facligne->pa_ht = $arraytmp[
'pa_total'];
2499 $facligne->total_ht = -$remise->amount_ht;
2500 $facligne->total_tva = -$remise->amount_tva;
2501 $facligne->total_ttc = -$remise->amount_ttc;
2503 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2504 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2505 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2506 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2508 $lineid = $facligne->insert();
2513 $result = $remise->link_to_invoice($lineid, 0);
2515 $this->error = $remise->error;
2516 $this->
db->rollback();
2520 $this->
db->commit();
2523 $this->error = $facligne->error;
2524 $this->
db->rollback();
2528 $this->error = $facligne->error;
2529 $this->
db->rollback();
2533 $this->
db->rollback();
2555 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2556 if (empty($ref_client)) {
2557 $sql .=
' SET ref_client = NULL';
2559 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2561 $sql .=
" WHERE rowid = ".((int) $this->
id);
2563 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2564 $resql = $this->
db->query(
$sql);
2566 $this->errors[] = $this->
db->error();
2571 $this->ref_client = $ref_client;
2574 if (!$notrigger && empty($error)) {
2584 $this->ref_client = $ref_client;
2586 $this->
db->commit();
2589 foreach ($this->errors as $errmsg) {
2590 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2591 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2593 $this->
db->rollback();
2606 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2608 global $langs, $conf;
2609 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2613 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2626 if (!$error && !$notrigger) {
2640 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2654 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2655 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2656 $sql .=
' AND fk_facture_line IS NULL';
2657 $resql = $this->
db->query(
$sql);
2661 $list_rowid_det = array();
2662 foreach ($this->lines as $key => $invoiceline) {
2663 $list_rowid_det[] = $invoiceline->id;
2667 if (count($list_rowid_det)) {
2668 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2669 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2670 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(join(
',', $list_rowid_det)).
')';
2672 if (!$this->
db->query(
$sql)) {
2673 $this->error = $this->
db->error().
" sql=".
$sql;
2674 $this->errors[] = $this->error;
2675 $this->
db->rollback();
2682 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2683 $sql .=
' SET fk_invoice = NULL';
2684 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2686 if (!$this->
db->query(
$sql)) {
2687 $this->error = $this->
db->error().
" sql=".
$sql;
2688 $this->errors[] = $this->error;
2689 $this->
db->rollback();
2693 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'projet_task_time';
2694 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2695 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2697 if (!$this->
db->query(
$sql)) {
2698 $this->error = $this->
db->error().
" sql=".
$sql;
2699 $this->errors[] = $this->error;
2700 $this->
db->rollback();
2705 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
2706 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2707 $langs->load(
"agenda");
2709 $num = count($this->lines);
2710 for ($i = 0; $i < $num; $i++) {
2711 if ($this->lines[$i]->fk_product > 0) {
2713 $mouvP->origin = &$this;
2714 $mouvP->setOrigin($this->element, $this->
id);
2716 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2717 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2719 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2726 $main = MAIN_DB_PREFIX.
'facturedet';
2727 $ef = $main.
"_extrafields";
2728 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2730 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2733 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2735 $resql = $this->
db->query(
$sql);
2742 if ($conf->facture->dir_output && !empty($this->
ref)) {
2743 $dir = $conf->facture->dir_output.
"/".$ref;
2744 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2745 if (file_exists($file)) {
2749 $langs->load(
"errors");
2750 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2751 $this->errors[] = $this->error;
2752 $this->
db->rollback();
2756 if (file_exists($dir)) {
2758 $langs->load(
"errors");
2759 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2760 $this->errors[] = $this->error;
2761 $this->
db->rollback();
2767 $this->
db->commit();
2770 $this->error = $this->
db->lasterror().
" sql=".
$sql;
2771 $this->errors[] = $this->error;
2772 $this->
db->rollback();
2776 $this->error = $this->
db->lasterror().
" sql=".
$sql;
2777 $this->errors[] = $this->error;
2778 $this->
db->rollback();
2782 $this->
db->rollback();
2799 public function set_paid($user, $close_code =
'', $close_note =
'')
2802 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2803 return $this->
setPaid($user, $close_code, $close_note);
2815 public function setPaid($user, $close_code =
'', $close_note =
'')
2819 if ($this->paye != 1) {
2824 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
2826 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2827 $sql .=
' fk_statut='.self::STATUS_CLOSED;
2832 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2835 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2837 $sql .=
', fk_user_closing = '.((int) $user->id);
2838 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
2839 $sql .=
" WHERE rowid = ".((int) $this->
id);
2841 $resql = $this->
db->query(
$sql);
2851 $this->error = $this->
db->lasterror();
2855 $this->
db->commit();
2858 $this->
db->rollback();
2881 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
2899 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2900 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
2901 $sql .=
' date_closing=null,';
2902 $sql .=
' fk_user_closing=null';
2903 $sql .=
" WHERE rowid = ".((int) $this->
id);
2905 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
2906 $resql = $this->
db->query(
$sql);
2916 $this->error = $this->
db->error();
2921 $this->
db->commit();
2924 $this->
db->rollback();
2946 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
2947 return $this->
setCanceled($user, $close_code, $close_note);
2960 public function setCanceled($user, $close_code =
'', $close_note =
'')
2962 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
2966 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2967 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
2969 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2972 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2974 $sql .=
" WHERE rowid = ".((int) $this->
id);
2976 $resql = $this->
db->query(
$sql);
2980 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2981 $sql .=
' SET fk_facture = NULL';
2982 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
2984 $resql = $this->
db->query(
$sql);
2989 $this->
db->rollback();
2994 $this->
db->commit();
2997 $this->error = $this->
db->error().
" sql=".
$sql;
2998 $this->
db->rollback();
3002 $this->error = $this->
db->error().
" sql=".
$sql;
3003 $this->
db->rollback();
3019 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3021 global $conf, $langs, $mysoc;
3022 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3024 $productStatic =
null;
3025 $warehouseStatic =
null;
3026 if ($batch_rule > 0) {
3027 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3028 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3029 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3030 $productStatic =
new Product($this->
db);
3032 $productbatch =
new ProductBatch($this->
db);
3038 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3045 if ($this->statut != self::STATUS_DRAFT) {
3046 dol_syslog(get_class($this).
"::validate status is not draft. operation canceled.", LOG_WARNING);
3049 if (count($this->lines) <= 0) {
3050 $langs->load(
"errors");
3051 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3054 if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
3055 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
3056 $this->error =
'Permission denied';
3057 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
3060 if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
3062 if (!$last_of_type[0]) {
3063 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3069 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3070 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3071 foreach ($array_to_check as $key) {
3072 $keymin = strtolower($key);
3073 if (!property_exists($this->thirdparty, $keymin)) {
3076 $vallabel = $this->thirdparty->$keymin;
3078 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3080 if ($this->thirdparty->isACompany()) {
3082 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3083 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3084 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3085 $langs->load(
"errors");
3086 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3087 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3093 if ($key ==
'EMAIL') {
3095 if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
3096 $langs->load(
"errors");
3097 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3098 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3102 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3104 if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
3105 $langs->load(
"errors");
3106 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3107 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3116 $array_to_check = array(
'REF_CLIENT'=>
'RefCustomer');
3117 foreach ($array_to_check as $key => $val) {
3118 $keymin = strtolower($key);
3119 $vallabel = $this->$keymin;
3122 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3123 if (!$vallabel && !empty($conf->global->$keymandatory)) {
3124 $langs->load(
"errors");
3126 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val)),
null,
'errors');
3133 if ($this->
type == self::TYPE_REPLACEMENT) {
3135 if ($this->fk_facture_source <= 0) {
3136 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3137 $this->
db->rollback();
3143 $result = $facreplaced->fetch($this->fk_facture_source);
3145 $this->error = $langs->trans(
"ErrorBadInvoice");
3146 $this->
db->rollback();
3151 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3152 if ($idreplacement && $idreplacement != $this->
id) {
3153 $facreplacement =
new Facture($this->
db);
3154 $facreplacement->fetch($idreplacement);
3155 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3156 $this->
db->rollback();
3160 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3162 $this->error = $facreplaced->error;
3163 $this->
db->rollback();
3169 if ($force_number) {
3170 $num = $force_number;
3171 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3172 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3187 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3188 $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).
"'";
3189 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3190 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3191 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3193 $sql .=
" WHERE rowid = ".((int) $this->
id);
3195 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3196 $resql = $this->
db->query(
$sql);
3203 if (!$error && (preg_match(
'/^[\(]?PROV/i', $this->
ref))) {
3209 $result = $this->thirdparty->set_as_client();
3212 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
3213 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3214 $langs->load(
"agenda");
3217 $cpt = count($this->lines);
3218 for ($i = 0; $i < $cpt; $i++) {
3219 if ($this->lines[$i]->fk_product > 0) {
3221 $mouvP->origin = &$this;
3222 $mouvP->setOrigin($this->element, $this->
id);
3224 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3225 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3228 $this->error = $mouvP->error;
3231 $is_batch_line =
false;
3232 if ($batch_rule > 0) {
3233 $productStatic->fetch($this->lines[$i]->fk_product);
3234 if ($productStatic->hasbatch()) {
3235 $is_batch_line =
true;
3236 $product_qty_remain = $this->lines[$i]->qty;
3242 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3243 $sortorder =
'ASC,ASC,ASC,ASC';
3246 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_ALLOW_NEGATIVE_TRANSFER') ?
null : 0), $sortfield, $sortorder);
3247 if (!is_array($resBatchList)) {
3249 $this->error = $this->
db->lasterror();
3253 $batchList = $resBatchList;
3254 if (empty($batchList)) {
3256 $langs->load(
'errors');
3257 $warehouseStatic->fetch($idwarehouse);
3258 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3259 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3262 foreach ($batchList as $batch) {
3263 if ($batch->qty <= 0) {
3268 if ($batch->qty >= $product_qty_remain) {
3269 $product_batch_qty = $product_qty_remain;
3272 $product_batch_qty = $batch->qty;
3274 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3277 $this->error = $mouvP->error;
3281 $product_qty_remain -= $product_batch_qty;
3283 if ($product_qty_remain <= 0) {
3288 if (!$error && $product_qty_remain > 0) {
3291 $batch = $batchList[0];
3292 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3295 $this->error = $mouvP->error;
3299 $langs->load(
'errors');
3300 $warehouseStatic->fetch($idwarehouse);
3301 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3302 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3309 if (!$is_batch_line) {
3310 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3313 $this->error = $mouvP->error;
3326 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3327 $invoice_situation =
new Facture($this->
db);
3328 $result = $invoice_situation->fetch($this->fk_facture_source);
3329 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3330 $invoice_situation->situation_final = 0;
3332 $result = $invoice_situation->setFinal($user, 1);
3335 $this->error = $invoice_situation->error;
3336 $this->errors = $invoice_situation->errors;
3342 if (!$error && !$notrigger) {
3352 $this->oldref = $this->ref;
3355 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3357 $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).
"'";
3358 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->
db->escape($this->
ref).
"' and entity = ".$conf->entity;
3359 $resql = $this->
db->query(
$sql);
3362 $this->error = $this->
db->lasterror();
3368 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3369 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3370 if (!$error && file_exists($dirsource)) {
3371 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3373 if (@rename($dirsource, $dirdest)) {
3376 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3377 foreach ($listoffiles as $fileentry) {
3378 $dirsource = $fileentry[
'name'];
3379 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3380 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3381 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3382 @rename($dirsource, $dirdest);
3401 $this->brouillon = 0;
3402 $this->date_validation = $now;
3405 if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3407 $nboflines = count($this->lines);
3408 while (($i < $nboflines) && $final) {
3409 $final = ($this->lines[$i]->situation_percent == 100);
3413 if (empty($final)) {
3414 $this->situation_final = 0;
3416 $this->situation_final = 1;
3427 $this->
db->commit();
3430 $this->
db->rollback();
3443 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3444 $is_last = $next_invoice->is_last_in_cycle();
3446 if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
3447 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3451 $next_invoice->brouillon = 1;
3453 foreach ($next_invoice->lines as $line) {
3454 $result = $next_invoice->updateline(
3459 $line->remise_percent,
3463 $line->localtax1_tx,
3464 $line->localtax2_tx,
3467 $line->product_type,
3468 $line->fk_parent_line,
3470 $line->fk_fournprice,
3473 $line->special_code,
3474 $line->array_options,
3475 $line->situation_percent,
3480 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3501 global $conf, $langs;
3505 if ($this->statut == self::STATUS_DRAFT) {
3506 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3514 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3515 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3516 $sql .=
" WHERE rowid = ".((int) $this->
id);
3518 $result = $this->
db->query(
$sql);
3521 $this->oldcopy = clone $this;
3525 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3526 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3527 $langs->load(
"agenda");
3529 $num = count($this->lines);
3530 for ($i = 0; $i < $num; $i++) {
3531 if ($this->lines[$i]->fk_product > 0) {
3533 $mouvP->origin = &$this;
3534 $mouvP->setOrigin($this->element, $this->
id);
3536 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3537 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3539 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3546 $old_statut = $this->statut;
3547 $this->brouillon = 1;
3552 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3555 $this->statut = $old_statut;
3556 $this->status = $old_statut;
3557 $this->brouillon = 0;
3561 $this->
db->rollback();
3566 $this->
db->commit();
3569 $this->
db->rollback();
3573 $this->error = $this->
db->error();
3574 $this->
db->rollback();
3628 $remise_percent = 0,
3633 $fk_remise_except =
'',
3634 $price_base_type =
'HT',
3641 $fk_parent_line = 0,
3642 $fk_fournprice =
null,
3646 $situation_percent = 100,
3651 $noupdateafterinsertline = 0
3655 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3659 global $mysoc, $conf, $langs;
3661 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);
3663 if ($this->statut == self::STATUS_DRAFT) {
3664 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3667 if (empty($remise_percent)) {
3668 $remise_percent = 0;
3673 if (empty($info_bits)) {
3679 if (empty($ventil)) {
3682 if (empty($txtva)) {
3685 if (empty($txlocaltax1)) {
3688 if (empty($txlocaltax2)) {
3691 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3692 $fk_parent_line = 0;
3694 if (empty($fk_prev_id)) {
3695 $fk_prev_id =
'null';
3697 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3698 $situation_percent = 100;
3700 if (empty($ref_ext)) {
3704 $remise_percent =
price2num($remise_percent);
3707 $pu_ht_devise =
price2num($pu_ht_devise);
3710 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3716 if ($price_base_type ==
'HT') {
3727 if ($date_start && $date_end && $date_start > $date_end) {
3728 $langs->load(
"errors");
3729 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3735 $product_type = $type;
3736 if (!empty($fk_product) && $fk_product > 0) {
3738 $result = $product->fetch($fk_product);
3739 $product_type = $product->type;
3741 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3742 $langs->load(
"errors");
3743 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3744 $this->
db->rollback();
3754 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3755 $vat_src_code = $reg[1];
3756 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3764 $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);
3766 $total_ht = $tabprice[0];
3767 $total_tva = $tabprice[1];
3768 $total_ttc = $tabprice[2];
3769 $total_localtax1 = $tabprice[9];
3770 $total_localtax2 = $tabprice[10];
3771 $pu_ht = $tabprice[3];
3774 $multicurrency_total_ht = $tabprice[16];
3775 $multicurrency_total_tva = $tabprice[17];
3776 $multicurrency_total_ttc = $tabprice[18];
3777 $pu_ht_devise = $tabprice[19];
3781 if ($ranktouse == -1) {
3782 $rangmax = $this->
line_max($fk_parent_line);
3783 $ranktouse = $rangmax + 1;
3789 $this->line->context = $this->context;
3791 $this->line->fk_facture = $this->id;
3792 $this->line->label = $label;
3793 $this->line->desc = $desc;
3794 $this->line->ref_ext = $ref_ext;
3796 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty);
3797 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
3799 $this->line->vat_src_code = $vat_src_code;
3800 $this->line->tva_tx = $txtva;
3801 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3802 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3803 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
3804 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
3806 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
3807 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
3808 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
3809 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
3810 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
3812 $this->line->fk_product = $fk_product;
3813 $this->line->product_type = $product_type;
3814 $this->line->remise_percent = $remise_percent;
3815 $this->line->date_start = $date_start;
3816 $this->line->date_end = $date_end;
3817 $this->line->ventil = $ventil;
3818 $this->line->rang = $ranktouse;
3819 $this->line->info_bits = $info_bits;
3820 $this->line->fk_remise_except = $fk_remise_except;
3822 $this->line->special_code = $special_code;
3823 $this->line->fk_parent_line = $fk_parent_line;
3824 $this->line->origin = $origin;
3825 $this->line->origin_id = $origin_id;
3826 $this->line->situation_percent = $situation_percent;
3827 $this->line->fk_prev_id = $fk_prev_id;
3828 $this->line->fk_unit = $fk_unit;
3831 $this->line->fk_fournprice = $fk_fournprice;
3832 $this->line->pa_ht = $pa_ht;
3835 $this->line->fk_multicurrency = $this->fk_multicurrency;
3836 $this->line->multicurrency_code = $this->multicurrency_code;
3837 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
3839 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
3840 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
3841 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
3843 if (is_array($array_options) && count($array_options) > 0) {
3844 $this->line->array_options = $array_options;
3847 $result = $this->line->insert();
3850 if (!empty($fk_parent_line)) {
3852 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
3853 $linecount = count($this->lines);
3854 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
3860 if (empty($noupdateafterinsertline)) {
3865 $this->
db->commit();
3866 return $this->line->id;
3868 $this->error = $this->
db->lasterror();
3869 $this->
db->rollback();
3873 $this->error = $this->line->error;
3874 $this->errors = $this->line->errors;
3875 $this->
db->rollback();
3879 $this->errors[]=
'status of invoice must be Draft to allow use of ->addline()';
3880 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3916 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)
3918 global $conf, $user;
3921 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3924 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3926 global $mysoc, $langs;
3928 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);
3930 if ($this->statut == self::STATUS_DRAFT) {
3933 if (!$this->error) {
3934 $this->error = $langs->trans(
'invoiceLineProgressError');
3940 if ($date_start && $date_end && $date_start > $date_end) {
3941 $langs->load(
"errors");
3942 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3952 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3953 $fk_parent_line = 0;
3955 if (empty($special_code) || $special_code == 3) {
3958 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3959 $situation_percent = 100;
3961 if (empty($ref_ext)) {
3965 $remise_percent =
price2num($remise_percent);
3968 $pu_ht_devise =
price2num($pu_ht_devise);
3970 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3990 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3991 $vat_src_code = $reg[1];
3992 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3995 $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);
3997 $total_ht = $tabprice[0];
3998 $total_tva = $tabprice[1];
3999 $total_ttc = $tabprice[2];
4000 $total_localtax1 = $tabprice[9];
4001 $total_localtax2 = $tabprice[10];
4002 $pu_ht = $tabprice[3];
4003 $pu_tva = $tabprice[4];
4004 $pu_ttc = $tabprice[5];
4007 $multicurrency_total_ht = $tabprice[16];
4008 $multicurrency_total_tva = $tabprice[17];
4009 $multicurrency_total_ttc = $tabprice[18];
4010 $pu_ht_devise = $tabprice[19];
4015 if ($remise_percent > 0) {
4016 $remise = round(($pu * $remise_percent / 100), 2);
4017 $price = ($pu - $remise);
4023 $line->fetch($rowid);
4024 $line->fetch_optionals();
4026 if (!empty($line->fk_product)) {
4028 $result = $product->fetch($line->fk_product);
4029 $product_type = $product->type;
4031 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
4032 $langs->load(
"errors");
4033 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4034 $this->
db->rollback();
4039 $staticline = clone $line;
4041 $line->oldline = $staticline;
4042 $this->line = $line;
4043 $this->line->context = $this->context;
4044 $this->line->rang = $rang;
4047 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4048 $rangmax = $this->
line_max($fk_parent_line);
4049 $this->line->rang = $rangmax + 1;
4052 $this->line->id = $rowid;
4053 $this->line->rowid = $rowid;
4054 $this->line->label = $label;
4055 $this->line->desc = $desc;
4056 $this->line->ref_ext = $ref_ext;
4057 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty);
4059 $this->line->vat_src_code = $vat_src_code;
4060 $this->line->tva_tx = $txtva;
4061 $this->line->localtax1_tx = $txlocaltax1;
4062 $this->line->localtax2_tx = $txlocaltax2;
4063 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
4064 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
4066 $this->line->remise_percent = $remise_percent;
4067 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht);
4068 $this->line->date_start = $date_start;
4069 $this->line->date_end = $date_end;
4070 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht);
4071 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
4072 $this->line->total_localtax1 = $total_localtax1;
4073 $this->line->total_localtax2 = $total_localtax2;
4074 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
4075 $this->line->info_bits = $info_bits;
4076 $this->line->special_code = $special_code;
4077 $this->line->product_type = $type;
4078 $this->line->fk_parent_line = $fk_parent_line;
4079 $this->line->skip_update_total = $skip_update_total;
4080 $this->line->situation_percent = $situation_percent;
4081 $this->line->fk_unit = $fk_unit;
4083 $this->line->fk_fournprice = $fk_fournprice;
4084 $this->line->pa_ht = $pa_ht;
4087 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise);
4088 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht);
4089 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
4090 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4092 if (is_array($array_options) && count($array_options) > 0) {
4094 foreach ($array_options as $key => $value) {
4095 $this->line->array_options[$key] = $array_options[$key];
4099 $result = $this->line->update($user, $notrigger);
4102 if (!empty($fk_parent_line)) {
4108 $this->
db->commit();
4111 $this->error = $this->line->error;
4112 $this->
db->rollback();
4116 $this->error =
"Invoice statut makes operation forbidden";
4130 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4131 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4132 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4134 $result = $this->
db->query(
$sql);
4136 $this->error = $this->
db->error();
4140 $obj = $this->
db->fetch_object($result);
4142 if ($obj ===
null) {
4145 return ($situation_percent < $obj->situation_percent);
4161 global $mysoc, $user;
4164 if (($line->info_bits & 2) == 2) {
4168 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4171 if ($percent > 100) {
4174 $line->situation_percent = $percent;
4175 $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);
4176 $line->total_ht = $tabprice[0];
4177 $line->total_tva = $tabprice[1];
4178 $line->total_ttc = $tabprice[2];
4179 $line->total_localtax1 = $tabprice[9];
4180 $line->total_localtax2 = $tabprice[10];
4181 $line->multicurrency_total_ht = $tabprice[16];
4182 $line->multicurrency_total_tva = $tabprice[17];
4183 $line->multicurrency_total_ttc = $tabprice[18];
4184 $line->update($user);
4187 if ($update_price) {
4203 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4205 if ($this->statut != self::STATUS_DRAFT) {
4206 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4212 $line->context = $this->context;
4215 $result = $line->fetch($rowid);
4216 if (!($result > 0)) {
4221 if ($id > 0 && $line->fk_facture != $id) {
4222 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4229 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
4230 $sql .=
' SET fk_facture_line = NULL';
4231 $sql .=
' WHERE fk_facture_line = '.((int) $rowid);
4233 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
4234 $result = $this->
db->query(
$sql);
4236 $this->error = $this->
db->error();
4237 $this->
db->rollback();
4242 $staticline = clone $line;
4243 $line->oldline = $staticline;
4245 if ($line->delete($user) > 0) {
4249 $this->
db->commit();
4252 $this->
db->rollback();
4253 $this->error = $this->
db->lasterror();
4257 $this->
db->rollback();
4258 $this->error = $line->error;
4277 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4278 return $this->
setDiscount($user, $remise, $notrigger);
4292 if (empty($remise)) {
4296 if ($user->rights->facture->creer) {
4303 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4304 $sql .=
' SET remise_percent = '.((float) $remise);
4305 $sql .=
" WHERE rowid = ".((int) $this->
id);
4306 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4309 $resql = $this->
db->query(
$sql);
4311 $this->errors[] = $this->
db->error();
4315 if (!$notrigger && empty($error)) {
4325 $this->remise_percent = $remise;
4328 $this->
db->commit();
4331 foreach ($this->errors as $errmsg) {
4332 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4333 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4335 $this->
db->rollback();
4356 if (empty($remise)) {
4360 if ($user->rights->facture->creer) {
4367 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4368 $sql .=
' SET remise_absolue = '.((float) $remise);
4369 $sql .=
" WHERE rowid = ".((int) $this->
id);
4370 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4373 $resql = $this->
db->query(
$sql);
4375 $this->errors[] = $this->
db->error();
4380 $this->oldcopy = clone $this;
4381 $this->remise_absolue = $remise;
4385 if (!$notrigger && empty($error)) {
4395 $this->
db->commit();
4398 foreach ($this->errors as $errmsg) {
4399 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4400 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4402 $this->
db->rollback();
4420 global $conf, $langs;
4422 if ($this->module_source ==
'takepos') {
4423 $langs->load(
'cashdesk');
4425 $moduleName =
'takepos';
4426 $moduleSourceName =
'Takepos';
4427 $addonConstName =
'TAKEPOS_REF_ADDON';
4430 if (empty($conf->global->TAKEPOS_REF_ADDON)) {
4431 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4434 $addon = $conf->global->TAKEPOS_REF_ADDON;
4436 $langs->load(
'bills');
4438 $moduleName =
'facture';
4439 $moduleSourceName =
'Invoice';
4440 $addonConstName =
'FACTURE_ADDON';
4443 if (empty($conf->global->FACTURE_ADDON)) {
4444 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4445 } elseif ($conf->global->FACTURE_ADDON ==
'terre') {
4446 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4447 } elseif ($conf->global->FACTURE_ADDON ==
'mercure') {
4448 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4451 $addon = $conf->global->FACTURE_ADDON;
4454 if (!empty($addon)) {
4455 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = ".$conf->global->FACTURE_ADDON.
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4459 $file = $addon.
'.php';
4460 $classname = $addon;
4464 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4465 foreach ($dirmodels as $reldir) {
4466 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4469 if (is_file($dir.$file) && is_readable($dir.$file)) {
4470 $mybool |= include_once $dir.$file;
4476 $file = $addon.
'/'.$addon.
'.modules.php';
4477 $classname =
'mod_'.$moduleName.
'_'.$addon;
4478 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4480 foreach ($conf->file->dol_document_root as $dirroot) {
4481 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4484 if (is_file($dir.$file) && is_readable($dir.$file)) {
4485 $mybool |= include_once $dir.$file;
4495 $obj =
new $classname();
4497 $numref = $obj->getNextValue($soc, $this, $mode);
4504 if ($mode !=
'last' && !$numref) {
4505 $this->error = $obj->error;
4511 $langs->load(
'errors');
4512 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4525 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4526 $sql .=
' date_closing as dateclosing,';
4527 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4528 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4529 $sql .=
' WHERE c.rowid = '.((int) $id);
4531 $result = $this->
db->query(
$sql);
4533 if ($this->
db->num_rows($result)) {
4534 $obj = $this->
db->fetch_object($result);
4535 $this->
id = $obj->rowid;
4536 if ($obj->fk_user_author) {
4537 $cuser =
new User($this->
db);
4538 $cuser->fetch($obj->fk_user_author);
4539 $this->user_creation = $cuser;
4541 if ($obj->fk_user_valid) {
4542 $vuser =
new User($this->
db);
4543 $vuser->fetch($obj->fk_user_valid);
4544 $this->user_validation = $vuser;
4546 if ($obj->fk_user_closing) {
4547 $cluser =
new User($this->
db);
4548 $cluser->fetch($obj->fk_user_closing);
4549 $this->user_closing = $cluser;
4552 $this->date_creation = $this->
db->jdate($obj->datec);
4553 $this->date_modification = $this->
db->jdate($obj->datem);
4554 $this->date_validation = $this->
db->jdate($obj->datev);
4555 $this->date_closing = $this->
db->jdate($obj->dateclosing);
4557 $this->
db->free($result);
4578 public function liste_array($shortlist = 0, $draft = 0, $excluser =
'', $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4581 global $conf, $user;
4585 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4586 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4587 if (empty($user->rights->societe->client->voir) && !$socid) {
4588 $sql .=
", sc.fk_soc, sc.fk_user";
4590 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4591 if (empty($user->rights->societe->client->voir) && !$socid) {
4592 $sql .=
", ".MAIN_DB_PREFIX.
"societe_commerciaux as sc";
4594 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4595 $sql .=
" AND f.fk_soc = s.rowid";
4596 if (empty($user->rights->societe->client->voir) && !$socid) {
4597 $sql .=
" AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4600 $sql .=
" AND s.rowid = ".((int) $socid);
4603 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4605 if (is_object($excluser)) {
4606 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4608 $sql .= $this->
db->order($sortfield, $sortorder);
4609 $sql .= $this->
db->plimit($limit, $offset);
4611 $result = $this->
db->query(
$sql);
4613 $numc = $this->
db->num_rows($result);
4616 while ($i < $numc) {
4617 $obj = $this->
db->fetch_object($result);
4619 if ($shortlist == 1) {
4620 $ga[$obj->fid] = $obj->ref;
4621 } elseif ($shortlist == 2) {
4622 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4624 $ga[$i][
'id'] = $obj->fid;
4625 $ga[$i][
'ref'] = $obj->ref;
4626 $ga[$i][
'name'] = $obj->name;
4655 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4656 $sql .=
" ff.rowid as rowidnext";
4658 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4659 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4660 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4661 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4662 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4663 $sql .=
" AND f.paye = 0";
4664 $sql .=
" AND pf.fk_paiement IS NULL";
4665 $sql .=
" AND ff.fk_statut IS NULL";
4667 $sql .=
" AND f.fk_soc = ".((int) $socid);
4670 $sql .=
" ORDER BY f.ref";
4672 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4673 $resql = $this->
db->query(
$sql);
4675 while ($obj = $this->
db->fetch_object($resql)) {
4676 $return[$obj->rowid] = array(
4677 'id' => $obj->rowid,
4679 'status' => $obj->status,
4680 'paid' => $obj->paid,
4687 $this->error = $this->
db->error();
4710 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
4711 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4712 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4713 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4714 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4715 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4719 $sql .=
" AND ff.type IS NULL";
4720 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4722 if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4724 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4725 $sql .=
'(SELECT MAX(fs.rowid)';
4726 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4727 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4728 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4729 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4731 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4733 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4736 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4740 $sql .=
" AND f.fk_soc = ".((int) $socid);
4742 $sql .=
" ORDER BY f.ref";
4744 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4745 $resql = $this->
db->query(
$sql);
4747 while ($obj = $this->
db->fetch_object($resql)) {
4749 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4752 if ($obj->fk_statut == self::STATUS_CLOSED) {
4757 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4758 $return[$obj->rowid] = array(
'ref'=>$obj->ref,
'status'=>$obj->fk_statut,
'type'=>$obj->type,
'paye'=>$obj->paye,
'paymentornot'=>$paymentornot);
4764 $this->error = $this->
db->error();
4780 global $conf, $langs;
4784 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
4785 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4786 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4787 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4788 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4791 $sql .= $clause.
" f.paye=0";
4792 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4793 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
4795 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
4798 $resql = $this->
db->query(
$sql);
4800 $langs->load(
"bills");
4804 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4805 $response->label = $langs->trans(
"CustomerBillsUnpaid");
4806 $response->labelShort = $langs->trans(
"Unpaid");
4807 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4810 $generic_facture =
new Facture($this->
db);
4812 while ($obj = $this->
db->fetch_object($resql)) {
4813 $generic_facture->date_lim_reglement = $this->
db->jdate($obj->datefin);
4814 $generic_facture->statut = $obj->fk_statut;
4816 $response->nbtodo++;
4817 $response->total += $obj->total_ht;
4819 if ($generic_facture->hasDelay()) {
4820 $response->nbtodolate++;
4821 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4825 $this->
db->free($resql);
4829 $this->error = $this->
db->error();
4868 global $conf, $langs, $user;
4872 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
4877 $sql =
"SELECT rowid";
4878 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
4879 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
4880 $sql .= $this->
db->plimit(100);
4882 $resql = $this->
db->query(
$sql);
4884 $num_prods = $this->
db->num_rows($resql);
4886 while ($i < $num_prods) {
4888 $row = $this->
db->fetch_row($resql);
4889 $prodids[$i] = $row[0];
4893 if (empty($num_prods)) {
4900 $this->
ref =
'SPECIMEN';
4901 $this->specimen = 1;
4903 $this->date = $nownotime;
4904 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4905 $this->cond_reglement_id = 1;
4906 $this->cond_reglement_code =
'RECEP';
4908 $this->mode_reglement_id = 0;
4909 $this->mode_reglement_code =
'';
4911 $this->note_public =
'This is a comment (public)';
4912 $this->note_private =
'This is a comment (private)';
4913 $this->note =
'This is a comment (private)';
4915 $this->fk_user_author = $user->id;
4917 $this->multicurrency_tx = 1;
4918 $this->multicurrency_code = $conf->currency;
4920 $this->fk_incoterms = 0;
4921 $this->location_incoterms =
'';
4923 if (empty($option) || $option !=
'nolines') {
4927 while ($xnbp < $nbp) {
4929 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
4931 $line->subprice = 100;
4932 $line->tva_tx = 19.6;
4933 $line->localtax1_tx = 0;
4934 $line->localtax2_tx = 0;
4935 $line->remise_percent = 0;
4937 $prodid = mt_rand(1, $num_prods);
4938 $line->fk_product = $prodids[$prodid];
4940 $line->total_ht = -100;
4941 $line->total_ttc = -119.6;
4942 $line->total_tva = -19.6;
4943 $line->multicurrency_total_ht = -200;
4944 $line->multicurrency_total_ttc = -239.2;
4945 $line->multicurrency_total_tva = -39.2;
4946 } elseif ($xnbp == 2) {
4947 $line->subprice = -100;
4948 $line->total_ht = -100;
4949 $line->total_ttc = -119.6;
4950 $line->total_tva = -19.6;
4951 $line->remise_percent = 0;
4952 $line->multicurrency_total_ht = -200;
4953 $line->multicurrency_total_ttc = -239.2;
4954 $line->multicurrency_total_tva = -39.2;
4955 } elseif ($xnbp == 3) {
4956 $prodid = mt_rand(1, $num_prods);
4957 $line->fk_product = $prodids[$prodid];
4958 $line->total_ht = 50;
4959 $line->total_ttc = 59.8;
4960 $line->total_tva = 9.8;
4961 $line->multicurrency_total_ht = 100;
4962 $line->multicurrency_total_ttc = 119.6;
4963 $line->multicurrency_total_tva = 19.6;
4964 $line->remise_percent = 50;
4967 $prodid = mt_rand(1, $num_prods);
4968 $line->fk_product = $prodids[$prodid];
4969 $line->total_ht = 100;
4970 $line->total_ttc = 119.6;
4971 $line->total_tva = 19.6;
4972 $line->multicurrency_total_ht = 200;
4973 $line->multicurrency_total_ttc = 239.2;
4974 $line->multicurrency_total_tva = 39.2;
4975 $line->remise_percent = 0;
4978 $this->lines[$xnbp] = $line;
4981 $this->total_ht += $line->total_ht;
4982 $this->total_tva += $line->total_tva;
4983 $this->total_ttc += $line->total_ttc;
4985 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4986 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4987 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4991 $this->revenuestamp = 0;
4995 $line->desc = $langs->trans(
"Description").
" (offered line)";
4997 $line->subprice = 100;
4998 $line->tva_tx = 19.6;
4999 $line->localtax1_tx = 0;
5000 $line->localtax2_tx = 0;
5001 $line->remise_percent = 100;
5002 $line->total_ht = 0;
5003 $line->total_ttc = 0;
5004 $line->total_tva = 0;
5005 $line->multicurrency_total_ht = 0;
5006 $line->multicurrency_total_ttc = 0;
5007 $line->multicurrency_total_tva = 0;
5008 $prodid = mt_rand(1, $num_prods);
5009 $line->fk_product = $prodids[$prodid];
5011 $this->lines[$xnbp] = $line;
5025 global $conf, $user;
5027 $this->nb = array();
5031 $sql =
"SELECT count(f.rowid) as nb";
5032 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5033 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5034 if (empty($user->rights->societe->client->voir) && !$user->socid) {
5035 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5036 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5039 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
5041 $resql = $this->
db->query(
$sql);
5043 while ($obj = $this->
db->fetch_object($resql)) {
5044 $this->nb[
"invoices"] = $obj->nb;
5046 $this->
db->free($resql);
5050 $this->error = $this->
db->error();
5076 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5078 global $conf, $langs;
5080 $outputlangs->loadLangs(array(
"bills",
"products"));
5084 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5086 if (!empty($this->model_pdf)) {
5087 $modele = $this->model_pdf;
5088 } elseif (!empty($this->modelpdf)) {
5089 $modele = $this->modelpdf;
5090 } elseif (!empty($conf->global->$thisTypeConfName)) {
5091 $modele = $conf->global->$thisTypeConfName;
5092 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
5093 $modele = $conf->global->FACTURE_ADDON_PDF;
5097 $modelpath =
"core/modules/facture/doc/";
5099 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5109 $sql =
'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.
'facture as f';
5110 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5111 $resql = $this->
db->query(
$sql);
5113 if ($this->
db->num_rows($resql) > 0) {
5114 $res = $this->
db->fetch_array($resql);
5115 $ref = $res[
'max(situation_cycle_ref)'];
5120 $this->
db->free($resql);
5123 $this->error = $this->
db->lasterror();
5138 return ($this->situation_counter == 1);
5152 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5153 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5154 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5155 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5156 $resql = $this->
db->query(
$sql);
5158 if ($resql && $this->
db->num_rows($resql) > 0) {
5159 while ($row = $this->
db->fetch_object($resql)) {
5162 $situation->fetch($id);
5163 $res[] = $situation;
5166 $this->error = $this->
db->error();
5187 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5190 $resql = $this->
db->query(
$sql);
5192 $this->errors[] = $this->
db->error();
5196 if (!$notrigger && empty($error)) {
5206 $this->
db->commit();
5209 foreach ($this->errors as $errmsg) {
5210 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5211 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5213 $this->
db->rollback();
5229 if (!empty($this->situation_cycle_ref)) {
5231 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5232 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5233 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5234 $resql = $this->
db->query(
$sql);
5236 if ($resql && $this->
db->num_rows($resql) > 0) {
5237 $res = $this->
db->fetch_array($resql);
5238 $last = $res[
'max(situation_counter)'];
5239 return ($last == $this->situation_counter);
5241 $this->error = $this->
db->lasterror();
5242 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5300 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5301 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5303 $totalpaid = floatval($totalpaid);
5305 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5306 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5308 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5331 $displayWarranty =
false;
5332 if (!empty($this->retained_warranty)) {
5333 $displayWarranty =
true;
5337 $displayWarranty =
false;
5338 if (!empty($this->situation_final)) {
5339 $displayWarranty =
true;
5342 $displayWarranty =
true;
5344 foreach ($this->lines as $i => $line) {
5345 if ($line->product_type < 2 && $line->situation_percent < 100) {
5346 $displayWarranty =
false;
5354 return $displayWarranty;
5364 if (empty($this->retained_warranty)) {
5368 $retainedWarrantyAmount = 0;
5372 $displayWarranty =
true;
5374 if (!empty($this->lines)) {
5375 foreach ($this->lines as $i => $line) {
5376 if ($line->product_type < 2 && $line->situation_percent < 100) {
5377 $displayWarranty =
false;
5383 if ($displayWarranty && !empty($this->situation_final)) {
5385 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5388 foreach ($TPreviousIncoice as &$fac) {
5389 $total2BillWT += $fac->total_ttc;
5391 $total2BillWT += $this->total_ttc;
5393 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5399 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5402 if ($rounding < 0) {
5403 $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5406 if ($rounding > 0) {
5407 return round($retainedWarrantyAmount, $rounding);
5410 return $retainedWarrantyAmount;
5421 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5423 if ($this->statut >= 0) {
5424 $fieldname =
'retained_warranty';
5425 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5426 $sql .=
" SET ".$fieldname.
" = ".((
float) $value);
5427 $sql .=
' WHERE rowid='.((int) $this->
id);
5429 if ($this->
db->query(
$sql)) {
5430 $this->retained_warranty = floatval($value);
5433 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.
$sql.
' - '.$this->db->error());
5434 $this->error = $this->
db->error();
5438 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5439 $this->error =
'Status of the object is incompatible '.$this->statut;
5454 if (!$timestamp && $dateYmd) {
5455 $timestamp = $this->
db->jdate($dateYmd);
5459 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5460 if ($this->statut >= 0) {
5461 $fieldname =
'retained_warranty_date_limit';
5462 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5463 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5464 $sql .=
' WHERE rowid = '.((int) $this->
id);
5466 if ($this->
db->query(
$sql)) {
5467 $this->retained_warranty_date_limit = $timestamp;
5470 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.
$sql.
' - '.$this->db->error());
5471 $this->error = $this->
db->error();
5475 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5476 $this->error =
'Status of the object is incompatible '.$this->statut;
5494 global $conf, $langs, $user;
5500 $errorsMsg = array();
5502 $langs->load(
"bills");
5505 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5515 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5516 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5517 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5528 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5529 if (!empty($paymentmode) && $paymentmode !=
'all') {
5530 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5532 $sql .=
" WHERE f.paye = 0";
5533 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5534 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5535 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
5536 if (!empty($paymentmode) && $paymentmode !=
'all') {
5537 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5540 $sql .= $this->
db->order(
"date_lim_reglement",
"ASC");
5542 $resql = $this->
db->query(
$sql);
5545 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5546 if (!empty($paymentmode) && $paymentmode !=
'all') {
5547 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5549 $this->output .=
'<br>';
5552 while ($obj = $this->
db->fetch_object($resql)) {
5555 $res = $tmpinvoice->fetch($obj->id);
5557 $tmpinvoice->fetch_thirdparty();
5559 $outputlangs =
new Translate(
'', $conf);
5560 if ($tmpinvoice->thirdparty->default_lang) {
5561 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5562 $outputlangs->loadLangs(array(
"main",
"bills"));
5564 $outputlangs = $langs;
5568 $arraymessage = $formmail->getEMailTemplate($this->
db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5569 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5570 $langs->load(
"errors");
5571 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5584 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5587 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5593 if ($forcerecipient) {
5594 $to = array($forcerecipient);
5596 $res = $tmpinvoice->fetch_thirdparty();
5597 $recipient = $tmpinvoice->thirdparty;
5599 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
5600 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5601 foreach ($tmparraycontact as $data_email) {
5602 if (!empty($data_email[
'email'])) {
5603 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
5607 if (empty($to) && !empty($recipient->email)) {
5608 $to[] = $recipient->email;
5610 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for user.";
5614 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5621 if (!empty($arraymessage->email_from)) {
5622 $from = $arraymessage->email_from;
5625 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5629 if (!$error && !empty($to)) {
5632 $to = implode(
',', $to);
5633 if (!empty($arraymessage->email_to)) {
5634 $to = $to.
','.$arraymessage->email_to;
5638 $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
5640 $trackid =
'inv'.$tmpinvoice->id;
5641 $sendcontext =
'standard';
5644 if (!empty($arraymessage->email_tocc)) {
5645 $email_tocc = $arraymessage->email_tocc;
5649 if (!empty($arraymessage->email_tobcc)) {
5650 $email_tobcc = $arraymessage->email_tobcc;
5654 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5657 if ($cMailFile->sendfile()) {
5661 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5666 $actioncomm->type_code =
'AC_OTH_AUTO';
5667 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5668 $actioncomm->contact_id = 0;
5670 $actioncomm->code =
'AC_EMAIL';
5671 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK';
5672 $actioncomm->note_private = $sendContent;
5673 $actioncomm->fk_project = $tmpinvoice->fk_project;
5674 $actioncomm->datep =
dol_now();
5675 $actioncomm->datef = $actioncomm->datep;
5676 $actioncomm->percentage = -1;
5677 $actioncomm->authorid = $user->id;
5678 $actioncomm->userownerid = $user->id;
5680 $actioncomm->email_msgid = $cMailFile->msgid;
5681 $actioncomm->email_from = $from;
5682 $actioncomm->email_sender =
'';
5683 $actioncomm->email_to = $to;
5687 $actioncomm->errors_to = $errors_to;
5689 $actioncomm->elementtype =
'invoice';
5690 $actioncomm->fk_element = $tmpinvoice->id;
5694 $actioncomm->create($user);
5696 $errormesg = $cMailFile->error.
' : '.$to;
5700 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5705 $actioncomm->type_code =
'AC_OTH_AUTO';
5706 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5707 $actioncomm->contact_id = 0;
5709 $actioncomm->code =
'AC_EMAIL';
5710 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5711 $actioncomm->note_private = $errormesg;
5712 $actioncomm->fk_project = $tmpinvoice->fk_project;
5713 $actioncomm->datep =
dol_now();
5714 $actioncomm->datef = $actioncomm->datep;
5715 $actioncomm->percentage = -1;
5716 $actioncomm->authorid = $user->id;
5717 $actioncomm->userownerid = $user->id;
5719 $actioncomm->email_msgid = $cMailFile->msgid;
5720 $actioncomm->email_from = $from;
5721 $actioncomm->email_sender =
'';
5722 $actioncomm->email_to = $to;
5726 $actioncomm->errors_to = $errors_to;
5730 $actioncomm->create($user);
5733 $this->
db->commit();
5737 $errorsMsg[] = $errormesg;
5740 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
5750 $this->output .=
'Nb of emails sent : '.$nbMailSend;
5753 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg)) ? join(
', ', $errorsMsg) : $error;
5767 $sql =
"SELECT datef";
5768 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
5769 $sql .=
" WHERE type = " . (int) $this->
type ;
5770 $sql .=
" AND date_valid IS NOT NULL";
5771 $sql .=
" ORDER BY datef DESC LIMIT 1";
5773 $result = $this->
db->query(
$sql);
5776 if ($this->
db->num_rows($result)) {
5777 $obj = $this->
db->fetch_object($result);
5778 $last_date = $this->
db->jdate($obj->datef);
5779 $invoice_date = $this->date;
5781 $is_last_of_same_type = $invoice_date >= $last_date;
5782 if ($allow_validated_drafts) {
5783 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->
ref,
'PROV') && $this->status ==
self::STATUS_DRAFT);
5786 return array($is_last_of_same_type, $last_date);
5807 $return =
'<div class="box-flex-item box-flex-grow-zero">';
5808 $return .=
'<div class="info-box info-box-sm">';
5809 $return .=
'<span class="info-box-icon bg-infobox-action">';
5812 $return .=
'</span>';
5813 $return .=
'<div class="info-box-content">';
5814 $return .=
'<span class="info-box-ref">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
5815 if (property_exists($this,
'socid')) {
5816 $return .=
'<br><span class="info-box-label">'.$this->socid.
'</span>';
5818 if (property_exists($this,
'fk_user_author')) {
5819 $return .=
'<br><span class="info-box-label">'.$this->fk_user_author.
'</span>';
5821 if (method_exists($this,
'getLibStatut')) {
5822 $return .=
'<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).
'</div>';
5824 $return .=
'</div>';
5825 $return .=
'</div>';
5826 $return .=
'</div>';
5840 public $element =
'facturedet';
5845 public $table_element =
'facturedet';
5859 public $localtax1_type;
5860 public $localtax2_type;
5861 public $fk_remise_except;
5864 public $fk_fournprice;
5869 public $remise_percent;
5871 public $special_code;
5879 public $fk_code_ventilation = 0;
5884 public $skip_update_total;
5889 public $situation_percent;
5897 public $fk_multicurrency;
5898 public $multicurrency_code;
5899 public $multicurrency_subprice;
5900 public $multicurrency_total_ht;
5901 public $multicurrency_total_tva;
5902 public $multicurrency_total_ttc;
5912 $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,';
5913 $sql .=
' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
5914 $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,';
5915 $sql .=
' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
5916 $sql .=
' fd.fk_code_ventilation,';
5917 $sql .=
' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
5918 $sql .=
' fd.situation_percent, fd.fk_prev_id,';
5919 $sql .=
' fd.multicurrency_subprice,';
5920 $sql .=
' fd.multicurrency_total_ht,';
5921 $sql .=
' fd.multicurrency_total_tva,';
5922 $sql .=
' fd.multicurrency_total_ttc,';
5923 $sql .=
' p.ref as product_ref, p.label as product_label, p.description as product_desc';
5924 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as fd';
5925 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON fd.fk_product = p.rowid';
5926 $sql .=
' WHERE fd.rowid = '.((int) $rowid);
5928 $result = $this->
db->query(
$sql);
5930 $objp = $this->
db->fetch_object($result);
5933 $this->error =
'InvoiceLine with id '. $rowid .
' not found sql='.
$sql;
5937 $this->
rowid = $objp->rowid;
5938 $this->
id = $objp->rowid;
5939 $this->fk_facture = $objp->fk_facture;
5940 $this->fk_parent_line = $objp->fk_parent_line;
5941 $this->label = $objp->custom_label;
5942 $this->desc = $objp->description;
5943 $this->qty = $objp->qty;
5944 $this->subprice = $objp->subprice;
5945 $this->ref_ext = $objp->ref_ext;
5946 $this->vat_src_code = $objp->vat_src_code;
5947 $this->tva_tx = $objp->tva_tx;
5948 $this->localtax1_tx = $objp->localtax1_tx;
5949 $this->localtax2_tx = $objp->localtax2_tx;
5950 $this->remise_percent = $objp->remise_percent;
5951 $this->fk_remise_except = $objp->fk_remise_except;
5952 $this->fk_product = $objp->fk_product;
5953 $this->product_type = $objp->product_type;
5954 $this->date_start = $this->
db->jdate($objp->date_start);
5955 $this->date_end = $this->
db->jdate($objp->date_end);
5956 $this->info_bits = $objp->info_bits;
5957 $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
5958 $this->special_code = $objp->special_code;
5959 $this->total_ht = $objp->total_ht;
5960 $this->total_tva = $objp->total_tva;
5961 $this->total_localtax1 = $objp->total_localtax1;
5962 $this->total_localtax2 = $objp->total_localtax2;
5963 $this->total_ttc = $objp->total_ttc;
5964 $this->fk_code_ventilation = $objp->fk_code_ventilation;
5965 $this->rang = $objp->rang;
5966 $this->fk_fournprice = $objp->fk_fournprice;
5967 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
5968 $this->pa_ht = $marginInfos[0];
5969 $this->marge_tx = $marginInfos[1];
5970 $this->marque_tx = $marginInfos[2];
5972 $this->
ref = $objp->product_ref;
5974 $this->product_ref = $objp->product_ref;
5975 $this->product_label = $objp->product_label;
5976 $this->product_desc = $objp->product_desc;
5978 $this->fk_unit = $objp->fk_unit;
5979 $this->fk_user_modif = $objp->fk_user_modif;
5980 $this->fk_user_author = $objp->fk_user_author;
5982 $this->situation_percent = $objp->situation_percent;
5983 $this->fk_prev_id = $objp->fk_prev_id;
5985 $this->multicurrency_subprice = $objp->multicurrency_subprice;
5986 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
5987 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
5988 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
5990 $this->
db->free($result);
5994 $this->error = $this->
db->lasterror();
6006 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
6008 global $langs, $user, $conf;
6012 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6014 dol_syslog(get_class($this).
"::insert rang=".$this->rang, LOG_DEBUG);
6017 $this->desc = trim($this->desc);
6018 if (empty($this->tva_tx)) {
6021 if (empty($this->localtax1_tx)) {
6022 $this->localtax1_tx = 0;
6024 if (empty($this->localtax2_tx)) {
6025 $this->localtax2_tx = 0;
6027 if (empty($this->localtax1_type)) {
6028 $this->localtax1_type = 0;
6030 if (empty($this->localtax2_type)) {
6031 $this->localtax2_type = 0;
6033 if (empty($this->total_localtax1)) {
6034 $this->total_localtax1 = 0;
6036 if (empty($this->total_localtax2)) {
6037 $this->total_localtax2 = 0;
6039 if (empty($this->rang)) {
6042 if (empty($this->remise_percent)) {
6043 $this->remise_percent = 0;
6045 if (empty($this->info_bits)) {
6046 $this->info_bits = 0;
6048 if (empty($this->subprice)) {
6049 $this->subprice = 0;
6051 if (empty($this->ref_ext)) {
6052 $this->ref_ext =
'';
6054 if (empty($this->special_code)) {
6055 $this->special_code = 0;
6057 if (empty($this->fk_parent_line)) {
6058 $this->fk_parent_line = 0;
6060 if (empty($this->fk_prev_id)) {
6061 $this->fk_prev_id = 0;
6063 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6064 $this->situation_percent = 100;
6067 if (empty($this->pa_ht)) {
6070 if (empty($this->multicurrency_subprice)) {
6071 $this->multicurrency_subprice = 0;
6073 if (empty($this->multicurrency_total_ht)) {
6074 $this->multicurrency_total_ht = 0;
6076 if (empty($this->multicurrency_total_tva)) {
6077 $this->multicurrency_total_tva = 0;
6079 if (empty($this->multicurrency_total_ttc)) {
6080 $this->multicurrency_total_ttc = 0;
6084 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6085 if (($result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
6088 $this->pa_ht = $result;
6093 if ($this->product_type < 0) {
6094 $this->error =
'ErrorProductTypeMustBe0orMore';
6097 if (!empty($this->fk_product) && $this->fk_product > 0) {
6101 $this->error =
'ErrorProductIdDoesNotExists';
6102 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6110 $sql =
'INSERT INTO '.MAIN_DB_PREFIX.
'facturedet';
6111 $sql .=
' (fk_facture, fk_parent_line, label, description, qty,';
6112 $sql .=
' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6113 $sql .=
' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6114 $sql .=
' date_start, date_end, fk_code_ventilation, ';
6115 $sql .=
' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6116 $sql .=
' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6117 $sql .=
' situation_percent, fk_prev_id,';
6118 $sql .=
' fk_unit, fk_user_author, fk_user_modif,';
6119 $sql .=
' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
6121 $sql .=
" VALUES (".$this->fk_facture.
",";
6122 $sql .=
" ".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null").
",";
6123 $sql .=
" ".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null").
",";
6124 $sql .=
" '".$this->db->escape($this->desc).
"',";
6125 $sql .=
" ".price2num($this->qty).
",";
6126 $sql .=
" ".(empty($this->vat_src_code) ?
"''" :
"'".$this->db->escape($this->vat_src_code).
"'").
",";
6127 $sql .=
" ".price2num($this->tva_tx).
",";
6128 $sql .=
" ".price2num($this->localtax1_tx).
",";
6129 $sql .=
" ".price2num($this->localtax2_tx).
",";
6130 $sql .=
" '".$this->db->escape($this->localtax1_type).
"',";
6131 $sql .=
" '".$this->db->escape($this->localtax2_type).
"',";
6132 $sql .=
' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product :
"null").
',';
6133 $sql .=
" ".((int) $this->product_type).
",";
6134 $sql .=
" ".price2num($this->remise_percent).
",";
6135 $sql .=
" ".price2num($this->subprice).
",";
6136 $sql .=
" '".$this->db->escape($this->ref_ext).
"',";
6137 $sql .=
' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except :
"null").
',';
6138 $sql .=
" ".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null").
",";
6139 $sql .=
" ".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null").
",";
6140 $sql .=
' '.((int) $this->fk_code_ventilation).
',';
6141 $sql .=
' '.((int) $this->rang).
',';
6142 $sql .=
' '.((int) $this->special_code).
',';
6143 $sql .=
' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice :
"null").
',';
6144 $sql .=
' '.price2num($this->pa_ht).
',';
6145 $sql .=
" '".$this->db->escape($this->info_bits).
"',";
6146 $sql .=
" ".price2num($this->total_ht).
",";
6147 $sql .=
" ".price2num($this->total_tva).
",";
6148 $sql .=
" ".price2num($this->total_ttc).
",";
6149 $sql .=
" ".price2num($this->total_localtax1).
",";
6150 $sql .=
" ".price2num($this->total_localtax2);
6151 $sql .=
", ".((float) $this->situation_percent);
6152 $sql .=
", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id :
"null");
6153 $sql .=
", ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6154 $sql .=
", ".((int) $user->id);
6155 $sql .=
", ".((int) $user->id);
6156 $sql .=
", ".(int) $this->fk_multicurrency;
6157 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
6158 $sql .=
", ".price2num($this->multicurrency_subprice);
6159 $sql .=
", ".price2num($this->multicurrency_total_ht);
6160 $sql .=
", ".price2num($this->multicurrency_total_tva);
6161 $sql .=
", ".price2num($this->multicurrency_total_ttc);
6164 dol_syslog(get_class($this).
"::insert", LOG_DEBUG);
6165 $resql = $this->
db->query(
$sql);
6167 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facturedet');
6168 $this->
rowid = $this->id;
6179 if ($this->fk_remise_except) {
6181 $result = $discount->fetch($this->fk_remise_except);
6186 if ($discount->fk_facture_line > 0) {
6187 if (empty($noerrorifdiscountalreadylinked)) {
6188 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed", $discount->id);
6189 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6190 $this->
db->rollback();
6194 $result = $discount->link_to_invoice($this->
rowid, 0);
6196 $this->error = $discount->error;
6197 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6198 $this->
db->rollback();
6203 $this->error = $langs->trans(
"ErrorADiscountThatHasBeenRemovedIsIncluded");
6204 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6205 $this->
db->rollback();
6209 $this->error = $discount->error;
6210 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6211 $this->
db->rollback();
6218 $result = $this->
call_trigger(
'LINEBILL_INSERT', $user);
6220 $this->
db->rollback();
6226 $this->
db->commit();
6229 $this->error = $this->
db->lasterror();
6230 $this->
db->rollback();
6242 public function update($user =
'', $notrigger = 0)
6244 global $user, $conf;
6248 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6251 $this->desc = trim($this->desc);
6252 if (empty($this->ref_ext)) {
6253 $this->ref_ext =
'';
6255 if (empty($this->tva_tx)) {
6258 if (empty($this->localtax1_tx)) {
6259 $this->localtax1_tx = 0;
6261 if (empty($this->localtax2_tx)) {
6262 $this->localtax2_tx = 0;
6264 if (empty($this->localtax1_type)) {
6265 $this->localtax1_type = 0;
6267 if (empty($this->localtax2_type)) {
6268 $this->localtax2_type = 0;
6270 if (empty($this->total_localtax1)) {
6271 $this->total_localtax1 = 0;
6273 if (empty($this->total_localtax2)) {
6274 $this->total_localtax2 = 0;
6276 if (empty($this->remise_percent)) {
6277 $this->remise_percent = 0;
6279 if (empty($this->info_bits)) {
6280 $this->info_bits = 0;
6282 if (empty($this->special_code)) {
6283 $this->special_code = 0;
6285 if (empty($this->product_type)) {
6286 $this->product_type = 0;
6288 if (empty($this->fk_parent_line)) {
6289 $this->fk_parent_line = 0;
6291 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6292 $this->situation_percent = 100;
6294 if (empty($this->pa_ht)) {
6298 if (empty($this->multicurrency_subprice)) {
6299 $this->multicurrency_subprice = 0;
6301 if (empty($this->multicurrency_total_ht)) {
6302 $this->multicurrency_total_ht = 0;
6304 if (empty($this->multicurrency_total_tva)) {
6305 $this->multicurrency_total_tva = 0;
6307 if (empty($this->multicurrency_total_ttc)) {
6308 $this->multicurrency_total_ttc = 0;
6312 if ($this->product_type < 0) {
6317 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6319 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6323 $this->pa_ht = $result;
6330 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6331 $sql .=
" description='".$this->db->escape($this->desc).
"'";
6332 $sql .=
", ref_ext='".$this->db->escape($this->ref_ext).
"'";
6333 $sql .=
", label=".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null");
6334 $sql .=
", subprice=".price2num($this->subprice);
6335 $sql .=
", remise_percent=".price2num($this->remise_percent);
6336 if ($this->fk_remise_except) {
6337 $sql .=
", fk_remise_except=".$this->fk_remise_except;
6339 $sql .=
", fk_remise_except=null";
6341 $sql .=
", vat_src_code = '".(empty($this->vat_src_code) ?
'' : $this->
db->escape($this->vat_src_code)).
"'";
6342 $sql .=
", tva_tx=".price2num($this->tva_tx);
6343 $sql .=
", localtax1_tx=".price2num($this->localtax1_tx);
6344 $sql .=
", localtax2_tx=".price2num($this->localtax2_tx);
6345 $sql .=
", localtax1_type='".$this->db->escape($this->localtax1_type).
"'";
6346 $sql .=
", localtax2_type='".$this->db->escape($this->localtax2_type).
"'";
6347 $sql .=
", qty=".price2num($this->qty);
6348 $sql .=
", date_start=".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null");
6349 $sql .=
", date_end=".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null");
6350 $sql .=
", product_type=".$this->product_type;
6351 $sql .=
", info_bits='".$this->db->escape($this->info_bits).
"'";
6352 $sql .=
", special_code='".$this->db->escape($this->special_code).
"'";
6353 if (empty($this->skip_update_total)) {
6354 $sql .=
", total_ht=".price2num($this->total_ht);
6355 $sql .=
", total_tva=".price2num($this->total_tva);
6356 $sql .=
", total_ttc=".price2num($this->total_ttc);
6357 $sql .=
", total_localtax1=".price2num($this->total_localtax1);
6358 $sql .=
", total_localtax2=".price2num($this->total_localtax2);
6360 $sql .=
", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ?
"'".$this->db->escape($this->fk_fournprice).
"'" :
"null");
6361 $sql .=
", buy_price_ht=".(($this->pa_ht || (string) $this->pa_ht ===
'0') ?
price2num($this->pa_ht) :
"null");
6362 $sql .=
", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null");
6363 if (!empty($this->rang)) {
6364 $sql .=
", rang=".((int) $this->rang);
6366 $sql .=
", situation_percent = ".((float) $this->situation_percent);
6367 $sql .=
", fk_unit = ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6368 $sql .=
", fk_user_modif = ".((int) $user->id);
6371 $sql .=
", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6372 $sql .=
", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6373 $sql .=
", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6374 $sql .=
", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6376 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6378 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
6379 $resql = $this->
db->query(
$sql);
6382 $this->
id = $this->rowid;
6389 if (!$error && !$notrigger) {
6391 $result = $this->
call_trigger(
'LINEBILL_MODIFY', $user);
6393 $this->
db->rollback();
6398 $this->
db->commit();
6401 $this->error = $this->
db->error();
6402 $this->
db->rollback();
6414 public function delete($tmpuser =
null, $notrigger =
false)
6421 if (empty($notrigger)) {
6422 $result = $this->
call_trigger(
'LINEBILL_DELETE', $user);
6424 $this->
db->rollback();
6433 $this->
db->rollback();
6437 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->
rowid);
6439 if ($this->
db->query(
$sql)) {
6440 $this->
db->commit();
6443 $this->error = $this->
db->error().
" sql=".
$sql;
6444 $this->
db->rollback();
6460 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6463 if (empty($this->total_localtax1)) {
6464 $this->total_localtax1 = 0;
6466 if (empty($this->total_localtax2)) {
6467 $this->total_localtax2 = 0;
6471 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6472 $sql .=
" total_ht=".price2num($this->total_ht);
6473 $sql .=
",total_tva=".price2num($this->total_tva);
6474 $sql .=
",total_localtax1=".price2num($this->total_localtax1);
6475 $sql .=
",total_localtax2=".price2num($this->total_localtax2);
6476 $sql .=
",total_ttc=".price2num($this->total_ttc);
6477 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6479 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6481 $resql = $this->
db->query(
$sql);
6483 $this->
db->commit();
6486 $this->error = $this->
db->error();
6487 $this->
db->rollback();
6504 global $invoicecache;
6505 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6509 if (!isset($invoicecache[$invoiceid])) {
6510 $invoicecache[$invoiceid] =
new Facture($this->
db);
6511 $invoicecache[$invoiceid]->fetch($invoiceid);
6517 $sql =
"SELECT situation_percent FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->fk_prev_id);
6518 $resql = $this->
db->query(
$sql);
6519 if ($resql && $this->
db->num_rows($resql) > 0) {
6520 $res = $this->
db->fetch_array($resql);
6522 $returnPercent = floatval($res[
'situation_percent']);
6524 if ($include_credit_note) {
6525 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6526 $sql .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6527 $sql .=
" WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6528 $sql .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6529 $sql .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6531 $res = $this->
db->query(
$sql);
6533 while ($obj = $this->
db->fetch_object($res)) {
6534 $returnPercent = $returnPercent + floatval($obj->situation_percent);
6541 return $returnPercent;
6543 $this->error = $this->
db->error();
6544 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6545 $this->
db->rollback();