43 require_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
44 require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobjectline.class.php';
45 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
46 require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
47 require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
48 require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
51 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
54 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
65 public $element =
'facture';
70 public $table_element =
'facture';
75 public $table_element_line =
'facturedet';
80 public $fk_element =
'fk_facture';
85 public $picto =
'bill';
91 public $ismultientitymanaged = 1;
97 public $restrictiononfksoc = 1;
120 public $fk_user_author;
125 public $fk_user_valid;
130 public $fk_user_modif;
141 public $date_livraison;
146 public $delivery_date;
158 public $ref_customer;
165 public $remise_absolue;
166 public $remise_percent;
169 public $total_localtax1;
170 public $total_localtax2;
172 public $revenuestamp;
202 public $linked_objects = array();
204 public $date_lim_reglement;
205 public $cond_reglement_code;
206 public $mode_reglement_code;
216 public $lines = array();
219 public $extraparams = array();
223 public $date_pointoftax;
229 public $fk_multicurrency;
231 public $multicurrency_code;
232 public $multicurrency_tx;
233 public $multicurrency_total_ht;
234 public $multicurrency_total_tva;
235 public $multicurrency_total_ttc;
240 public $situation_cycle_ref;
245 public $situation_counter;
250 public $situation_final;
255 public $tab_previous_situation_invoice = array();
260 public $tab_next_situation_invoice = array();
267 public $retained_warranty;
272 public $retained_warranty_date_limit;
277 public $retained_warranty_fk_cond_reglement;
308 public $fields = array(
309 'rowid' =>array(
'type'=>
'integer',
'label'=>
'TechnicalID',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>1),
310 'ref' =>array(
'type'=>
'varchar(30)',
'label'=>
'Ref',
'enabled'=>1,
'visible'=>1,
'notnull'=>1,
'showoncombobox'=>1,
'position'=>5),
311 'entity' =>array(
'type'=>
'integer',
'label'=>
'Entity',
'default'=>1,
'enabled'=>1,
'visible'=>-2,
'notnull'=>1,
'position'=>20,
'index'=>1),
312 'ref_client' =>array(
'type'=>
'varchar(255)',
'label'=>
'RefCustomer',
'enabled'=>1,
'visible'=>-1,
'position'=>10),
313 'ref_ext' =>array(
'type'=>
'varchar(255)',
'label'=>
'Ref ext',
'enabled'=>1,
'visible'=>0,
'position'=>12),
314 'type' =>array(
'type'=>
'smallint(6)',
'label'=>
'Type',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>15),
316 'fk_soc' =>array(
'type'=>
'integer:Societe:societe/class/societe.class.php',
'label'=>
'ThirdParty',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>50),
317 'datef' =>array(
'type'=>
'date',
'label'=>
'DateInvoice',
'enabled'=>1,
'visible'=>1,
'position'=>20),
318 'date_valid' =>array(
'type'=>
'date',
'label'=>
'DateValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>22),
319 'date_lim_reglement' =>array(
'type'=>
'date',
'label'=>
'DateDue',
'enabled'=>1,
'visible'=>1,
'position'=>25),
320 'date_closing' =>array(
'type'=>
'datetime',
'label'=>
'Date closing',
'enabled'=>1,
'visible'=>-1,
'position'=>30),
321 'paye' =>array(
'type'=>
'smallint(6)',
'label'=>
'InvoicePaidCompletely',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>80),
323 'remise_percent' =>array(
'type'=>
'double',
'label'=>
'RelativeDiscount',
'enabled'=>1,
'visible'=>-1,
'position'=>90),
324 'remise_absolue' =>array(
'type'=>
'double',
'label'=>
'CustomerRelativeDiscount',
'enabled'=>1,
'visible'=>-1,
'position'=>91),
326 'close_code' =>array(
'type'=>
'varchar(16)',
'label'=>
'EarlyClosingReason',
'enabled'=>1,
'visible'=>-1,
'position'=>92),
327 'close_note' =>array(
'type'=>
'varchar(128)',
'label'=>
'EarlyClosingComment',
'enabled'=>1,
'visible'=>-1,
'position'=>93),
328 'total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountHT',
'enabled'=>1,
'visible'=>1,
'position'=>95,
'isameasure'=>1),
329 'total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountVAT',
'enabled'=>1,
'visible'=>-1,
'position'=>100,
'isameasure'=>1),
330 'localtax1' =>array(
'type'=>
'double(24,8)',
'label'=>
'LT1',
'enabled'=>1,
'visible'=>-1,
'position'=>110,
'isameasure'=>1),
331 'localtax2' =>array(
'type'=>
'double(24,8)',
'label'=>
'LT2',
'enabled'=>1,
'visible'=>-1,
'position'=>120,
'isameasure'=>1),
332 'revenuestamp' =>array(
'type'=>
'double(24,8)',
'label'=>
'RevenueStamp',
'enabled'=>1,
'visible'=>-1,
'position'=>115,
'isameasure'=>1),
333 'total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountTTC',
'enabled'=>1,
'visible'=>1,
'position'=>130,
'isameasure'=>1),
334 'fk_facture_source' =>array(
'type'=>
'integer',
'label'=>
'SourceInvoice',
'enabled'=>1,
'visible'=>-1,
'position'=>170),
335 'fk_projet' =>array(
'type'=>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label'=>
'Project',
'enabled'=>1,
'visible'=>-1,
'position'=>175),
336 'fk_account' =>array(
'type'=>
'integer',
'label'=>
'Fk account',
'enabled'=>1,
'visible'=>-1,
'position'=>180),
337 'fk_currency' =>array(
'type'=>
'varchar(3)',
'label'=>
'CurrencyCode',
'enabled'=>1,
'visible'=>-1,
'position'=>185),
338 'fk_cond_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentTerm',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>190),
339 'fk_mode_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentMode',
'enabled'=>1,
'visible'=>-1,
'position'=>195),
340 'note_private' =>array(
'type'=>
'text',
'label'=>
'NotePrivate',
'enabled'=>1,
'visible'=>0,
'position'=>205),
341 'note_public' =>array(
'type'=>
'text',
'label'=>
'NotePublic',
'enabled'=>1,
'visible'=>0,
'position'=>210),
342 'model_pdf' =>array(
'type'=>
'varchar(255)',
'label'=>
'Model pdf',
'enabled'=>1,
'visible'=>0,
'position'=>215),
343 'extraparams' =>array(
'type'=>
'varchar(255)',
'label'=>
'Extraparams',
'enabled'=>1,
'visible'=>-1,
'position'=>225),
344 'situation_cycle_ref' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation cycle ref',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>230),
345 'situation_counter' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation counter',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>235),
346 'situation_final' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation final',
'enabled'=>
'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1',
'visible'=>-1,
'position'=>240),
347 'retained_warranty' =>array(
'type'=>
'double',
'label'=>
'Retained warranty',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>245),
348 'retained_warranty_date_limit' =>array(
'type'=>
'date',
'label'=>
'Retained warranty date limit',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>250),
349 'retained_warranty_fk_cond_reglement' =>array(
'type'=>
'integer',
'label'=>
'Retained warranty fk cond reglement',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>255),
350 'fk_incoterms' =>array(
'type'=>
'integer',
'label'=>
'IncotermCode',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>260),
351 'location_incoterms' =>array(
'type'=>
'varchar(255)',
'label'=>
'IncotermLabel',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>265),
352 'date_pointoftax' =>array(
'type'=>
'date',
'label'=>
'DatePointOfTax',
'enabled'=>
'$conf->global->INVOICE_POINTOFTAX_DATE',
'visible'=>-1,
'position'=>270),
353 'fk_multicurrency' =>array(
'type'=>
'integer',
'label'=>
'MulticurrencyID',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>275),
354 'multicurrency_code' =>array(
'type'=>
'varchar(255)',
'label'=>
'Currency',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>280),
355 'multicurrency_tx' =>array(
'type'=>
'double(24,8)',
'label'=>
'CurrencyRate',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>285,
'isameasure'=>1),
356 'multicurrency_total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountHT',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>290,
'isameasure'=>1),
357 'multicurrency_total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountVAT',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>291,
'isameasure'=>1),
358 'multicurrency_total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountTTC',
'enabled'=>
'isModEnabled("multicurrency")',
'visible'=>-1,
'position'=>292,
'isameasure'=>1),
359 'fk_fac_rec_source' =>array(
'type'=>
'integer',
'label'=>
'RecurringInvoiceSource',
'enabled'=>1,
'visible'=>-1,
'position'=>305),
360 'last_main_doc' =>array(
'type'=>
'varchar(255)',
'label'=>
'LastMainDoc',
'enabled'=>1,
'visible'=>-1,
'position'=>310),
361 'module_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSModule',
'enabled'=>1,
'visible'=>-1,
'position'=>315),
362 'pos_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSTerminal',
'enabled'=>1,
'visible'=>-1,
'position'=>320),
363 'datec' =>array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'enabled'=>1,
'visible'=>-1,
'position'=>500),
364 'tms' =>array(
'type'=>
'timestamp',
'label'=>
'DateModificationShort',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>502),
365 'fk_user_author' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'enabled'=>1,
'visible'=>-1,
'position'=>506),
366 'fk_user_modif' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'enabled'=>1,
'visible'=>-1,
'notnull'=>-1,
'position'=>508),
367 'fk_user_valid' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>510),
368 'fk_user_closing' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserClosing',
'enabled'=>1,
'visible'=>-1,
'position'=>512),
369 'import_key' =>array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'enabled'=>1,
'visible'=>-2,
'position'=>900),
370 'fk_statut' =>array(
'type'=>
'smallint(6)',
'label'=>
'Status',
'enabled'=>1,
'visible'=>1,
'notnull'=>1,
'position'=>1000,
'arrayofkeyval'=>array(0=>
'Draft', 1=>
'Validated', 2=>
'Paid', 3=>
'Abandonned')),
432 const CLOSECODE_DISCOUNTVAT =
'discount_vat';
433 const CLOSECODE_BADDEBT =
'badcustomer';
434 const CLOSECODE_BANKCHARGE =
'bankcharge';
435 const CLOSECODE_OTHER =
'other';
437 const CLOSECODE_ABANDONED =
'abandon';
438 const CLOSECODE_REPLACED =
'replaced';
461 public function create(
User $user, $notrigger = 0, $forceduedate = 0)
463 global $langs, $conf, $mysoc, $hookmanager;
467 if (empty($this->
type)) {
470 $this->ref_client = trim($this->ref_client);
471 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
472 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
473 $this->note_public = trim($this->note_public);
474 if (!$this->cond_reglement_id) {
475 $this->cond_reglement_id = 0;
477 if (!$this->mode_reglement_id) {
478 $this->mode_reglement_id = 0;
480 $this->brouillon = 1;
484 if (!empty($this->multicurrency_code)) {
486 if (empty($this->multicurrency_tx)) {
494 $this->fk_multicurrency = 0;
496 if (empty($this->fk_multicurrency)) {
497 $this->multicurrency_code = $conf->currency;
498 $this->fk_multicurrency = 0;
499 $this->multicurrency_tx = 1;
502 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
505 if (empty($this->date)) {
506 $this->error =
"Try to create an invoice with an empty parameter (date)";
507 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
511 $result = $soc->fetch($this->socid);
513 $this->error =
"Failed to fetch company: ".$soc->error;
514 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
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->ref_customer = trim($this->ref_customer);
573 $this->note_public = trim($this->note_public);
574 $this->note_private = trim($this->note_private);
575 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
577 $this->array_options = $_facrec->array_options;
579 if (!$this->mode_reglement_id) {
580 $this->mode_reglement_id = 0;
582 $this->brouillon = 1;
586 $this->linked_objects = $_facrec->linkedObjectsIds;
591 if ($_facrec->frequency > 0) {
592 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
593 if (empty($_facrec->date_when)) {
594 $_facrec->date_when = $now;
596 $next_date = $_facrec->getNextDate();
597 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
599 $result = $_facrec->setNextDate($next_date, 1);
603 $outputlangs = $langs;
606 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
607 $newlang = $this->thirdparty->default_lang;
609 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
610 $newlang = $this->default_lang;
612 if (!empty($newlang)) {
614 $outputlangs->setDefaultLang($newlang);
620 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
623 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
626 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
629 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
630 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
631 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
632 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
633 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
644 if (empty($forceduedate)) {
650 $this->date_lim_reglement = $duedate;
652 $this->date_lim_reglement = $forceduedate;
656 $socid = $this->socid;
658 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
665 $sql .=
", remise_absolue";
666 $sql .=
", remise_percent";
668 $sql .=
", date_pointoftax";
669 $sql .=
", note_private";
670 $sql .=
", note_public";
671 $sql .=
", ref_client";
672 $sql .=
", fk_account";
673 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
674 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
675 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
676 $sql .=
", fk_incoterms, location_incoterms";
677 $sql .=
", fk_multicurrency";
678 $sql .=
", multicurrency_code";
679 $sql .=
", multicurrency_tx";
680 $sql .=
", retained_warranty";
681 $sql .=
", retained_warranty_date_limit";
682 $sql .=
", retained_warranty_fk_cond_reglement";
686 $sql .=
", ".setEntity($this);
687 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
688 $sql .=
", '".$this->db->escape($this->
type).
"'";
689 $sql .=
", ".((int) $socid);
690 $sql .=
", '".$this->db->idate($now).
"'";
691 $sql .=
", ".($this->remise_absolue > 0 ? $this->remise_absolue :
'NULL');
692 $sql .=
", ".($this->remise_percent > 0 ? $this->remise_percent :
'NULL');
693 $sql .=
", '".$this->db->idate($this->date).
"'";
694 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
695 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
696 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
697 $sql .=
", ".($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null");
698 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
699 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
700 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape($this->pos_source).
"'" :
"null");
701 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape($this->fk_fac_rec_source).
"'" :
"null");
702 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape($this->fk_facture_source).
"'" :
"null");
703 $sql .=
", ".($user->id > 0 ? (int) $user->id :
"null");
704 $sql .=
", ".($this->fk_project ? $this->fk_project :
"null");
705 $sql .=
", ".((int) $this->cond_reglement_id);
706 $sql .=
", ".((int) $this->mode_reglement_id);
707 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
708 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
709 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape($this->situation_cycle_ref).
"'" :
"null");
710 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape($this->situation_counter).
"'" :
"null");
711 $sql .=
", ".($this->situation_final ? $this->situation_final : 0);
712 $sql .=
", ".(int) $this->fk_incoterms;
713 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
714 $sql .=
", ".(int) $this->fk_multicurrency;
715 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
716 $sql .=
", ".(double) $this->multicurrency_tx;
717 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty));
718 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
719 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
724 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facture');
727 $this->
ref =
'(PROV'.$this->id.
')';
728 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->
db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
735 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
736 $this->linked_objects = $this->linkedObjectsIds;
740 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
741 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
742 if (is_array($tmp_origin_id)) {
743 foreach ($tmp_origin_id as $origin_id) {
746 $this->error = $this->
db->lasterror();
752 $origin_id = $tmp_origin_id;
755 $this->error = $this->
db->lasterror();
763 if (!$error && $this->
id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) {
764 $originforcontact = $this->origin;
765 $originidforcontact = $this->origin_id;
766 if ($originforcontact ==
'shipping') {
767 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
769 $exp->fetch($this->origin_id);
770 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
771 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
772 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
773 $originforcontact =
'commande';
774 if (is_object($value)) {
775 $originidforcontact = $value->id;
777 $originidforcontact = $value;
784 $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";
785 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->
db->escape($originforcontact).
"'";
787 $resqlcontact = $this->
db->query($sqlcontact);
789 while ($objcontact = $this->
db->fetch_object($resqlcontact)) {
791 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
801 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
804 dol_syslog(
"There is ".count($this->lines).
" lines that are invoice lines objects");
805 foreach ($this->lines as $i => $val) {
806 $newinvoiceline = $this->lines[$i];
808 $newinvoiceline->context = $this->context;
810 $newinvoiceline->fk_facture = $this->id;
812 $newinvoiceline->origin = $this->lines[$i]->element;
813 $newinvoiceline->origin_id = $this->lines[$i]->id;
816 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
817 $newinvoiceline->date_start = $originaldatewhen;
819 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
820 $newinvoiceline->date_end = $previousdaynextdatewhen;
825 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
830 $vatrate = $newinvoiceline->tva_tx;
831 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', $vatrate)) $vatrate.=
' ('.$newinvoiceline->vat_src_code.
')';
833 $newinvoiceline->fk_parent_line = $fk_parent_line;
837 $discount->fetch($newinvoiceline->fk_remise_except);
839 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
840 $newinvoiceline->fk_remise_except = $discountId;
844 $newinvoiceline->desc,
845 $newinvoiceline->subprice,
846 $newinvoiceline->qty,
848 $newinvoiceline->localtax1_tx,
849 $newinvoiceline->localtax2_tx,
850 $newinvoiceline->fk_product,
851 $newinvoiceline->remise_percent,
852 $newinvoiceline->date_start,
853 $newinvoiceline->date_end,
854 $newinvoiceline->fk_code_ventilation,
855 $newinvoiceline->info_bits,
856 $newinvoiceline->fk_remise_except,
859 $newinvoiceline->product_type,
860 $newinvoiceline->rang,
861 $newinvoiceline->special_code,
862 $newinvoiceline->element,
865 $newinvoiceline->fk_fournprice,
866 $newinvoiceline->pa_ht,
867 $newinvoiceline->label,
868 $newinvoiceline->array_options,
869 $newinvoiceline->situation_percent,
870 $newinvoiceline->fk_prev_id,
871 $newinvoiceline->fk_unit,
872 $newinvoiceline->multicurrency_subprice,
873 $newinvoiceline->ref_ext,
878 if ($result > 0 && $newinvoiceline->product_type == 9) {
879 $fk_parent_line = $result;
883 $this->error = $newinvoiceline->error;
884 $this->errors = $newinvoiceline->errors;
889 } elseif (!$error && empty($this->fac_rec)) {
892 dol_syslog(
"There is ".count($this->lines).
" lines that are array lines");
894 foreach ($this->lines as $i => $val) {
895 $line = $this->lines[$i];
899 if (!is_object($line)) {
900 $line = (object) $line;
905 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
910 $vatrate = $line->tva_tx;
911 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', $vatrate)) {
912 $vatrate .=
' ('.$line->vat_src_code.
')';
915 if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
916 $originid = $line->origin_id;
917 $origintype = $line->origin;
919 $originid = $line->id;
920 $origintype = $this->element;
924 if (empty($line->ref_ext)) {
936 $line->remise_percent,
939 $line->fk_code_ventilation,
941 $line->fk_remise_except,
950 $line->fk_fournprice,
953 $line->array_options,
954 $line->situation_percent,
957 $line->multicurrency_subprice,
962 $this->error = $this->
db->lasterror();
964 $this->
db->rollback();
969 if ($result > 0 && $line->product_type == 9) {
970 $fk_parent_line = $result;
979 if (!$error && $this->fac_rec > 0) {
980 foreach ($_facrec->lines as $i => $val) {
981 if ($_facrec->lines[$i]->fk_product) {
983 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
994 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
995 $tva_npr = $_facrec->lines[$i]->info_bits;
996 if (empty($tva_tx)) {
999 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1000 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1002 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1003 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1006 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1007 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1009 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1014 if ($conf->global->MARGIN_TYPE ==
'costprice' && !empty($producttmp->cost_price)) {
1015 $buyprice = $producttmp->cost_price;
1016 } elseif (
isModEnabled(
'stock') && ($conf->global->MARGIN_TYPE ==
'costprice' || $conf->global->MARGIN_TYPE ==
'pmp') && !empty($producttmp->pmp)) {
1017 $buyprice = $producttmp->pmp;
1019 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1020 if ($producttmp->product_fourn_price_id > 0) {
1021 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1027 $result_insert = $this->
addline(
1028 $_facrec->lines[$i]->desc,
1029 $_facrec->lines[$i]->subprice,
1030 $_facrec->lines[$i]->qty,
1034 $_facrec->lines[$i]->fk_product,
1035 $_facrec->lines[$i]->remise_percent,
1036 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1037 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1043 $_facrec->lines[$i]->product_type,
1044 $_facrec->lines[$i]->rang,
1045 $_facrec->lines[$i]->special_code,
1049 $fk_product_fournisseur_price,
1051 $_facrec->lines[$i]->label,
1052 empty($_facrec->lines[$i]->array_options) ?
null:$_facrec->lines[$i]->array_options,
1053 $_facrec->lines[$i]->situation_percent,
1055 $_facrec->lines[$i]->fk_unit,
1056 $_facrec->lines[$i]->multicurrency_subprice,
1057 $_facrec->lines[$i]->ref_ext,
1061 if ($result_insert < 0) {
1063 $this->error = $this->
db->error();
1082 if (!$error && !$notrigger) {
1092 $this->
db->commit();
1095 $this->
db->rollback();
1099 $this->error = $langs->trans(
'FailedToUpdatePrice');
1100 $this->
db->rollback();
1104 dol_syslog(get_class($this).
"::create error ".$this->error, LOG_ERR);
1105 $this->
db->rollback();
1109 $this->error = $this->
db->error();
1110 $this->
db->rollback();
1134 if (!empty($this->array_options)) {
1135 $facture->array_options = $this->array_options;
1138 foreach ($this->lines as &$line) {
1139 $line->fetch_optionals();
1143 $facture->type = $this->type;
1144 $facture->socid = $this->socid;
1145 $facture->date = $this->date;
1146 $facture->date_pointoftax = $this->date_pointoftax;
1147 $facture->note_public = $this->note_public;
1148 $facture->note_private = $this->note_private;
1149 $facture->ref_client = $this->ref_client;
1150 $facture->modelpdf = $this->model_pdf;
1151 $facture->model_pdf = $this->model_pdf;
1152 $facture->fk_project = $this->fk_project;
1153 $facture->cond_reglement_id = $this->cond_reglement_id;
1154 $facture->mode_reglement_id = $this->mode_reglement_id;
1155 $facture->remise_absolue = $this->remise_absolue;
1156 $facture->remise_percent = $this->remise_percent;
1158 $facture->origin = $this->origin;
1159 $facture->origin_id = $this->origin_id;
1161 $facture->lines = $this->lines;
1162 $facture->situation_counter = $this->situation_counter;
1163 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1164 $facture->situation_final = $this->situation_final;
1166 $facture->retained_warranty = $this->retained_warranty;
1167 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1168 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1170 $facture->fk_user_author = $user->id;
1174 foreach ($facture->lines as $i => $tmpline) {
1175 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1176 if ($invertdetail) {
1177 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1178 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1179 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1180 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1181 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1182 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1183 $facture->lines[$i]->ref_ext =
'';
1187 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1189 $facid = $facture->create($user);
1191 $this->error = $facture->error;
1192 $this->errors = $facture->errors;
1193 } elseif ($this->
type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
1196 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1197 foreach ($Tfk_object as $fk_object) {
1198 $facture->add_object_linked($typeObject, $fk_object);
1202 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1218 global $conf, $hookmanager;
1226 $object->fetch($fromid);
1229 $objFrom = clone $object;
1232 if (!empty($this->socid) && $this->socid != $object->socid) {
1235 if ($objsoc->fetch($this->socid) > 0) {
1236 $object->socid = $objsoc->id;
1237 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1238 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1239 $object->fk_project =
'';
1240 $object->fk_delivery_address =
'';
1251 $object->date = (empty($this->date) ?
dol_now() : $this->date);
1252 $object->user_author = $user->id;
1253 $object->user_valid =
null;
1254 $object->fk_user_author = $user->id;
1255 $object->fk_user_valid =
null;
1256 $object->fk_facture_source = 0;
1257 $object->date_creation =
'';
1258 $object->date_modification =
'';
1259 $object->date_validation =
'';
1260 $object->ref_client =
'';
1261 $object->close_code =
'';
1262 $object->close_note =
'';
1264 $object->note_private =
'';
1265 $object->note_public =
'';
1269 foreach ($object->lines as $i => $line) {
1270 if (($object->lines[$i]->info_bits & 0x02) == 0x02) {
1271 unset($object->lines[$i]);
1277 if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
1289 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1290 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1294 $object->lines[$i]->date_start = $newFirst;
1295 $object->lines[$i]->date_end = $newLast;
1299 $object->lines[$i]->ref_ext =
'';
1303 $object->context[
'createfromclone'] =
'createfromclone';
1304 $result = $object->create($user);
1307 $this->error = $object->error;
1308 $this->errors = $object->errors;
1311 if ($object->copy_linked_contact($objFrom,
'internal') < 0) {
1313 $this->error = $object->error;
1314 $this->errors = $object->errors;
1315 } elseif ($object->socid == $objFrom->socid) {
1317 if ($object->copy_linked_contact($objFrom,
'external') < 0) {
1319 $this->error = $object->error;
1320 $this->errors = $object->errors;
1327 if (is_object($hookmanager)) {
1328 $parameters = array(
'objFrom'=>$objFrom);
1330 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $object, $action);
1332 $this->errors += $hookmanager->errors;
1333 $this->error = $hookmanager->error;
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);
1467 $this->errors += $hookmanager->errors;
1468 $this->error = $hookmanager->error;
1496 global $conf, $langs, $hookmanager, $action;
1498 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1499 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1504 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1508 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1510 if ($date > (
dol_get_last_hour(
dol_now(
'tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1511 $origin->error =
'ErrorDateIsInFuture';
1515 if ($payment_terms_id <= 0) {
1516 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1520 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1522 if (empty($payment_conditions_deposit_percent)) {
1523 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1527 if (empty($origin->deposit_percent)) {
1528 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1532 $deposit =
new self($origin->db);
1533 $deposit->socid = $origin->socid;
1535 $deposit->fk_project = $origin->fk_project;
1536 $deposit->ref_client = $origin->ref_client;
1537 $deposit->date = $date;
1538 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1539 $deposit->cond_reglement_id = $payment_terms_id;
1540 $deposit->availability_id = $origin->availability_id;
1541 $deposit->demand_reason_id = $origin->demand_reason_id;
1542 $deposit->fk_account = $origin->fk_account;
1543 $deposit->fk_incoterms = $origin->fk_incoterms;
1544 $deposit->location_incoterms = $origin->location_incoterms;
1545 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1546 $deposit->multicurrency_code = $origin->multicurrency_code;
1547 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1548 $deposit->module_source = $origin->module_source;
1549 $deposit->pos_source = $origin->pos_source;
1550 $deposit->model_pdf =
'crabe';
1552 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1554 if (!empty($conf->global->$modelByTypeConfName)) {
1555 $deposit->model_pdf = $conf->global->$modelByTypeConfName;
1556 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
1557 $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
1560 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1561 $deposit->note_private = $origin->note_private;
1562 $deposit->note_public = $origin->note_public;
1565 $deposit->origin = $origin->element;
1566 $deposit->origin_id = $origin->id;
1568 $origin->fetch_optionals();
1570 foreach ($origin->array_options as $extrakey => $value) {
1571 $deposit->array_options[$extrakey] = $value;
1574 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1576 foreach ($overrideFields as $key => $value) {
1577 $deposit->$key = $value;
1580 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1582 $origin->db->begin();
1585 $createReturn = $deposit->create($user, $notrigger);
1587 if ($createReturn <= 0) {
1588 $origin->db->rollback();
1589 $origin->error = $deposit->error;
1590 $origin->errors = $deposit->errors;
1594 $amount_ttc_diff = 0;
1595 $amountdeposit = array();
1596 $descriptions = array();
1598 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1599 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1601 $TTotalByTva = array();
1602 foreach ($origin->lines as &$line) {
1603 if (!empty($line->special_code)) {
1606 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1607 $descriptions[$line->tva_tx] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1608 $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1609 $descriptions[$line->tva_tx] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1610 $descriptions[$line->tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1613 foreach ($TTotalByTva as $tva => &$total) {
1614 $coef = $total / $origin->total_ttc;
1615 $am = $amount * $coef;
1616 $amount_ttc_diff += $am;
1617 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1621 $lines = $origin->lines;
1622 $numlines = count($lines);
1623 for ($i = 0; $i < $numlines; $i++) {
1624 if (empty($lines[$i]->qty)) {
1627 if (!empty($lines[$i]->special_code)) {
1631 $totalamount += $lines[$i]->total_ht;
1632 $tva_tx = $lines[$i]->tva_tx;
1633 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1634 $descriptions[$tva_tx] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1635 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1636 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1637 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1640 if ($totalamount == 0) {
1641 $amountdeposit[0] = 0;
1644 $amount_ttc_diff = $amountdeposit[0];
1647 foreach ($amountdeposit as $tva => $amount) {
1648 if (empty($amount)) {
1652 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1655 if (!empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && !empty($descriptions[$tva])) {
1656 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1659 $addlineResult = $deposit->addline(
1666 (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1686 if ($addlineResult < 0) {
1687 $origin->db->rollback();
1688 $origin->error = $deposit->error;
1689 $origin->errors = $deposit->errors;
1694 $diff = $deposit->total_ttc - $amount_ttc_diff;
1696 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1697 $deposit->fetch_lines();
1698 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1700 $updatelineResult = $deposit->updateline(
1701 $deposit->lines[0]->id,
1702 $deposit->lines[0]->desc,
1704 $deposit->lines[0]->qty,
1705 $deposit->lines[0]->remise_percent,
1706 $deposit->lines[0]->date_start,
1707 $deposit->lines[0]->date_end,
1708 $deposit->lines[0]->tva_tx,
1712 $deposit->lines[0]->info_bits,
1713 $deposit->lines[0]->product_type,
1717 $deposit->lines[0]->pa_ht,
1718 $deposit->lines[0]->label,
1724 if ($updatelineResult < 0) {
1725 $origin->db->rollback();
1726 $origin->error = $deposit->error;
1727 $origin->errors = $deposit->errors;
1733 if (! is_object($hookmanager)) {
1734 require_once DOL_DOCUMENT_ROOT .
'/core/class/hookmanager.class.php';
1738 $hookmanager->initHooks(array(
'invoicedao'));
1740 $parameters = array(
'objFrom' => $origin);
1741 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1744 $origin->db->rollback();
1745 $origin->error = $hookmanager->error;
1746 $origin->errors = $hookmanager->errors;
1750 if (!empty($autoValidateDeposit)) {
1751 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1753 if ($validateReturn < 0) {
1754 $origin->db->rollback();
1755 $origin->error = $deposit->error;
1756 $origin->errors = $deposit->errors;
1761 unset($deposit->context[
'createdepositfromorigin']);
1763 $origin->db->commit();
1782 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
1784 global $langs, $conf, $user, $mysoc;
1786 if (!empty($conf->dol_no_mouse_hover)) {
1792 if ($option ==
'withdraw') {
1793 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
1795 $url = DOL_URL_ROOT.
'/compta/facture/card.php?facid='.$this->id;
1798 if (!$user->hasRight(
"facture",
"read")) {
1802 if ($option !==
'nolink') {
1804 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1805 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
1806 $add_save_lastsearch_values = 1;
1808 if ($add_save_lastsearch_values) {
1809 $url .=
'&save_lastsearch_values=1';
1817 $picto = $this->picto;
1818 if ($this->
type == self::TYPE_REPLACEMENT) {
1821 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1824 if ($this->
type == self::TYPE_DEPOSIT) {
1829 if ($user->hasRight(
"facture",
"read")) {
1830 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1831 if (isset($this->statut) && isset($this->alreadypaid)) {
1832 $label .=
' '.$this->getLibStatut(5, $this->alreadypaid);
1834 $label .=
' '.$this->getLibType(1);
1835 if (!empty($this->
ref)) {
1836 $label .=
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
1838 if (!empty($this->ref_client)) {
1839 $label .=
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_client;
1841 if (!empty($this->date)) {
1842 $label .=
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
1844 if (!empty($this->total_ht)) {
1845 $label .=
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1847 if (!empty($this->total_tva)) {
1848 $label .=
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1850 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1851 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1853 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1854 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1856 if (!empty($this->total_ttc)) {
1857 $label .=
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1860 $label .=
' - '.$moretitle;
1864 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
1865 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
1866 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1867 $label = $langs->trans(
"Invoice");
1868 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
1870 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
1871 $linkclose .=
' class="classfortooltip"';
1874 $linkstart =
'<a href="'.$url.
'"';
1875 $linkstart .= $linkclose.
'>';
1878 if ($option ==
'nolink') {
1883 $result .= $linkstart;
1885 $result .=
img_object(($notooltip ?
'' : $label), $picto, ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1887 if ($withpicto != 2) {
1888 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
1890 $result .= $linkend;
1892 if ($addlinktonotes) {
1893 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1896 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
1897 $result .=
' <span class="note inline-block">';
1898 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
1903 $result .=
'</span>';
1907 global $action, $hookmanager;
1908 $hookmanager->initHooks(array(
'invoicedao'));
1909 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value'=> $save_lastsearch_value,
'target' => $target);
1910 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
1912 $result = $hookmanager->resPrint;
1914 $result .= $hookmanager->resPrint;
1930 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused =
'', $fetch_situation =
false)
1932 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
1936 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.fk_soc';
1937 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
1938 $sql .=
', f.remise_percent, f.remise_absolue, f.remise';
1939 $sql .=
', f.datef as df, f.date_pointoftax';
1940 $sql .=
', f.date_lim_reglement as dlr';
1941 $sql .=
', f.datec as datec';
1942 $sql .=
', f.date_valid as datev';
1943 $sql .=
', f.tms as datem';
1944 $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';
1945 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
1946 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1947 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1948 $sql .=
', f.fk_account';
1949 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1950 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1951 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1952 $sql .=
', f.fk_incoterms, f.location_incoterms';
1953 $sql .=
', f.module_source, f.pos_source';
1954 $sql .=
", i.libelle as label_incoterms";
1955 $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";
1956 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
1957 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
1958 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
1959 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
1962 $sql .=
" WHERE f.rowid = ".((int) $rowid);
1964 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
1966 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
1969 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
1973 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
1977 $obj = $this->
db->fetch_object(
$resql);
1979 $this->
id = $obj->rowid;
1980 $this->entity = $obj->entity;
1982 $this->
ref = $obj->ref;
1983 $this->ref_client = $obj->ref_client;
1984 $this->ref_customer = $obj->ref_client;
1985 $this->ref_ext = $obj->ref_ext;
1986 $this->
type = $obj->type;
1987 $this->date = $this->
db->jdate($obj->df);
1988 $this->date_pointoftax = $this->
db->jdate($obj->date_pointoftax);
1989 $this->date_creation = $this->
db->jdate($obj->datec);
1990 $this->date_validation = $this->
db->jdate($obj->datev);
1991 $this->date_modification = $this->
db->jdate($obj->datem);
1992 $this->datem = $this->
db->jdate($obj->datem);
1993 $this->remise_percent = $obj->remise_percent;
1994 $this->remise_absolue = $obj->remise_absolue;
1995 $this->total_ht = $obj->total_ht;
1996 $this->total_tva = $obj->total_tva;
1997 $this->total_localtax1 = $obj->localtax1;
1998 $this->total_localtax2 = $obj->localtax2;
1999 $this->total_ttc = $obj->total_ttc;
2000 $this->revenuestamp = $obj->revenuestamp;
2001 $this->paye = $obj->paye;
2002 $this->close_code = $obj->close_code;
2003 $this->close_note = $obj->close_note;
2005 $this->socid = $obj->fk_soc;
2006 $this->thirdparty =
null;
2008 $this->fk_project = $obj->fk_project;
2009 $this->project =
null;
2011 $this->statut = $obj->fk_statut;
2012 $this->status = $obj->fk_statut;
2014 $this->date_lim_reglement = $this->
db->jdate($obj->dlr);
2015 $this->mode_reglement_id = $obj->fk_mode_reglement;
2016 $this->mode_reglement_code = $obj->mode_reglement_code;
2017 $this->mode_reglement = $obj->mode_reglement_libelle;
2018 $this->cond_reglement_id = $obj->fk_cond_reglement;
2019 $this->cond_reglement_code = $obj->cond_reglement_code;
2020 $this->cond_reglement = $obj->cond_reglement_libelle;
2021 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2022 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2023 $this->fk_facture_source = $obj->fk_facture_source;
2024 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2025 $this->note = $obj->note_private;
2026 $this->note_private = $obj->note_private;
2027 $this->note_public = $obj->note_public;
2028 $this->user_author = $obj->fk_user_author;
2029 $this->user_valid = $obj->fk_user_valid;
2030 $this->user_modification = $obj->fk_user_modif;
2031 $this->fk_user_author = $obj->fk_user_author;
2032 $this->fk_user_valid = $obj->fk_user_valid;
2033 $this->fk_user_modif = $obj->fk_user_modif;
2034 $this->model_pdf = $obj->model_pdf;
2035 $this->modelpdf = $obj->model_pdf;
2036 $this->last_main_doc = $obj->last_main_doc;
2037 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2038 $this->situation_counter = $obj->situation_counter;
2039 $this->situation_final = $obj->situation_final;
2040 $this->retained_warranty = $obj->retained_warranty;
2041 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2042 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2044 $this->extraparams = (array) json_decode($obj->extraparams,
true);
2047 $this->fk_incoterms = $obj->fk_incoterms;
2048 $this->location_incoterms = $obj->location_incoterms;
2049 $this->label_incoterms = $obj->label_incoterms;
2051 $this->module_source = $obj->module_source;
2052 $this->pos_source = $obj->pos_source;
2055 $this->fk_multicurrency = $obj->fk_multicurrency;
2056 $this->multicurrency_code = $obj->multicurrency_code;
2057 $this->multicurrency_tx = $obj->multicurrency_tx;
2058 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2059 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2060 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2062 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2066 if ($this->status == self::STATUS_DRAFT) {
2067 $this->brouillon = 1;
2075 $this->lines = array();
2079 $this->error = $this->
db->error();
2087 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2089 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2093 $this->error = $this->
db->lasterror();
2108 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2111 global $langs, $conf;
2113 $this->lines = array();
2115 $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,';
2116 $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,';
2117 $sql .=
' l.situation_percent, l.fk_prev_id,';
2118 $sql .=
' l.rang, l.special_code,';
2119 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2120 $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,';
2121 $sql .=
' l.fk_unit,';
2122 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2123 $sql .=
' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2124 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2125 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2126 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2127 $sql .=
' ORDER BY l.rang, l.rowid';
2129 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2130 $result = $this->
db->query($sql);
2132 $num = $this->
db->num_rows($result);
2135 $objp = $this->
db->fetch_object($result);
2138 $line->id = $objp->rowid;
2139 $line->rowid = $objp->rowid;
2140 $line->fk_facture = $objp->fk_facture;
2141 $line->label = $objp->custom_label;
2142 $line->desc = $objp->description;
2143 $line->description = $objp->description;
2144 $line->product_type = $objp->product_type;
2145 $line->ref = $objp->product_ref;
2146 $line->product_ref = $objp->product_ref;
2147 $line->libelle = $objp->product_label;
2148 $line->product_label = $objp->product_label;
2149 $line->product_desc = $objp->product_desc;
2150 $line->fk_product_type = $objp->fk_product_type;
2151 $line->qty = $objp->qty;
2152 $line->subprice = $objp->subprice;
2153 $line->ref_ext = $objp->ref_ext;
2155 $line->vat_src_code = $objp->vat_src_code;
2156 $line->tva_tx = $objp->tva_tx;
2157 $line->localtax1_tx = $objp->localtax1_tx;
2158 $line->localtax2_tx = $objp->localtax2_tx;
2159 $line->localtax1_type = $objp->localtax1_type;
2160 $line->localtax2_type = $objp->localtax2_type;
2161 $line->remise_percent = $objp->remise_percent;
2162 $line->fk_remise_except = $objp->fk_remise_except;
2163 $line->fk_product = $objp->fk_product;
2164 $line->date_start = $this->
db->jdate($objp->date_start);
2165 $line->date_end = $this->
db->jdate($objp->date_end);
2166 $line->date_start = $this->
db->jdate($objp->date_start);
2167 $line->date_end = $this->
db->jdate($objp->date_end);
2168 $line->info_bits = $objp->info_bits;
2169 $line->total_ht = $objp->total_ht;
2170 $line->total_tva = $objp->total_tva;
2171 $line->total_localtax1 = $objp->total_localtax1;
2172 $line->total_localtax2 = $objp->total_localtax2;
2173 $line->total_ttc = $objp->total_ttc;
2174 $line->code_ventilation = $objp->fk_code_ventilation;
2175 $line->fk_fournprice = $objp->fk_fournprice;
2176 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2177 $line->pa_ht = $marginInfos[0];
2178 $line->marge_tx = $marginInfos[1];
2179 $line->marque_tx = $marginInfos[2];
2180 $line->rang = $objp->rang;
2181 $line->special_code = $objp->special_code;
2182 $line->fk_parent_line = $objp->fk_parent_line;
2183 $line->situation_percent = $objp->situation_percent;
2184 $line->fk_prev_id = $objp->fk_prev_id;
2185 $line->fk_unit = $objp->fk_unit;
2188 $line->fk_accounting_account = $objp->fk_code_ventilation;
2191 $line->fk_multicurrency = $objp->fk_multicurrency;
2192 $line->multicurrency_code = $objp->multicurrency_code;
2193 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2194 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2195 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2196 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2198 $line->fetch_optionals();
2201 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2203 $tmpproduct->fetch($objp->fk_product);
2204 $tmpproduct->getMultiLangs();
2206 $line->multilangs = $tmpproduct->multilangs;
2209 $this->lines[$i] = $line;
2213 $this->
db->free($result);
2216 $this->error = $this->
db->error();
2231 $this->tab_previous_situation_invoice = array();
2232 $this->tab_next_situation_invoice = array();
2234 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2235 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2236 $sql .=
' AND entity = '.((int) $this->entity);
2237 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2238 $sql .=
' ORDER BY situation_counter ASC';
2240 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2241 $result = $this->
db->query($sql);
2242 if ($result && $this->
db->num_rows($result) > 0) {
2243 while ($objp = $this->
db->fetch_object($result)) {
2245 if ($invoice->fetch($objp->rowid) > 0) {
2246 if ($objp->situation_counter < $this->situation_counter
2247 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2249 $this->tab_previous_situation_invoice[] = $invoice;
2251 $this->tab_next_situation_invoice[] = $invoice;
2272 if (empty($this->
type)) {
2275 if (isset($this->
ref)) {
2276 $this->
ref = trim($this->
ref);
2278 if (isset($this->ref_ext)) {
2279 $this->ref_ext = trim($this->ref_ext);
2281 if (isset($this->ref_client)) {
2282 $this->ref_client = trim($this->ref_client);
2284 if (isset($this->increment)) {
2285 $this->increment = trim($this->increment);
2287 if (isset($this->close_code)) {
2288 $this->close_code = trim($this->close_code);
2290 if (isset($this->close_note)) {
2291 $this->close_note = trim($this->close_note);
2293 if (isset($this->note) || isset($this->note_private)) {
2294 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2296 if (isset($this->note) || isset($this->note_private)) {
2297 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2299 if (isset($this->note_public)) {
2300 $this->note_public = trim($this->note_public);
2302 if (isset($this->model_pdf)) {
2303 $this->model_pdf = trim($this->model_pdf);
2305 if (isset($this->import_key)) {
2306 $this->import_key = trim($this->import_key);
2308 if (isset($this->retained_warranty)) {
2309 $this->retained_warranty = floatval($this->retained_warranty);
2317 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2318 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2319 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2320 $sql .=
" type=".(isset($this->
type) ? $this->
db->escape($this->
type) :
"null").
",";
2321 $sql .=
" ref_client=".(isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null").
",";
2322 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2323 $sql .=
" fk_soc=".(isset($this->socid) ? $this->
db->escape($this->socid) :
"null").
",";
2324 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2325 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2326 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2327 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2328 $sql .=
" paye=".(isset($this->paye) ? $this->
db->escape($this->paye) : 0).
",";
2329 $sql .=
" remise_percent=".(isset($this->remise_percent) ? $this->
db->escape($this->remise_percent) :
"null").
",";
2330 $sql .=
" remise_absolue=".(isset($this->remise_absolue) ? $this->
db->escape($this->remise_absolue) :
"null").
",";
2331 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2332 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2333 $sql .=
" total_tva=".(isset($this->total_tva) ? $this->total_tva :
"null").
",";
2334 $sql .=
" localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 :
"null").
",";
2335 $sql .=
" localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 :
"null").
",";
2336 $sql .=
" total_ht=".(isset($this->total_ht) ? $this->total_ht :
"null").
",";
2337 $sql .=
" total_ttc=".(isset($this->total_ttc) ? $this->total_ttc :
"null").
",";
2338 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? $this->
db->escape($this->revenuestamp) :
"null").
",";
2339 $sql .=
" fk_statut=".(isset($this->statut) ? $this->
db->escape($this->statut) :
"null").
",";
2340 $sql .=
" fk_user_author=".(isset($this->user_author) ? $this->
db->escape($this->user_author) :
"null").
",";
2341 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? $this->
db->escape($this->fk_user_valid) :
"null").
",";
2342 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? $this->
db->escape($this->fk_facture_source) :
"null").
",";
2343 $sql .=
" fk_projet=".(isset($this->fk_project) ? $this->
db->escape($this->fk_project) :
"null").
",";
2344 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->
db->escape($this->cond_reglement_id) :
"null").
",";
2345 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->
db->escape($this->mode_reglement_id) :
"null").
",";
2346 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2347 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2348 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2349 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2350 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2351 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : $this->
db->escape($this->situation_cycle_ref)).
",";
2352 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : $this->
db->escape($this->situation_counter)).
",";
2353 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : $this->
db->escape($this->situation_final)).
",";
2354 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty)).
",";
2355 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2356 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) :
"null");
2357 $sql .=
" WHERE rowid=".((int) $this->
id);
2361 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2365 $this->errors[] =
"Error ".$this->db->lasterror();
2375 if (!$error && !$notrigger) {
2386 foreach ($this->errors as $errmsg) {
2387 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2388 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2390 $this->
db->rollback();
2393 $this->
db->commit();
2409 global $conf, $langs;
2411 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2412 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2417 $result = $remise->fetch($idremise);
2420 if ($remise->fk_facture) {
2421 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2422 $this->
db->rollback();
2427 $facligne->fk_facture = $this->id;
2428 $facligne->fk_remise_except = $remise->id;
2429 $facligne->desc = $remise->description;
2430 $facligne->vat_src_code = $remise->vat_src_code;
2431 $facligne->tva_tx = $remise->tva_tx;
2432 $facligne->subprice = -$remise->amount_ht;
2433 $facligne->fk_product = 0;
2435 $facligne->remise_percent = 0;
2436 $facligne->rang = -1;
2437 $facligne->info_bits = 2;
2439 if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
2440 $facligne->rang = 1;
2441 $linecount = count($this->lines);
2442 for ($ii = 1; $ii <= $linecount; $ii++) {
2448 if ($remise->fk_facture_source > 0) {
2450 $srcinvoice->fetch($remise->fk_facture_source);
2451 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2453 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2454 $facligne->pa_ht = $arraytmp[
'pa_total'];
2457 $facligne->total_ht = -$remise->amount_ht;
2458 $facligne->total_tva = -$remise->amount_tva;
2459 $facligne->total_ttc = -$remise->amount_ttc;
2461 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2462 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2463 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2464 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2466 $lineid = $facligne->insert();
2471 $result = $remise->link_to_invoice($lineid, 0);
2473 $this->error = $remise->error;
2474 $this->
db->rollback();
2478 $this->
db->commit();
2481 $this->error = $facligne->error;
2482 $this->
db->rollback();
2486 $this->error = $facligne->error;
2487 $this->
db->rollback();
2491 $this->
db->rollback();
2513 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2514 if (empty($ref_client)) {
2515 $sql .=
' SET ref_client = NULL';
2517 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2519 $sql .=
" WHERE rowid = ".((int) $this->
id);
2521 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2524 $this->errors[] = $this->
db->error();
2529 $this->ref_client = $ref_client;
2532 if (!$notrigger && empty($error)) {
2542 $this->ref_client = $ref_client;
2544 $this->
db->commit();
2547 foreach ($this->errors as $errmsg) {
2548 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2549 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2551 $this->
db->rollback();
2564 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2566 global $langs, $conf;
2567 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2571 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2584 if (!$error && !$notrigger) {
2598 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2612 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2613 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2614 $sql .=
' AND fk_facture_line IS NULL';
2619 $list_rowid_det = array();
2620 foreach ($this->lines as $key => $invoiceline) {
2621 $list_rowid_det[] = $invoiceline->id;
2625 if (count($list_rowid_det)) {
2626 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2627 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2628 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(join(
',', $list_rowid_det)).
')';
2630 if (!$this->
db->query($sql)) {
2631 $this->error = $this->
db->error().
" sql=".$sql;
2632 $this->errors[] = $this->error;
2633 $this->
db->rollback();
2640 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2641 $sql .=
' SET fk_invoice = NULL';
2642 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2644 if (!$this->
db->query($sql)) {
2645 $this->error = $this->
db->error().
" sql=".$sql;
2646 $this->errors[] = $this->error;
2647 $this->
db->rollback();
2651 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'projet_task_time';
2652 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2653 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2655 if (!$this->
db->query($sql)) {
2656 $this->error = $this->
db->error().
" sql=".$sql;
2657 $this->errors[] = $this->error;
2658 $this->
db->rollback();
2663 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
2664 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2665 $langs->load(
"agenda");
2667 $num = count($this->lines);
2668 for ($i = 0; $i < $num; $i++) {
2669 if ($this->lines[$i]->fk_product > 0) {
2671 $mouvP->origin = &$this;
2672 $mouvP->setOrigin($this->element, $this->
id);
2674 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2675 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2677 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2684 $main = MAIN_DB_PREFIX.
'facturedet';
2685 $ef = $main.
"_extrafields";
2686 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2688 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2691 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2700 if ($conf->facture->dir_output && !empty($this->
ref)) {
2701 $dir = $conf->facture->dir_output.
"/".$ref;
2702 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2703 if (file_exists($file)) {
2707 $langs->load(
"errors");
2708 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2709 $this->errors[] = $this->error;
2710 $this->
db->rollback();
2714 if (file_exists($dir)) {
2716 $langs->load(
"errors");
2717 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2718 $this->errors[] = $this->error;
2719 $this->
db->rollback();
2725 $this->
db->commit();
2728 $this->error = $this->
db->lasterror().
" sql=".$sql;
2729 $this->errors[] = $this->error;
2730 $this->
db->rollback();
2734 $this->error = $this->
db->lasterror().
" sql=".$sql;
2735 $this->errors[] = $this->error;
2736 $this->
db->rollback();
2740 $this->
db->rollback();
2757 public function set_paid($user, $close_code =
'', $close_note =
'')
2760 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2761 return $this->
setPaid($user, $close_code, $close_note);
2773 public function setPaid($user, $close_code =
'', $close_note =
'')
2777 if ($this->paye != 1) {
2782 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
2784 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2785 $sql .=
' fk_statut='.self::STATUS_CLOSED;
2790 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2793 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2795 $sql .=
', fk_user_closing = '.((int) $user->id);
2796 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
2797 $sql .=
" WHERE rowid = ".((int) $this->
id);
2809 $this->error = $this->
db->lasterror();
2813 $this->
db->commit();
2816 $this->
db->rollback();
2839 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
2857 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2858 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
2859 $sql .=
' date_closing=null,';
2860 $sql .=
' fk_user_closing=null';
2861 $sql .=
" WHERE rowid = ".((int) $this->
id);
2863 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
2874 $this->error = $this->
db->error();
2879 $this->
db->commit();
2882 $this->
db->rollback();
2904 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
2905 return $this->
setCanceled($user, $close_code, $close_note);
2918 public function setCanceled($user, $close_code =
'', $close_note =
'')
2920 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
2924 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2925 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
2927 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2930 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2932 $sql .=
" WHERE rowid = ".((int) $this->
id);
2938 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2939 $sql .=
' SET fk_facture = NULL';
2940 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
2947 $this->
db->rollback();
2952 $this->
db->commit();
2955 $this->error = $this->
db->error().
" sql=".$sql;
2956 $this->
db->rollback();
2960 $this->error = $this->
db->error().
" sql=".$sql;
2961 $this->
db->rollback();
2977 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
2979 global $conf, $langs, $mysoc;
2980 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2982 $productStatic =
null;
2983 $warehouseStatic =
null;
2984 if ($batch_rule > 0) {
2985 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2986 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
2987 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
2988 $productStatic =
new Product($this->
db);
2990 $productbatch =
new ProductBatch($this->
db);
2996 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3003 if ($this->statut != self::STATUS_DRAFT) {
3004 dol_syslog(get_class($this).
"::validate status is not draft. operation canceled.", LOG_WARNING);
3007 if (count($this->lines) <= 0) {
3008 $langs->load(
"errors");
3009 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3012 if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
3013 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
3014 $this->error =
'Permission denied';
3015 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
3018 if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
3020 if (!$last_of_type[0]) {
3021 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3027 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3028 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3029 foreach ($array_to_check as $key) {
3030 $keymin = strtolower($key);
3031 if (!property_exists($this->thirdparty, $keymin)) {
3034 $vallabel = $this->thirdparty->$keymin;
3036 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3038 if ($this->thirdparty->isACompany()) {
3040 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3041 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3042 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3043 $langs->load(
"errors");
3044 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3045 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3051 if ($key ==
'EMAIL') {
3053 if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
3054 $langs->load(
"errors");
3055 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3056 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3060 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3062 if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
3063 $langs->load(
"errors");
3064 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3065 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3074 $array_to_check = array(
'REF_CLIENT'=>
'RefCustomer');
3075 foreach ($array_to_check as $key => $val) {
3076 $keymin = strtolower($key);
3077 $vallabel = $this->$keymin;
3080 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3081 if (!$vallabel && !empty($conf->global->$keymandatory)) {
3082 $langs->load(
"errors");
3084 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val)),
null,
'errors');
3091 if ($this->
type == self::TYPE_REPLACEMENT) {
3093 if ($this->fk_facture_source <= 0) {
3094 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3095 $this->
db->rollback();
3101 $result = $facreplaced->fetch($this->fk_facture_source);
3103 $this->error = $langs->trans(
"ErrorBadInvoice");
3104 $this->
db->rollback();
3109 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3110 if ($idreplacement && $idreplacement != $this->
id) {
3111 $facreplacement =
new Facture($this->
db);
3112 $facreplacement->fetch($idreplacement);
3113 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3114 $this->
db->rollback();
3118 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3120 $this->error = $facreplaced->error;
3121 $this->
db->rollback();
3127 if ($force_number) {
3128 $num = $force_number;
3129 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3130 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3145 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3146 $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).
"'";
3147 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3148 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3149 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3151 $sql .=
" WHERE rowid = ".((int) $this->
id);
3153 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3161 if (!$error && (preg_match(
'/^[\(]?PROV/i', $this->
ref))) {
3167 $result = $this->thirdparty->set_as_client();
3170 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
3171 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3172 $langs->load(
"agenda");
3175 $cpt = count($this->lines);
3176 for ($i = 0; $i < $cpt; $i++) {
3177 if ($this->lines[$i]->fk_product > 0) {
3179 $mouvP->origin = &$this;
3180 $mouvP->setOrigin($this->element, $this->
id);
3182 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3183 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3186 $this->error = $mouvP->error;
3189 $is_batch_line =
false;
3190 if ($batch_rule > 0) {
3191 $productStatic->fetch($this->lines[$i]->fk_product);
3192 if ($productStatic->hasbatch()) {
3193 $is_batch_line =
true;
3194 $product_qty_remain = $this->lines[$i]->qty;
3200 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3201 $sortorder =
'ASC,ASC,ASC,ASC';
3204 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ?
null : 0), $sortfield, $sortorder);
3205 if (!is_array($resBatchList)) {
3207 $this->error = $this->
db->lasterror();
3211 $batchList = $resBatchList;
3212 if (empty($batchList)) {
3214 $langs->load(
'errors');
3215 $warehouseStatic->fetch($idwarehouse);
3216 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3217 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3220 foreach ($batchList as $batch) {
3221 if ($batch->qty <= 0) {
3226 if ($batch->qty >= $product_qty_remain) {
3227 $product_batch_qty = $product_qty_remain;
3230 $product_batch_qty = $batch->qty;
3232 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3235 $this->error = $mouvP->error;
3239 $product_qty_remain -= $product_batch_qty;
3241 if ($product_qty_remain <= 0) {
3246 if (!$error && $product_qty_remain > 0) {
3247 if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
3249 $batch = $batchList[0];
3250 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3253 $this->error = $mouvP->error;
3257 $langs->load(
'errors');
3258 $warehouseStatic->fetch($idwarehouse);
3259 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3260 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3267 if (!$is_batch_line) {
3268 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3271 $this->error = $mouvP->error;
3284 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3285 $invoice_situation =
new Facture($this->
db);
3286 $result = $invoice_situation->fetch($this->fk_facture_source);
3287 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3288 $invoice_situation->situation_final = 0;
3290 $result = $invoice_situation->setFinal($user, 1);
3293 $this->error = $invoice_situation->error;
3294 $this->errors = $invoice_situation->errors;
3300 if (!$error && !$notrigger) {
3310 $this->oldref = $this->ref;
3313 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3315 $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).
"'";
3316 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->
db->escape($this->
ref).
"' and entity = ".$conf->entity;
3320 $this->error = $this->
db->lasterror();
3326 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3327 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3328 if (!$error && file_exists($dirsource)) {
3329 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3331 if (@rename($dirsource, $dirdest)) {
3334 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3335 foreach ($listoffiles as $fileentry) {
3336 $dirsource = $fileentry[
'name'];
3337 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3338 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3339 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3340 @rename($dirsource, $dirdest);
3359 $this->brouillon = 0;
3360 $this->date_validation = $now;
3363 if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3365 $nboflines = count($this->lines);
3366 while (($i < $nboflines) && $final) {
3367 $final = ($this->lines[$i]->situation_percent == 100);
3371 if (empty($final)) {
3372 $this->situation_final = 0;
3374 $this->situation_final = 1;
3385 $this->
db->commit();
3388 $this->
db->rollback();
3401 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3402 $is_last = $next_invoice->is_last_in_cycle();
3404 if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
3405 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3409 $next_invoice->brouillon = 1;
3411 foreach ($next_invoice->lines as $line) {
3412 $result = $next_invoice->updateline(
3417 $line->remise_percent,
3421 $line->localtax1_tx,
3422 $line->localtax2_tx,
3425 $line->product_type,
3426 $line->fk_parent_line,
3428 $line->fk_fournprice,
3431 $line->special_code,
3432 $line->array_options,
3433 $line->situation_percent,
3438 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3459 global $conf, $langs;
3463 if ($this->statut == self::STATUS_DRAFT) {
3464 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3472 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3473 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3474 $sql .=
" WHERE rowid = ".((int) $this->
id);
3476 $result = $this->
db->query($sql);
3479 $this->oldcopy = clone $this;
3483 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 &&
isModEnabled(
'stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3484 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3485 $langs->load(
"agenda");
3487 $num = count($this->lines);
3488 for ($i = 0; $i < $num; $i++) {
3489 if ($this->lines[$i]->fk_product > 0) {
3491 $mouvP->origin = &$this;
3492 $mouvP->setOrigin($this->element, $this->
id);
3494 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3495 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3497 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3504 $old_statut = $this->statut;
3505 $this->brouillon = 1;
3510 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3513 $this->statut = $old_statut;
3514 $this->status = $old_statut;
3515 $this->brouillon = 0;
3519 $this->
db->rollback();
3524 $this->
db->commit();
3527 $this->
db->rollback();
3531 $this->error = $this->
db->error();
3532 $this->
db->rollback();
3587 $remise_percent = 0,
3592 $fk_remise_except =
'',
3593 $price_base_type =
'HT',
3600 $fk_parent_line = 0,
3601 $fk_fournprice =
null,
3605 $situation_percent = 100,
3610 $noupdateafterinsertline = 0
3614 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3618 global $mysoc, $conf, $langs;
3620 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);
3622 if ($this->statut == self::STATUS_DRAFT) {
3623 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3626 if (empty($remise_percent)) {
3627 $remise_percent = 0;
3632 if (empty($info_bits)) {
3638 if (empty($ventil)) {
3641 if (empty($txtva)) {
3644 if (empty($txlocaltax1)) {
3647 if (empty($txlocaltax2)) {
3650 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3651 $fk_parent_line = 0;
3653 if (empty($fk_prev_id)) {
3654 $fk_prev_id =
'null';
3656 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3657 $situation_percent = 100;
3659 if (empty($ref_ext)) {
3663 $remise_percent =
price2num($remise_percent);
3666 $pu_ht_devise =
price2num($pu_ht_devise);
3669 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3675 if ($price_base_type ==
'HT') {
3686 if ($date_start && $date_end && $date_start > $date_end) {
3687 $langs->load(
"errors");
3688 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3694 $product_type = $type;
3695 if (!empty($fk_product) && $fk_product > 0) {
3697 $result = $product->fetch($fk_product);
3698 $product_type = $product->type;
3700 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3701 $langs->load(
"errors");
3702 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3703 $this->
db->rollback();
3713 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3714 $vat_src_code = $reg[1];
3715 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3723 $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);
3725 $total_ht = $tabprice[0];
3726 $total_tva = $tabprice[1];
3727 $total_ttc = $tabprice[2];
3728 $total_localtax1 = $tabprice[9];
3729 $total_localtax2 = $tabprice[10];
3730 $pu_ht = $tabprice[3];
3733 $multicurrency_total_ht = $tabprice[16];
3734 $multicurrency_total_tva = $tabprice[17];
3735 $multicurrency_total_ttc = $tabprice[18];
3736 $pu_ht_devise = $tabprice[19];
3740 if ($ranktouse == -1) {
3741 $rangmax = $this->
line_max($fk_parent_line);
3742 $ranktouse = $rangmax + 1;
3748 $this->line->context = $this->context;
3750 $this->line->fk_facture = $this->id;
3751 $this->line->label = $label;
3752 $this->line->desc = $desc;
3753 $this->line->ref_ext = $ref_ext;
3755 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty);
3756 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
3758 $this->line->vat_src_code = $vat_src_code;
3759 $this->line->tva_tx = $txtva;
3760 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3761 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3762 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
3763 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
3765 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
3766 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
3767 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
3768 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
3769 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
3771 $this->line->fk_product = $fk_product;
3772 $this->line->product_type = $product_type;
3773 $this->line->remise_percent = $remise_percent;
3774 $this->line->date_start = $date_start;
3775 $this->line->date_end = $date_end;
3776 $this->line->ventil = $ventil;
3777 $this->line->rang = $ranktouse;
3778 $this->line->info_bits = $info_bits;
3779 $this->line->fk_remise_except = $fk_remise_except;
3781 $this->line->special_code = $special_code;
3782 $this->line->fk_parent_line = $fk_parent_line;
3783 $this->line->origin = $origin;
3784 $this->line->origin_id = $origin_id;
3785 $this->line->situation_percent = $situation_percent;
3786 $this->line->fk_prev_id = $fk_prev_id;
3787 $this->line->fk_unit = $fk_unit;
3790 $this->line->fk_fournprice = $fk_fournprice;
3791 $this->line->pa_ht = $pa_ht;
3794 $this->line->fk_multicurrency = $this->fk_multicurrency;
3795 $this->line->multicurrency_code = $this->multicurrency_code;
3796 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
3798 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
3799 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
3800 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
3802 if (is_array($array_options) && count($array_options) > 0) {
3803 $this->line->array_options = $array_options;
3806 $result = $this->line->insert();
3809 if (!empty($fk_parent_line)) {
3811 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
3812 $linecount = count($this->lines);
3813 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
3819 if (empty($noupdateafterinsertline)) {
3824 $this->
db->commit();
3825 return $this->line->id;
3827 $this->error = $this->
db->lasterror();
3828 $this->
db->rollback();
3832 $this->error = $this->line->error;
3833 $this->errors = $this->line->errors;
3834 $this->
db->rollback();
3838 $this->errors[]=
'status of invoice must be Draft to allow use of ->addline()';
3839 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3875 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)
3877 global $conf, $user;
3880 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3883 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3885 global $mysoc, $langs;
3887 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);
3889 if ($this->statut == self::STATUS_DRAFT) {
3892 if (!$this->error) {
3893 $this->error = $langs->trans(
'invoiceLineProgressError');
3899 if ($date_start && $date_end && $date_start > $date_end) {
3900 $langs->load(
"errors");
3901 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3911 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3912 $fk_parent_line = 0;
3914 if (empty($special_code) || $special_code == 3) {
3917 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3918 $situation_percent = 100;
3920 if (empty($ref_ext)) {
3924 $remise_percent =
price2num($remise_percent);
3927 $pu_ht_devise =
price2num($pu_ht_devise);
3929 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3949 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3950 $vat_src_code = $reg[1];
3951 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3954 $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);
3956 $total_ht = $tabprice[0];
3957 $total_tva = $tabprice[1];
3958 $total_ttc = $tabprice[2];
3959 $total_localtax1 = $tabprice[9];
3960 $total_localtax2 = $tabprice[10];
3961 $pu_ht = $tabprice[3];
3962 $pu_tva = $tabprice[4];
3963 $pu_ttc = $tabprice[5];
3966 $multicurrency_total_ht = $tabprice[16];
3967 $multicurrency_total_tva = $tabprice[17];
3968 $multicurrency_total_ttc = $tabprice[18];
3969 $pu_ht_devise = $tabprice[19];
3974 if ($remise_percent > 0) {
3975 $remise = round(($pu * $remise_percent / 100), 2);
3976 $price = ($pu - $remise);
3982 $line->fetch($rowid);
3983 $line->fetch_optionals();
3985 if (!empty($line->fk_product)) {
3987 $result = $product->fetch($line->fk_product);
3988 $product_type = $product->type;
3990 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3991 $langs->load(
"errors");
3992 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3993 $this->
db->rollback();
3998 $staticline = clone $line;
4000 $line->oldline = $staticline;
4001 $this->line = $line;
4002 $this->line->context = $this->context;
4003 $this->line->rang = $rang;
4006 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4007 $rangmax = $this->
line_max($fk_parent_line);
4008 $this->line->rang = $rangmax + 1;
4011 $this->line->id = $rowid;
4012 $this->line->rowid = $rowid;
4013 $this->line->label = $label;
4014 $this->line->desc = $desc;
4015 $this->line->ref_ext = $ref_ext;
4016 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty);
4018 $this->line->vat_src_code = $vat_src_code;
4019 $this->line->tva_tx = $txtva;
4020 $this->line->localtax1_tx = $txlocaltax1;
4021 $this->line->localtax2_tx = $txlocaltax2;
4022 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
4023 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
4025 $this->line->remise_percent = $remise_percent;
4026 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht);
4027 $this->line->date_start = $date_start;
4028 $this->line->date_end = $date_end;
4029 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht);
4030 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
4031 $this->line->total_localtax1 = $total_localtax1;
4032 $this->line->total_localtax2 = $total_localtax2;
4033 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
4034 $this->line->info_bits = $info_bits;
4035 $this->line->special_code = $special_code;
4036 $this->line->product_type = $type;
4037 $this->line->fk_parent_line = $fk_parent_line;
4038 $this->line->skip_update_total = $skip_update_total;
4039 $this->line->situation_percent = $situation_percent;
4040 $this->line->fk_unit = $fk_unit;
4042 $this->line->fk_fournprice = $fk_fournprice;
4043 $this->line->pa_ht = $pa_ht;
4046 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise);
4047 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht);
4048 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
4049 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4051 if (is_array($array_options) && count($array_options) > 0) {
4053 foreach ($array_options as $key => $value) {
4054 $this->line->array_options[$key] = $array_options[$key];
4058 $result = $this->line->update($user, $notrigger);
4061 if (!empty($fk_parent_line)) {
4067 $this->
db->commit();
4070 $this->error = $this->line->error;
4071 $this->
db->rollback();
4075 $this->error =
"Invoice statut makes operation forbidden";
4089 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4090 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4091 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4093 $result = $this->
db->query($sql);
4095 $this->error = $this->
db->error();
4099 $obj = $this->
db->fetch_object($result);
4101 if ($obj ===
null) {
4104 return $situation_percent < $obj->situation_percent;
4120 global $mysoc, $user;
4123 if (($line->info_bits & 2) == 2) {
4127 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4130 if ($percent > 100) {
4133 $line->situation_percent = $percent;
4134 $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);
4135 $line->total_ht = $tabprice[0];
4136 $line->total_tva = $tabprice[1];
4137 $line->total_ttc = $tabprice[2];
4138 $line->total_localtax1 = $tabprice[9];
4139 $line->total_localtax2 = $tabprice[10];
4140 $line->multicurrency_total_ht = $tabprice[16];
4141 $line->multicurrency_total_tva = $tabprice[17];
4142 $line->multicurrency_total_ttc = $tabprice[18];
4143 $line->update($user);
4146 if ($update_price) {
4161 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4163 if ($this->statut != self::STATUS_DRAFT) {
4164 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4171 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
4172 $sql .=
' SET fk_facture_line = NULL';
4173 $sql .=
' WHERE fk_facture_line = '.((int) $rowid);
4175 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
4176 $result = $this->
db->query($sql);
4178 $this->error = $this->
db->error();
4179 $this->
db->rollback();
4185 $line->context = $this->context;
4188 $result = $line->fetch($rowid);
4189 if (!($result > 0)) {
4193 if ($line->delete($user) > 0) {
4197 $this->
db->commit();
4200 $this->
db->rollback();
4201 $this->error = $this->
db->lasterror();
4205 $this->
db->rollback();
4206 $this->error = $line->error;
4225 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4226 return $this->
setDiscount($user, $remise, $notrigger);
4240 if (empty($remise)) {
4244 if ($user->rights->facture->creer) {
4251 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4252 $sql .=
' SET remise_percent = '.((float) $remise);
4253 $sql .=
" WHERE rowid = ".((int) $this->
id);
4254 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4259 $this->errors[] = $this->
db->error();
4263 if (!$notrigger && empty($error)) {
4273 $this->remise_percent = $remise;
4276 $this->
db->commit();
4279 foreach ($this->errors as $errmsg) {
4280 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4281 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4283 $this->
db->rollback();
4302 if (empty($remise)) {
4306 if ($user->rights->facture->creer) {
4313 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4314 $sql .=
' SET remise_absolue = '.((float) $remise);
4315 $sql .=
" WHERE rowid = ".((int) $this->
id);
4316 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4321 $this->errors[] = $this->
db->error();
4326 $this->oldcopy = clone $this;
4327 $this->remise_absolue = $remise;
4331 if (!$notrigger && empty($error)) {
4341 $this->
db->commit();
4344 foreach ($this->errors as $errmsg) {
4345 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4346 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4348 $this->
db->rollback();
4364 global $conf, $langs;
4366 if ($this->module_source ==
'takepos') {
4367 $langs->load(
'cashdesk');
4369 $moduleName =
'takepos';
4370 $moduleSourceName =
'Takepos';
4371 $addonConstName =
'TAKEPOS_REF_ADDON';
4374 if (empty($conf->global->TAKEPOS_REF_ADDON)) {
4375 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4378 $addon = $conf->global->TAKEPOS_REF_ADDON;
4380 $langs->load(
'bills');
4382 $moduleName =
'facture';
4383 $moduleSourceName =
'Invoice';
4384 $addonConstName =
'FACTURE_ADDON';
4387 if (empty($conf->global->FACTURE_ADDON)) {
4388 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4389 } elseif ($conf->global->FACTURE_ADDON ==
'terre') {
4390 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4391 } elseif ($conf->global->FACTURE_ADDON ==
'mercure') {
4392 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4395 $addon = $conf->global->FACTURE_ADDON;
4398 if (!empty($addon)) {
4399 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = ".$conf->global->FACTURE_ADDON.
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4403 $file = $addon.
'.php';
4404 $classname = $addon;
4408 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4409 foreach ($dirmodels as $reldir) {
4410 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4413 if (is_file($dir.$file) && is_readable($dir.$file)) {
4414 $mybool |= include_once $dir.$file;
4420 $file = $addon.
'/'.$addon.
'.modules.php';
4421 $classname =
'mod_'.$moduleName.
'_'.$addon;
4422 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4424 foreach ($conf->file->dol_document_root as $dirroot) {
4425 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4428 if (is_file($dir.$file) && is_readable($dir.$file)) {
4429 $mybool |= include_once $dir.$file;
4439 $obj =
new $classname();
4441 $numref = $obj->getNextValue($soc, $this, $mode);
4448 if ($mode !=
'last' && !$numref) {
4449 $this->error = $obj->error;
4455 $langs->load(
'errors');
4456 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4469 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4470 $sql .=
' date_closing as dateclosing,';
4471 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4472 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4473 $sql .=
' WHERE c.rowid = '.((int) $id);
4475 $result = $this->
db->query($sql);
4477 if ($this->
db->num_rows($result)) {
4478 $obj = $this->
db->fetch_object($result);
4479 $this->
id = $obj->rowid;
4480 if ($obj->fk_user_author) {
4481 $cuser =
new User($this->
db);
4482 $cuser->fetch($obj->fk_user_author);
4483 $this->user_creation = $cuser;
4485 if ($obj->fk_user_valid) {
4486 $vuser =
new User($this->
db);
4487 $vuser->fetch($obj->fk_user_valid);
4488 $this->user_validation = $vuser;
4490 if ($obj->fk_user_closing) {
4491 $cluser =
new User($this->
db);
4492 $cluser->fetch($obj->fk_user_closing);
4493 $this->user_closing = $cluser;
4496 $this->date_creation = $this->
db->jdate($obj->datec);
4497 $this->date_modification = $this->
db->jdate($obj->datem);
4498 $this->date_validation = $this->
db->jdate($obj->datev);
4499 $this->date_closing = $this->
db->jdate($obj->dateclosing);
4501 $this->
db->free($result);
4522 public function liste_array($shortlist = 0, $draft = 0, $excluser =
'', $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4525 global $conf, $user;
4529 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4530 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4531 if (empty($user->rights->societe->client->voir) && !$socid) {
4532 $sql .=
", sc.fk_soc, sc.fk_user";
4534 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4535 if (empty($user->rights->societe->client->voir) && !$socid) {
4536 $sql .=
", ".MAIN_DB_PREFIX.
"societe_commerciaux as sc";
4538 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4539 $sql .=
" AND f.fk_soc = s.rowid";
4540 if (empty($user->rights->societe->client->voir) && !$socid) {
4541 $sql .=
" AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4544 $sql .=
" AND s.rowid = ".((int) $socid);
4547 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4549 if (is_object($excluser)) {
4550 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4552 $sql .= $this->
db->order($sortfield, $sortorder);
4553 $sql .= $this->
db->plimit($limit, $offset);
4555 $result = $this->
db->query($sql);
4557 $numc = $this->
db->num_rows($result);
4560 while ($i < $numc) {
4561 $obj = $this->
db->fetch_object($result);
4563 if ($shortlist == 1) {
4564 $ga[$obj->fid] = $obj->ref;
4565 } elseif ($shortlist == 2) {
4566 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4568 $ga[$i][
'id'] = $obj->fid;
4569 $ga[$i][
'ref'] = $obj->ref;
4570 $ga[$i][
'name'] = $obj->name;
4599 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4600 $sql .=
" ff.rowid as rowidnext";
4602 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4603 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4604 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4605 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4606 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4607 $sql .=
" AND f.paye = 0";
4608 $sql .=
" AND pf.fk_paiement IS NULL";
4609 $sql .=
" AND ff.fk_statut IS NULL";
4611 $sql .=
" AND f.fk_soc = ".((int) $socid);
4614 $sql .=
" ORDER BY f.ref";
4616 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4619 while ($obj = $this->
db->fetch_object(
$resql)) {
4620 $return[$obj->rowid] = array(
4621 'id' => $obj->rowid,
4623 'status' => $obj->status,
4624 'paid' => $obj->paid,
4631 $this->error = $this->
db->error();
4654 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
4655 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4656 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4657 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4658 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4659 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4663 $sql .=
" AND ff.type IS NULL";
4664 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4666 if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4668 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4669 $sql .=
'(SELECT MAX(fs.rowid)';
4670 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4671 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4672 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4673 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4675 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4677 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4680 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4684 $sql .=
" AND f.fk_soc = ".((int) $socid);
4686 $sql .=
" ORDER BY f.ref";
4688 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4691 while ($obj = $this->
db->fetch_object(
$resql)) {
4693 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4696 if ($obj->fk_statut == self::STATUS_CLOSED) {
4701 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4702 $return[$obj->rowid] = array(
'ref'=>$obj->ref,
'status'=>$obj->fk_statut,
'type'=>$obj->type,
'paye'=>$obj->paye,
'paymentornot'=>$paymentornot);
4708 $this->error = $this->
db->error();
4724 global $conf, $langs;
4728 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
4729 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4730 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4731 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4732 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4735 $sql .= $clause.
" f.paye=0";
4736 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4737 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
4739 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
4744 $langs->load(
"bills");
4748 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4749 $response->label = $langs->trans(
"CustomerBillsUnpaid");
4750 $response->labelShort = $langs->trans(
"Unpaid");
4751 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4754 $generic_facture =
new Facture($this->
db);
4756 while ($obj = $this->
db->fetch_object(
$resql)) {
4757 $generic_facture->date_lim_reglement = $this->
db->jdate($obj->datefin);
4758 $generic_facture->statut = $obj->fk_statut;
4760 $response->nbtodo++;
4761 $response->total += $obj->total_ht;
4763 if ($generic_facture->hasDelay()) {
4764 $response->nbtodolate++;
4765 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4773 $this->error = $this->
db->error();
4812 global $conf, $langs, $user;
4816 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
4821 $sql =
"SELECT rowid";
4822 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
4823 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
4824 $sql .= $this->
db->plimit(100);
4828 $num_prods = $this->
db->num_rows(
$resql);
4830 while ($i < $num_prods) {
4832 $row = $this->
db->fetch_row(
$resql);
4833 $prodids[$i] = $row[0];
4837 if (empty($num_prods)) {
4844 $this->
ref =
'SPECIMEN';
4845 $this->specimen = 1;
4847 $this->date = $nownotime;
4848 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4849 $this->cond_reglement_id = 1;
4850 $this->cond_reglement_code =
'RECEP';
4852 $this->mode_reglement_id = 0;
4853 $this->mode_reglement_code =
'';
4855 $this->note_public =
'This is a comment (public)';
4856 $this->note_private =
'This is a comment (private)';
4857 $this->note =
'This is a comment (private)';
4859 $this->fk_user_author = $user->id;
4861 $this->multicurrency_tx = 1;
4862 $this->multicurrency_code = $conf->currency;
4864 $this->fk_incoterms = 0;
4865 $this->location_incoterms =
'';
4867 if (empty($option) || $option !=
'nolines') {
4871 while ($xnbp < $nbp) {
4873 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
4875 $line->subprice = 100;
4876 $line->tva_tx = 19.6;
4877 $line->localtax1_tx = 0;
4878 $line->localtax2_tx = 0;
4879 $line->remise_percent = 0;
4881 $prodid = mt_rand(1, $num_prods);
4882 $line->fk_product = $prodids[$prodid];
4884 $line->total_ht = -100;
4885 $line->total_ttc = -119.6;
4886 $line->total_tva = -19.6;
4887 $line->multicurrency_total_ht = -200;
4888 $line->multicurrency_total_ttc = -239.2;
4889 $line->multicurrency_total_tva = -39.2;
4890 } elseif ($xnbp == 2) {
4891 $line->subprice = -100;
4892 $line->total_ht = -100;
4893 $line->total_ttc = -119.6;
4894 $line->total_tva = -19.6;
4895 $line->remise_percent = 0;
4896 $line->multicurrency_total_ht = -200;
4897 $line->multicurrency_total_ttc = -239.2;
4898 $line->multicurrency_total_tva = -39.2;
4899 } elseif ($xnbp == 3) {
4900 $prodid = mt_rand(1, $num_prods);
4901 $line->fk_product = $prodids[$prodid];
4902 $line->total_ht = 50;
4903 $line->total_ttc = 59.8;
4904 $line->total_tva = 9.8;
4905 $line->multicurrency_total_ht = 100;
4906 $line->multicurrency_total_ttc = 119.6;
4907 $line->multicurrency_total_tva = 19.6;
4908 $line->remise_percent = 50;
4911 $prodid = mt_rand(1, $num_prods);
4912 $line->fk_product = $prodids[$prodid];
4913 $line->total_ht = 100;
4914 $line->total_ttc = 119.6;
4915 $line->total_tva = 19.6;
4916 $line->multicurrency_total_ht = 200;
4917 $line->multicurrency_total_ttc = 239.2;
4918 $line->multicurrency_total_tva = 39.2;
4919 $line->remise_percent = 0;
4922 $this->lines[$xnbp] = $line;
4925 $this->total_ht += $line->total_ht;
4926 $this->total_tva += $line->total_tva;
4927 $this->total_ttc += $line->total_ttc;
4929 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4930 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4931 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4935 $this->revenuestamp = 0;
4939 $line->desc = $langs->trans(
"Description").
" (offered line)";
4941 $line->subprice = 100;
4942 $line->tva_tx = 19.6;
4943 $line->localtax1_tx = 0;
4944 $line->localtax2_tx = 0;
4945 $line->remise_percent = 100;
4946 $line->total_ht = 0;
4947 $line->total_ttc = 0;
4948 $line->total_tva = 0;
4949 $line->multicurrency_total_ht = 0;
4950 $line->multicurrency_total_ttc = 0;
4951 $line->multicurrency_total_tva = 0;
4952 $prodid = mt_rand(1, $num_prods);
4953 $line->fk_product = $prodids[$prodid];
4955 $this->lines[$xnbp] = $line;
4969 global $conf, $user;
4971 $this->nb = array();
4975 $sql =
"SELECT count(f.rowid) as nb";
4976 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4977 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
4978 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4979 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
4980 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4983 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
4987 while ($obj = $this->
db->fetch_object(
$resql)) {
4988 $this->nb[
"invoices"] = $obj->nb;
4994 $this->error = $this->
db->error();
5020 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5022 global $conf, $langs;
5024 $outputlangs->loadLangs(array(
"bills",
"products"));
5028 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5030 if (!empty($this->model_pdf)) {
5031 $modele = $this->model_pdf;
5032 } elseif (!empty($this->modelpdf)) {
5033 $modele = $this->modelpdf;
5034 } elseif (!empty($conf->global->$thisTypeConfName)) {
5035 $modele = $conf->global->$thisTypeConfName;
5036 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
5037 $modele = $conf->global->FACTURE_ADDON_PDF;
5041 $modelpath =
"core/modules/facture/doc/";
5043 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5053 $sql =
'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.
'facture as f';
5054 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5057 if ($this->
db->num_rows(
$resql) > 0) {
5058 $res = $this->
db->fetch_array(
$resql);
5059 $ref = $res[
'max(situation_cycle_ref)'];
5067 $this->error = $this->
db->lasterror();
5068 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5082 return ($this->situation_counter == 1);
5096 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5097 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5098 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5099 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5103 while ($row = $this->
db->fetch_object(
$resql)) {
5106 $situation->fetch($id);
5107 $res[] = $situation;
5110 $this->error = $this->
db->error();
5111 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5131 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5136 $this->errors[] = $this->
db->error();
5140 if (!$notrigger && empty($error)) {
5150 $this->
db->commit();
5153 foreach ($this->errors as $errmsg) {
5154 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5155 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5157 $this->
db->rollback();
5173 if (!empty($this->situation_cycle_ref)) {
5175 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5176 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5177 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5181 $res = $this->
db->fetch_array(
$resql);
5182 $last = $res[
'max(situation_counter)'];
5183 return ($last == $this->situation_counter);
5185 $this->error = $this->
db->lasterror();
5186 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5244 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5245 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5247 $totalpaid = floatval($totalpaid);
5249 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5250 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5252 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5275 $displayWarranty =
false;
5276 if (!empty($this->retained_warranty)) {
5277 $displayWarranty =
true;
5281 $displayWarranty =
false;
5282 if (!empty($this->situation_final)) {
5283 $displayWarranty =
true;
5286 $displayWarranty =
true;
5288 foreach ($this->lines as $i => $line) {
5289 if ($line->product_type < 2 && $line->situation_percent < 100) {
5290 $displayWarranty =
false;
5298 return $displayWarranty;
5308 if (empty($this->retained_warranty)) {
5312 $retainedWarrantyAmount = 0;
5316 $displayWarranty =
true;
5318 if (!empty($this->lines)) {
5319 foreach ($this->lines as $i => $line) {
5320 if ($line->product_type < 2 && $line->situation_percent < 100) {
5321 $displayWarranty =
false;
5327 if ($displayWarranty && !empty($this->situation_final)) {
5329 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5332 foreach ($TPreviousIncoice as &$fac) {
5333 $total2BillWT += $fac->total_ttc;
5335 $total2BillWT += $this->total_ttc;
5337 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5343 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5346 if ($rounding < 0) {
5347 $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5350 if ($rounding > 0) {
5351 return round($retainedWarrantyAmount, $rounding);
5354 return $retainedWarrantyAmount;
5365 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5367 if ($this->statut >= 0) {
5368 $fieldname =
'retained_warranty';
5369 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5370 $sql .=
" SET ".$fieldname.
" = ".((
float) $value);
5371 $sql .=
' WHERE rowid='.((int) $this->
id);
5373 if ($this->
db->query($sql)) {
5374 $this->retained_warranty = floatval($value);
5377 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5378 $this->error = $this->
db->error();
5382 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5383 $this->error =
'Status of the object is incompatible '.$this->statut;
5398 if (!$timestamp && $dateYmd) {
5399 $timestamp = $this->
db->jdate($dateYmd);
5403 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5404 if ($this->statut >= 0) {
5405 $fieldname =
'retained_warranty_date_limit';
5406 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5407 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5408 $sql .=
' WHERE rowid = '.((int) $this->
id);
5410 if ($this->
db->query($sql)) {
5411 $this->retained_warranty_date_limit = $timestamp;
5414 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5415 $this->error = $this->
db->error();
5419 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5420 $this->error =
'Status of the object is incompatible '.$this->statut;
5438 global $conf, $langs, $user;
5444 $errorsMsg = array();
5446 $langs->load(
"bills");
5449 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5459 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5460 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5461 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5472 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5473 if (!empty($paymentmode) && $paymentmode !=
'all') {
5474 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5476 $sql .=
" WHERE f.paye = 0";
5477 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5478 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5479 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
5480 if (!empty($paymentmode) && $paymentmode !=
'all') {
5481 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5484 $sql .= $this->
db->order(
"date_lim_reglement",
"ASC");
5489 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5490 if (!empty($paymentmode) && $paymentmode !=
'all') {
5491 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5493 $this->output .=
'<br>';
5496 while ($obj = $this->
db->fetch_object(
$resql)) {
5499 $res = $tmpinvoice->fetch($obj->id);
5501 $tmpinvoice->fetch_thirdparty();
5503 $outputlangs =
new Translate(
'', $conf);
5504 if ($tmpinvoice->thirdparty->default_lang) {
5505 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5506 $outputlangs->loadLangs(array(
"main",
"bills"));
5508 $outputlangs = $langs;
5512 $arraymessage = $formmail->getEMailTemplate($this->
db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5513 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5514 $langs->load(
"errors");
5515 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5528 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5531 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5537 if ($forcerecipient) {
5538 $to = array($forcerecipient);
5540 $res = $tmpinvoice->fetch_thirdparty();
5541 $recipient = $tmpinvoice->thirdparty;
5543 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
5544 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5545 foreach ($tmparraycontact as $data_email) {
5546 if (!empty($data_email[
'email'])) {
5547 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
5551 if (empty($to) && !empty($recipient->email)) {
5552 $to[] = $recipient->email;
5555 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
5559 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5566 if (!empty($arraymessage->email_from)) {
5567 $from = $arraymessage->email_from;
5570 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5574 if (!$error && !empty($to)) {
5577 $to = implode(
',', $to);
5578 if (!empty($arraymessage->email_to)) {
5579 $to = $to.
','.$arraymessage->email_to;
5583 $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
5585 $trackid =
'inv'.$tmpinvoice->id;
5586 $sendcontext =
'standard';
5589 if (!empty($arraymessage->email_tocc)) {
5590 $email_tocc = $arraymessage->email_tocc;
5594 if (!empty($arraymessage->email_tobcc)) {
5595 $email_tobcc = $arraymessage->email_tobcc;
5599 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5602 if ($cMailFile->sendfile()) {
5606 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5611 $actioncomm->type_code =
'AC_OTH_AUTO';
5612 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5613 $actioncomm->contact_id = 0;
5615 $actioncomm->code =
'AC_EMAIL';
5616 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK';
5617 $actioncomm->note_private = $sendContent;
5618 $actioncomm->fk_project = $tmpinvoice->fk_project;
5619 $actioncomm->datep =
dol_now();
5620 $actioncomm->datef = $actioncomm->datep;
5621 $actioncomm->percentage = -1;
5622 $actioncomm->authorid = $user->id;
5623 $actioncomm->userownerid = $user->id;
5625 $actioncomm->email_msgid = $cMailFile->msgid;
5626 $actioncomm->email_from = $from;
5627 $actioncomm->email_sender =
'';
5628 $actioncomm->email_to = $to;
5632 $actioncomm->errors_to = $errors_to;
5634 $actioncomm->elementtype =
'invoice';
5635 $actioncomm->fk_element = $tmpinvoice->id;
5639 $actioncomm->create($user);
5641 $errormesg = $cMailFile->error.
' : '.$to;
5645 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5650 $actioncomm->type_code =
'AC_OTH_AUTO';
5651 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5652 $actioncomm->contact_id = 0;
5654 $actioncomm->code =
'AC_EMAIL';
5655 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5656 $actioncomm->note_private = $errormesg;
5657 $actioncomm->fk_project = $tmpinvoice->fk_project;
5658 $actioncomm->datep =
dol_now();
5659 $actioncomm->datef = $actioncomm->datep;
5660 $actioncomm->percentage = -1;
5661 $actioncomm->authorid = $user->id;
5662 $actioncomm->userownerid = $user->id;
5664 $actioncomm->email_msgid = $cMailFile->msgid;
5665 $actioncomm->email_from = $from;
5666 $actioncomm->email_sender =
'';
5667 $actioncomm->email_to = $to;
5671 $actioncomm->errors_to = $errors_to;
5675 $actioncomm->create($user);
5678 $this->
db->commit();
5682 $errorsMsg[] = $errormesg;
5685 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
5695 $this->output .=
'Nb of emails sent : '.$nbMailSend;
5698 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg)) ? join(
', ', $errorsMsg) : $error;
5712 $sql =
"SELECT datef";
5713 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
5714 $sql .=
" WHERE type = " . (int) $this->
type ;
5715 $sql .=
" AND date_valid IS NOT NULL";
5716 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
5717 $sql .=
" ORDER BY datef DESC LIMIT 1";
5719 $result = $this->
db->query($sql);
5722 if ($this->
db->num_rows($result)) {
5723 $obj = $this->
db->fetch_object($result);
5724 $last_date = $this->
db->jdate($obj->datef);
5725 $invoice_date = $this->date;
5727 $is_last_of_same_type = $invoice_date >= $last_date;
5728 if ($allow_validated_drafts) {
5729 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->
ref,
'PROV') && $this->status ==
self::STATUS_DRAFT);
5732 return array($is_last_of_same_type, $last_date);
5752 public $element =
'facturedet';
5757 public $table_element =
'facturedet';
5771 public $localtax1_type;
5772 public $localtax2_type;
5773 public $fk_remise_except;
5776 public $fk_fournprice;
5781 public $remise_percent;
5783 public $special_code;
5791 public $fk_code_ventilation = 0;
5796 public $skip_update_total;
5801 public $situation_percent;
5809 public $fk_multicurrency;
5810 public $multicurrency_code;
5811 public $multicurrency_subprice;
5812 public $multicurrency_total_ht;
5813 public $multicurrency_total_tva;
5814 public $multicurrency_total_ttc;
5824 $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,';
5825 $sql .=
' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
5826 $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,';
5827 $sql .=
' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
5828 $sql .=
' fd.fk_code_ventilation,';
5829 $sql .=
' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
5830 $sql .=
' fd.situation_percent, fd.fk_prev_id,';
5831 $sql .=
' fd.multicurrency_subprice,';
5832 $sql .=
' fd.multicurrency_total_ht,';
5833 $sql .=
' fd.multicurrency_total_tva,';
5834 $sql .=
' fd.multicurrency_total_ttc,';
5835 $sql .=
' p.ref as product_ref, p.label as product_label, p.description as product_desc';
5836 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as fd';
5837 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON fd.fk_product = p.rowid';
5838 $sql .=
' WHERE fd.rowid = '.((int) $rowid);
5840 $result = $this->
db->query($sql);
5842 $objp = $this->
db->fetch_object($result);
5845 $this->error =
'InvoiceLine with id '. $rowid .
' not found sql='.$sql;
5849 $this->
rowid = $objp->rowid;
5850 $this->
id = $objp->rowid;
5851 $this->fk_facture = $objp->fk_facture;
5852 $this->fk_parent_line = $objp->fk_parent_line;
5853 $this->label = $objp->custom_label;
5854 $this->desc = $objp->description;
5855 $this->qty = $objp->qty;
5856 $this->subprice = $objp->subprice;
5857 $this->ref_ext = $objp->ref_ext;
5858 $this->vat_src_code = $objp->vat_src_code;
5859 $this->tva_tx = $objp->tva_tx;
5860 $this->localtax1_tx = $objp->localtax1_tx;
5861 $this->localtax2_tx = $objp->localtax2_tx;
5862 $this->remise_percent = $objp->remise_percent;
5863 $this->fk_remise_except = $objp->fk_remise_except;
5864 $this->fk_product = $objp->fk_product;
5865 $this->product_type = $objp->product_type;
5866 $this->date_start = $this->
db->jdate($objp->date_start);
5867 $this->date_end = $this->
db->jdate($objp->date_end);
5868 $this->info_bits = $objp->info_bits;
5869 $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
5870 $this->special_code = $objp->special_code;
5871 $this->total_ht = $objp->total_ht;
5872 $this->total_tva = $objp->total_tva;
5873 $this->total_localtax1 = $objp->total_localtax1;
5874 $this->total_localtax2 = $objp->total_localtax2;
5875 $this->total_ttc = $objp->total_ttc;
5876 $this->fk_code_ventilation = $objp->fk_code_ventilation;
5877 $this->rang = $objp->rang;
5878 $this->fk_fournprice = $objp->fk_fournprice;
5879 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
5880 $this->pa_ht = $marginInfos[0];
5881 $this->marge_tx = $marginInfos[1];
5882 $this->marque_tx = $marginInfos[2];
5884 $this->
ref = $objp->product_ref;
5886 $this->product_ref = $objp->product_ref;
5887 $this->product_label = $objp->product_label;
5888 $this->product_desc = $objp->product_desc;
5890 $this->fk_unit = $objp->fk_unit;
5891 $this->fk_user_modif = $objp->fk_user_modif;
5892 $this->fk_user_author = $objp->fk_user_author;
5894 $this->situation_percent = $objp->situation_percent;
5895 $this->fk_prev_id = $objp->fk_prev_id;
5897 $this->multicurrency_subprice = $objp->multicurrency_subprice;
5898 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
5899 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
5900 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
5902 $this->
db->free($result);
5906 $this->error = $this->
db->lasterror();
5918 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
5920 global $langs, $user, $conf;
5924 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
5926 dol_syslog(get_class($this).
"::insert rang=".$this->rang, LOG_DEBUG);
5929 $this->desc = trim($this->desc);
5930 if (empty($this->tva_tx)) {
5933 if (empty($this->localtax1_tx)) {
5934 $this->localtax1_tx = 0;
5936 if (empty($this->localtax2_tx)) {
5937 $this->localtax2_tx = 0;
5939 if (empty($this->localtax1_type)) {
5940 $this->localtax1_type = 0;
5942 if (empty($this->localtax2_type)) {
5943 $this->localtax2_type = 0;
5945 if (empty($this->total_localtax1)) {
5946 $this->total_localtax1 = 0;
5948 if (empty($this->total_localtax2)) {
5949 $this->total_localtax2 = 0;
5951 if (empty($this->rang)) {
5954 if (empty($this->remise_percent)) {
5955 $this->remise_percent = 0;
5957 if (empty($this->info_bits)) {
5958 $this->info_bits = 0;
5960 if (empty($this->subprice)) {
5961 $this->subprice = 0;
5963 if (empty($this->ref_ext)) {
5964 $this->ref_ext =
'';
5966 if (empty($this->special_code)) {
5967 $this->special_code = 0;
5969 if (empty($this->fk_parent_line)) {
5970 $this->fk_parent_line = 0;
5972 if (empty($this->fk_prev_id)) {
5973 $this->fk_prev_id = 0;
5975 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
5976 $this->situation_percent = 100;
5979 if (empty($this->pa_ht)) {
5982 if (empty($this->multicurrency_subprice)) {
5983 $this->multicurrency_subprice = 0;
5985 if (empty($this->multicurrency_total_ht)) {
5986 $this->multicurrency_total_ht = 0;
5988 if (empty($this->multicurrency_total_tva)) {
5989 $this->multicurrency_total_tva = 0;
5991 if (empty($this->multicurrency_total_ttc)) {
5992 $this->multicurrency_total_ttc = 0;
5996 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
5997 if (($result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
6000 $this->pa_ht = $result;
6005 if ($this->product_type < 0) {
6006 $this->error =
'ErrorProductTypeMustBe0orMore';
6009 if (!empty($this->fk_product) && $this->fk_product > 0) {
6013 $this->error =
'ErrorProductIdDoesNotExists';
6014 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6022 $sql =
'INSERT INTO '.MAIN_DB_PREFIX.
'facturedet';
6023 $sql .=
' (fk_facture, fk_parent_line, label, description, qty,';
6024 $sql .=
' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6025 $sql .=
' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6026 $sql .=
' date_start, date_end, fk_code_ventilation, ';
6027 $sql .=
' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6028 $sql .=
' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6029 $sql .=
' situation_percent, fk_prev_id,';
6030 $sql .=
' fk_unit, fk_user_author, fk_user_modif,';
6031 $sql .=
' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
6033 $sql .=
" VALUES (".$this->fk_facture.
",";
6034 $sql .=
" ".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null").
",";
6035 $sql .=
" ".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null").
",";
6036 $sql .=
" '".$this->db->escape($this->desc).
"',";
6037 $sql .=
" ".price2num($this->qty).
",";
6038 $sql .=
" ".(empty($this->vat_src_code) ?
"''" :
"'".$this->db->escape($this->vat_src_code).
"'").
",";
6039 $sql .=
" ".price2num($this->tva_tx).
",";
6040 $sql .=
" ".price2num($this->localtax1_tx).
",";
6041 $sql .=
" ".price2num($this->localtax2_tx).
",";
6042 $sql .=
" '".$this->db->escape($this->localtax1_type).
"',";
6043 $sql .=
" '".$this->db->escape($this->localtax2_type).
"',";
6044 $sql .=
' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product :
"null").
',';
6045 $sql .=
" ".((int) $this->product_type).
",";
6046 $sql .=
" ".price2num($this->remise_percent).
",";
6047 $sql .=
" ".price2num($this->subprice).
",";
6048 $sql .=
" '".$this->db->escape($this->ref_ext).
"',";
6049 $sql .=
' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except :
"null").
',';
6050 $sql .=
" ".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null").
",";
6051 $sql .=
" ".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null").
",";
6052 $sql .=
' '.((int) $this->fk_code_ventilation).
',';
6053 $sql .=
' '.((int) $this->rang).
',';
6054 $sql .=
' '.((int) $this->special_code).
',';
6055 $sql .=
' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice :
"null").
',';
6056 $sql .=
' '.price2num($this->pa_ht).
',';
6057 $sql .=
" '".$this->db->escape($this->info_bits).
"',";
6058 $sql .=
" ".price2num($this->total_ht).
",";
6059 $sql .=
" ".price2num($this->total_tva).
",";
6060 $sql .=
" ".price2num($this->total_ttc).
",";
6061 $sql .=
" ".price2num($this->total_localtax1).
",";
6062 $sql .=
" ".price2num($this->total_localtax2);
6063 $sql .=
", ".((float) $this->situation_percent);
6064 $sql .=
", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id :
"null");
6065 $sql .=
", ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6066 $sql .=
", ".((int) $user->id);
6067 $sql .=
", ".((int) $user->id);
6068 $sql .=
", ".(int) $this->fk_multicurrency;
6069 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
6070 $sql .=
", ".price2num($this->multicurrency_subprice);
6071 $sql .=
", ".price2num($this->multicurrency_total_ht);
6072 $sql .=
", ".price2num($this->multicurrency_total_tva);
6073 $sql .=
", ".price2num($this->multicurrency_total_ttc);
6076 dol_syslog(get_class($this).
"::insert", LOG_DEBUG);
6079 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facturedet');
6080 $this->
rowid = $this->id;
6091 if ($this->fk_remise_except) {
6093 $result = $discount->fetch($this->fk_remise_except);
6098 if ($discount->fk_facture_line > 0) {
6099 if (empty($noerrorifdiscountalreadylinked)) {
6100 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed", $discount->id);
6101 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6102 $this->
db->rollback();
6106 $result = $discount->link_to_invoice($this->
rowid, 0);
6108 $this->error = $discount->error;
6109 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6110 $this->
db->rollback();
6115 $this->error = $langs->trans(
"ErrorADiscountThatHasBeenRemovedIsIncluded");
6116 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6117 $this->
db->rollback();
6121 $this->error = $discount->error;
6122 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6123 $this->
db->rollback();
6130 $result = $this->
call_trigger(
'LINEBILL_INSERT', $user);
6132 $this->
db->rollback();
6138 $this->
db->commit();
6141 $this->error = $this->
db->lasterror();
6142 $this->
db->rollback();
6154 public function update($user =
'', $notrigger = 0)
6156 global $user, $conf;
6160 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6163 $this->desc = trim($this->desc);
6164 if (empty($this->ref_ext)) {
6165 $this->ref_ext =
'';
6167 if (empty($this->tva_tx)) {
6170 if (empty($this->localtax1_tx)) {
6171 $this->localtax1_tx = 0;
6173 if (empty($this->localtax2_tx)) {
6174 $this->localtax2_tx = 0;
6176 if (empty($this->localtax1_type)) {
6177 $this->localtax1_type = 0;
6179 if (empty($this->localtax2_type)) {
6180 $this->localtax2_type = 0;
6182 if (empty($this->total_localtax1)) {
6183 $this->total_localtax1 = 0;
6185 if (empty($this->total_localtax2)) {
6186 $this->total_localtax2 = 0;
6188 if (empty($this->remise_percent)) {
6189 $this->remise_percent = 0;
6191 if (empty($this->info_bits)) {
6192 $this->info_bits = 0;
6194 if (empty($this->special_code)) {
6195 $this->special_code = 0;
6197 if (empty($this->product_type)) {
6198 $this->product_type = 0;
6200 if (empty($this->fk_parent_line)) {
6201 $this->fk_parent_line = 0;
6203 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6204 $this->situation_percent = 100;
6206 if (empty($this->pa_ht)) {
6210 if (empty($this->multicurrency_subprice)) {
6211 $this->multicurrency_subprice = 0;
6213 if (empty($this->multicurrency_total_ht)) {
6214 $this->multicurrency_total_ht = 0;
6216 if (empty($this->multicurrency_total_tva)) {
6217 $this->multicurrency_total_tva = 0;
6219 if (empty($this->multicurrency_total_ttc)) {
6220 $this->multicurrency_total_ttc = 0;
6224 if ($this->product_type < 0) {
6229 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6231 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6235 $this->pa_ht = $result;
6242 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6243 $sql .=
" description='".$this->db->escape($this->desc).
"'";
6244 $sql .=
", ref_ext='".$this->db->escape($this->ref_ext).
"'";
6245 $sql .=
", label=".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null");
6246 $sql .=
", subprice=".price2num($this->subprice);
6247 $sql .=
", remise_percent=".price2num($this->remise_percent);
6248 if ($this->fk_remise_except) {
6249 $sql .=
", fk_remise_except=".$this->fk_remise_except;
6251 $sql .=
", fk_remise_except=null";
6253 $sql .=
", vat_src_code = '".(empty($this->vat_src_code) ?
'' : $this->
db->escape($this->vat_src_code)).
"'";
6254 $sql .=
", tva_tx=".price2num($this->tva_tx);
6255 $sql .=
", localtax1_tx=".price2num($this->localtax1_tx);
6256 $sql .=
", localtax2_tx=".price2num($this->localtax2_tx);
6257 $sql .=
", localtax1_type='".$this->db->escape($this->localtax1_type).
"'";
6258 $sql .=
", localtax2_type='".$this->db->escape($this->localtax2_type).
"'";
6259 $sql .=
", qty=".price2num($this->qty);
6260 $sql .=
", date_start=".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null");
6261 $sql .=
", date_end=".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null");
6262 $sql .=
", product_type=".$this->product_type;
6263 $sql .=
", info_bits='".$this->db->escape($this->info_bits).
"'";
6264 $sql .=
", special_code='".$this->db->escape($this->special_code).
"'";
6265 if (empty($this->skip_update_total)) {
6266 $sql .=
", total_ht=".price2num($this->total_ht);
6267 $sql .=
", total_tva=".price2num($this->total_tva);
6268 $sql .=
", total_ttc=".price2num($this->total_ttc);
6269 $sql .=
", total_localtax1=".price2num($this->total_localtax1);
6270 $sql .=
", total_localtax2=".price2num($this->total_localtax2);
6272 $sql .=
", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ?
"'".$this->db->escape($this->fk_fournprice).
"'" :
"null");
6273 $sql .=
", buy_price_ht=".(($this->pa_ht || (string) $this->pa_ht ===
'0') ?
price2num($this->pa_ht) :
"null");
6274 $sql .=
", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null");
6275 if (!empty($this->rang)) {
6276 $sql .=
", rang=".((int) $this->rang);
6278 $sql .=
", situation_percent = ".((float) $this->situation_percent);
6279 $sql .=
", fk_unit = ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6280 $sql .=
", fk_user_modif = ".((int) $user->id);
6283 $sql .=
", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6284 $sql .=
", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6285 $sql .=
", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6286 $sql .=
", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6288 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6290 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
6294 $this->
id = $this->rowid;
6301 if (!$error && !$notrigger) {
6303 $result = $this->
call_trigger(
'LINEBILL_MODIFY', $user);
6305 $this->
db->rollback();
6310 $this->
db->commit();
6313 $this->error = $this->
db->error();
6314 $this->
db->rollback();
6326 public function delete($tmpuser =
null, $notrigger =
false)
6333 if (empty($notrigger)) {
6334 $result = $this->
call_trigger(
'LINEBILL_DELETE', $user);
6336 $this->
db->rollback();
6345 $this->
db->rollback();
6349 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->
rowid);
6351 if ($this->
db->query($sql)) {
6352 $this->
db->commit();
6355 $this->error = $this->
db->error().
" sql=".$sql;
6356 $this->
db->rollback();
6372 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6375 if (empty($this->total_localtax1)) {
6376 $this->total_localtax1 = 0;
6378 if (empty($this->total_localtax2)) {
6379 $this->total_localtax2 = 0;
6383 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6384 $sql .=
" total_ht=".price2num($this->total_ht).
"";
6385 $sql .=
",total_tva=".price2num($this->total_tva).
"";
6386 $sql .=
",total_localtax1=".price2num($this->total_localtax1).
"";
6387 $sql .=
",total_localtax2=".price2num($this->total_localtax2).
"";
6388 $sql .=
",total_ttc=".price2num($this->total_ttc).
"";
6389 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6391 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6395 $this->
db->commit();
6398 $this->error = $this->
db->error();
6399 $this->
db->rollback();
6416 global $invoicecache;
6418 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6422 if (!isset($invoicecache[$invoiceid])) {
6423 $invoicecache[$invoiceid] =
new Facture($this->
db);
6424 $invoicecache[$invoiceid]->fetch($invoiceid);
6430 $sql =
"SELECT situation_percent FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->fk_prev_id);
6433 $res = $this->
db->fetch_array(
$resql);
6435 $returnPercent = floatval($res[
'situation_percent']);
6437 if ($include_credit_note) {
6438 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6439 $sql .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6440 $sql .=
" WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6441 $sql .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6442 $sql .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6444 $res = $this->
db->query($sql);
6446 while ($obj = $this->
db->fetch_object($res)) {
6447 $returnPercent = $returnPercent + floatval($obj->situation_percent);
6454 return $returnPercent;
6456 $this->error = $this->
db->error();
6457 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6458 $this->
db->rollback();