43 include_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
44 require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobjectline.class.php';
45 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
46 require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
47 require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
48 require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
51 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
54 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
65 public $element =
'facture';
70 public $table_element =
'facture';
75 public $table_element_line =
'facturedet';
80 public $fk_element =
'fk_facture';
85 public $picto =
'bill';
91 public $ismultientitymanaged = 1;
97 public $restrictiononfksoc = 1;
120 public $fk_user_author;
125 public $fk_user_valid;
130 public $fk_user_modif;
141 public $date_livraison;
146 public $delivery_date;
158 public $ref_customer;
171 public $remise_absolue;
172 public $remise_percent;
175 public $total_localtax1;
176 public $total_localtax2;
178 public $revenuestamp;
206 public $linked_objects = array();
208 public $date_lim_reglement;
209 public $cond_reglement_code;
210 public $mode_reglement_code;
220 public $lines = array();
223 public $extraparams = array();
227 public $date_pointoftax;
233 public $fk_multicurrency;
235 public $multicurrency_code;
236 public $multicurrency_tx;
237 public $multicurrency_total_ht;
238 public $multicurrency_total_tva;
239 public $multicurrency_total_ttc;
244 public $situation_cycle_ref;
249 public $situation_counter;
254 public $situation_final;
259 public $tab_previous_situation_invoice = array();
264 public $tab_next_situation_invoice = array();
271 public $retained_warranty;
276 public $retained_warranty_date_limit;
281 public $retained_warranty_fk_cond_reglement;
312 public $fields = array(
313 'rowid' =>array(
'type'=>
'integer',
'label'=>
'TechnicalID',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>1),
314 'ref' =>array(
'type'=>
'varchar(30)',
'label'=>
'Ref',
'enabled'=>1,
'visible'=>1,
'notnull'=>1,
'showoncombobox'=>1,
'position'=>5),
315 'entity' =>array(
'type'=>
'integer',
'label'=>
'Entity',
'default'=>1,
'enabled'=>1,
'visible'=>-2,
'notnull'=>1,
'position'=>20,
'index'=>1),
316 'ref_client' =>array(
'type'=>
'varchar(255)',
'label'=>
'RefCustomer',
'enabled'=>1,
'visible'=>-1,
'position'=>10),
317 'ref_ext' =>array(
'type'=>
'varchar(255)',
'label'=>
'Ref ext',
'enabled'=>1,
'visible'=>0,
'position'=>12),
319 'type' =>array(
'type'=>
'smallint(6)',
'label'=>
'Type',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>15),
321 'fk_soc' =>array(
'type'=>
'integer:Societe:societe/class/societe.class.php',
'label'=>
'ThirdParty',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>50),
322 'datef' =>array(
'type'=>
'date',
'label'=>
'DateInvoice',
'enabled'=>1,
'visible'=>1,
'position'=>20),
323 'date_valid' =>array(
'type'=>
'date',
'label'=>
'DateValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>22),
324 'date_lim_reglement' =>array(
'type'=>
'date',
'label'=>
'DateDue',
'enabled'=>1,
'visible'=>1,
'position'=>25),
325 'date_closing' =>array(
'type'=>
'datetime',
'label'=>
'Date closing',
'enabled'=>1,
'visible'=>-1,
'position'=>30),
326 'paye' =>array(
'type'=>
'smallint(6)',
'label'=>
'InvoicePaidCompletely',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>80),
328 'remise_percent' =>array(
'type'=>
'double',
'label'=>
'RelativeDiscount',
'enabled'=>1,
'visible'=>-1,
'position'=>90),
329 'remise_absolue' =>array(
'type'=>
'double',
'label'=>
'CustomerRelativeDiscount',
'enabled'=>1,
'visible'=>-1,
'position'=>91),
331 'close_code' =>array(
'type'=>
'varchar(16)',
'label'=>
'EarlyClosingReason',
'enabled'=>1,
'visible'=>-1,
'position'=>92),
332 'close_note' =>array(
'type'=>
'varchar(128)',
'label'=>
'EarlyClosingComment',
'enabled'=>1,
'visible'=>-1,
'position'=>93),
333 'total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountHT',
'enabled'=>1,
'visible'=>1,
'position'=>95,
'isameasure'=>1),
334 'total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountVAT',
'enabled'=>1,
'visible'=>-1,
'position'=>100,
'isameasure'=>1),
335 'localtax1' =>array(
'type'=>
'double(24,8)',
'label'=>
'LT1',
'enabled'=>1,
'visible'=>-1,
'position'=>110,
'isameasure'=>1),
336 'localtax2' =>array(
'type'=>
'double(24,8)',
'label'=>
'LT2',
'enabled'=>1,
'visible'=>-1,
'position'=>120,
'isameasure'=>1),
337 'revenuestamp' =>array(
'type'=>
'double(24,8)',
'label'=>
'RevenueStamp',
'enabled'=>1,
'visible'=>-1,
'position'=>115,
'isameasure'=>1),
338 'total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'AmountTTC',
'enabled'=>1,
'visible'=>1,
'position'=>130,
'isameasure'=>1),
339 'fk_user_author' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'enabled'=>1,
'visible'=>-1,
'position'=>165),
340 'fk_user_modif' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'enabled'=>1,
'visible'=>-2,
'notnull'=>-1,
'position'=>166),
341 'fk_user_valid' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserValidation',
'enabled'=>1,
'visible'=>-1,
'position'=>167),
342 'fk_user_closing' =>array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserClosing',
'enabled'=>1,
'visible'=>-1,
'position'=>168),
343 'fk_facture_source' =>array(
'type'=>
'integer',
'label'=>
'SourceInvoice',
'enabled'=>1,
'visible'=>-1,
'position'=>170),
344 'fk_projet' =>array(
'type'=>
'integer:Project:projet/class/project.class.php:1:fk_statut=1',
'label'=>
'Project',
'enabled'=>1,
'visible'=>-1,
'position'=>175),
345 'fk_account' =>array(
'type'=>
'integer',
'label'=>
'Fk account',
'enabled'=>1,
'visible'=>-1,
'position'=>180),
346 'fk_currency' =>array(
'type'=>
'varchar(3)',
'label'=>
'CurrencyCode',
'enabled'=>1,
'visible'=>-1,
'position'=>185),
347 'fk_cond_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentTerm',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>190),
348 'fk_mode_reglement' =>array(
'type'=>
'integer',
'label'=>
'PaymentMode',
'enabled'=>1,
'visible'=>-1,
'position'=>195),
349 'note_private' =>array(
'type'=>
'text',
'label'=>
'NotePrivate',
'enabled'=>1,
'visible'=>0,
'position'=>205),
350 'note_public' =>array(
'type'=>
'text',
'label'=>
'NotePublic',
'enabled'=>1,
'visible'=>0,
'position'=>210),
351 'model_pdf' =>array(
'type'=>
'varchar(255)',
'label'=>
'Model pdf',
'enabled'=>1,
'visible'=>0,
'position'=>215),
352 'extraparams' =>array(
'type'=>
'varchar(255)',
'label'=>
'Extraparams',
'enabled'=>1,
'visible'=>-1,
'position'=>225),
353 'situation_cycle_ref' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation cycle ref',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>230),
354 'situation_counter' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation counter',
'enabled'=>
'$conf->global->INVOICE_USE_SITUATION',
'visible'=>-1,
'position'=>235),
355 'situation_final' =>array(
'type'=>
'smallint(6)',
'label'=>
'Situation final',
'enabled'=>
'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1',
'visible'=>-1,
'position'=>240),
356 'retained_warranty' =>array(
'type'=>
'double',
'label'=>
'Retained warranty',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>245),
357 'retained_warranty_date_limit' =>array(
'type'=>
'date',
'label'=>
'Retained warranty date limit',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>250),
358 'retained_warranty_fk_cond_reglement' =>array(
'type'=>
'integer',
'label'=>
'Retained warranty fk cond reglement',
'enabled'=>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible'=>-1,
'position'=>255),
359 'fk_incoterms' =>array(
'type'=>
'integer',
'label'=>
'IncotermCode',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>260),
360 'location_incoterms' =>array(
'type'=>
'varchar(255)',
'label'=>
'IncotermLabel',
'enabled'=>
'$conf->incoterm->enabled',
'visible'=>-1,
'position'=>265),
361 'date_pointoftax' =>array(
'type'=>
'date',
'label'=>
'DatePointOfTax',
'enabled'=>
'$conf->global->INVOICE_POINTOFTAX_DATE',
'visible'=>-1,
'position'=>270),
362 'fk_multicurrency' =>array(
'type'=>
'integer',
'label'=>
'MulticurrencyID',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>275),
363 'multicurrency_code' =>array(
'type'=>
'varchar(255)',
'label'=>
'Currency',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>280),
364 'multicurrency_tx' =>array(
'type'=>
'double(24,8)',
'label'=>
'CurrencyRate',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>285,
'isameasure'=>1),
365 'multicurrency_total_ht' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountHT',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>290,
'isameasure'=>1),
366 'multicurrency_total_tva' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountVAT',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>291,
'isameasure'=>1),
367 'multicurrency_total_ttc' =>array(
'type'=>
'double(24,8)',
'label'=>
'MulticurrencyAmountTTC',
'enabled'=>
'$conf->multicurrency->enabled',
'visible'=>-1,
'position'=>292,
'isameasure'=>1),
368 'fk_fac_rec_source' =>array(
'type'=>
'integer',
'label'=>
'RecurringInvoiceSource',
'enabled'=>1,
'visible'=>-1,
'position'=>305),
369 'last_main_doc' =>array(
'type'=>
'varchar(255)',
'label'=>
'LastMainDoc',
'enabled'=>1,
'visible'=>-1,
'position'=>310),
370 'module_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSModule',
'enabled'=>1,
'visible'=>-1,
'position'=>315),
371 'pos_source' =>array(
'type'=>
'varchar(32)',
'label'=>
'POSTerminal',
'enabled'=>1,
'visible'=>-1,
'position'=>320),
372 'datec' =>array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'enabled'=>1,
'visible'=>-1,
'position'=>500),
373 'tms' =>array(
'type'=>
'timestamp',
'label'=>
'DateModificationShort',
'enabled'=>1,
'visible'=>-1,
'notnull'=>1,
'position'=>500),
374 'import_key' =>array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'enabled'=>1,
'visible'=>-2,
'position'=>900),
375 'fk_statut' =>array(
'type'=>
'smallint(6)',
'label'=>
'Status',
'enabled'=>1,
'visible'=>1,
'notnull'=>1,
'position'=>1000,
'arrayofkeyval'=>array(0=>
'Draft', 1=>
'Validated', 2=>
'Paid', 3=>
'Abandonned')),
437 const CLOSECODE_DISCOUNTVAT =
'discount_vat';
438 const CLOSECODE_BADDEBT =
'badcustomer';
439 const CLOSECODE_BANKCHARGE =
'bankcharge';
440 const CLOSECODE_OTHER =
'other';
442 const CLOSECODE_ABANDONED =
'abandon';
443 const CLOSECODE_REPLACED =
'replaced';
466 public function create(
User $user, $notrigger = 0, $forceduedate = 0)
468 global $langs, $conf, $mysoc, $hookmanager;
472 if (empty($this->
type)) {
475 $this->ref_client = trim($this->ref_client);
476 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
477 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
478 $this->note_public = trim($this->note_public);
479 if (!$this->cond_reglement_id) {
480 $this->cond_reglement_id = 0;
482 if (!$this->mode_reglement_id) {
483 $this->mode_reglement_id = 0;
485 $this->brouillon = 1;
489 if (!empty($this->multicurrency_code)) {
491 if (empty($this->multicurrency_tx)) {
499 $this->fk_multicurrency = 0;
501 if (empty($this->fk_multicurrency)) {
502 $this->multicurrency_code = $conf->currency;
503 $this->fk_multicurrency = 0;
504 $this->multicurrency_tx = 1;
507 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
510 if (empty($this->date)) {
511 $this->error =
"Try to create an invoice with an empty parameter (date)";
512 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
516 $result = $soc->fetch($this->socid);
518 $this->error =
"Failed to fetch company: ".$soc->error;
519 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
527 $originaldatewhen =
null;
528 $nextdatewhen =
null;
529 $previousdaynextdatewhen =
null;
532 if ($this->fac_rec > 0) {
533 $this->fk_fac_rec_source = $this->fac_rec;
535 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
537 $result = $_facrec->fetch($this->fac_rec);
538 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
541 $originaldatewhen = $_facrec->date_when;
542 $nextdatewhen =
null; $previousdaynextdatewhen =
null;
543 if ($originaldatewhen) {
544 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
548 if (!empty($_facrec->frequency)) {
549 $this->socid = $_facrec->socid;
551 $this->entity = $_facrec->entity;
554 $this->fk_project =
GETPOST(
'projectid',
'int') > 0 ? ((int)
GETPOST(
'projectid',
'int')) : $_facrec->fk_project;
555 $this->note_public =
GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
556 $this->note_private =
GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
557 $this->model_pdf =
GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
558 $this->cond_reglement_id =
GETPOST(
'cond_reglement_id',
'int') > 0 ? ((int)
GETPOST(
'cond_reglement_id',
'int')) : $_facrec->cond_reglement_id;
559 $this->mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int') > 0 ? ((int)
GETPOST(
'mode_reglement_id',
'int')) : $_facrec->mode_reglement_id;
560 $this->fk_account =
GETPOST(
'fk_account') > 0 ? ((int)
GETPOST(
'fk_account')) : $_facrec->fk_account;
563 $this->total_ht = $_facrec->total_ht;
564 $this->total_ttc = $_facrec->total_ttc;
567 $this->remise_absolue = $_facrec->remise_absolue;
568 $this->remise_percent = $_facrec->remise_percent;
569 $this->fk_incoterms = $_facrec->fk_incoterms;
570 $this->location_incoterms = $_facrec->location_incoterms;
576 $this->ref_client = trim($this->ref_client);
577 $this->note_public = trim($this->note_public);
578 $this->note_private = trim($this->note_private);
579 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
581 $this->array_options = $_facrec->array_options;
583 if (!$this->mode_reglement_id) {
584 $this->mode_reglement_id = 0;
586 $this->brouillon = 1;
590 $this->linked_objects = $_facrec->linkedObjectsIds;
597 if ($_facrec->frequency > 0) {
598 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
599 if (empty($_facrec->date_when)) {
600 $_facrec->date_when = $now;
602 $next_date = $_facrec->getNextDate();
603 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
605 $result = $_facrec->setNextDate($next_date, 1);
609 $outputlangs = $langs;
612 if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) {
613 $newlang = $this->thirdparty->default_lang;
615 if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) {
616 $newlang = $this->default_lang;
618 if (!empty($newlang)) {
620 $outputlangs->setDefaultLang($newlang);
626 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
629 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
632 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
635 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
636 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
637 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
638 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
639 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
650 if (empty($forceduedate)) {
656 $this->date_lim_reglement = $duedate;
658 $this->date_lim_reglement = $forceduedate;
662 $socid = $this->socid;
664 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
671 $sql .=
", remise_absolue";
672 $sql .=
", remise_percent";
674 $sql .=
", date_pointoftax";
675 $sql .=
", note_private";
676 $sql .=
", note_public";
677 $sql .=
", ref_client, ref_int";
678 $sql .=
", fk_account";
679 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
680 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
681 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
682 $sql .=
", fk_incoterms, location_incoterms";
683 $sql .=
", fk_multicurrency";
684 $sql .=
", multicurrency_code";
685 $sql .=
", multicurrency_tx";
686 $sql .=
", retained_warranty";
687 $sql .=
", retained_warranty_date_limit";
688 $sql .=
", retained_warranty_fk_cond_reglement";
692 $sql .=
", ".setEntity($this);
693 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
694 $sql .=
", '".$this->db->escape($this->
type).
"'";
695 $sql .=
", ".((int) $socid);
696 $sql .=
", '".$this->db->idate($now).
"'";
697 $sql .=
", ".($this->remise_absolue > 0 ? $this->remise_absolue :
'NULL');
698 $sql .=
", ".($this->remise_percent > 0 ? $this->remise_percent :
'NULL');
699 $sql .=
", '".$this->db->idate($this->date).
"'";
700 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
701 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
702 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
703 $sql .=
", ".($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null");
704 $sql .=
", ".($this->ref_int ?
"'".$this->db->escape($this->ref_int).
"'" :
"null");
705 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
706 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
707 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape($this->pos_source).
"'" :
"null");
708 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape($this->fk_fac_rec_source).
"'" :
"null");
709 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape($this->fk_facture_source).
"'" :
"null");
710 $sql .=
", ".($user->id > 0 ? (int) $user->id :
"null");
711 $sql .=
", ".($this->fk_project ? $this->fk_project :
"null");
712 $sql .=
", ".((int) $this->cond_reglement_id);
713 $sql .=
", ".((int) $this->mode_reglement_id);
714 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
715 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
716 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape($this->situation_cycle_ref).
"'" :
"null");
717 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape($this->situation_counter).
"'" :
"null");
718 $sql .=
", ".($this->situation_final ? $this->situation_final : 0);
719 $sql .=
", ".(int) $this->fk_incoterms;
720 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
721 $sql .=
", ".(int) $this->fk_multicurrency;
722 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
723 $sql .=
", ".(double) $this->multicurrency_tx;
724 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty));
725 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
726 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
731 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facture');
734 $this->
ref =
'(PROV'.$this->id.
')';
735 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->
db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
742 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
743 $this->linked_objects = $this->linkedObjectsIds;
747 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
748 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
749 if (is_array($tmp_origin_id)) {
750 foreach ($tmp_origin_id as $origin_id) {
753 $this->error = $this->
db->lasterror();
759 $origin_id = $tmp_origin_id;
762 $this->error = $this->
db->lasterror();
770 if (!$error && $this->
id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) {
771 $originforcontact = $this->origin;
772 $originidforcontact = $this->origin_id;
773 if ($originforcontact ==
'shipping') {
774 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
776 $exp->fetch($this->origin_id);
777 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
778 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
779 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
780 $originforcontact =
'commande';
781 if (is_object($value)) {
782 $originidforcontact = $value->id;
784 $originidforcontact = $value;
791 $sqlcontact =
"SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX.
"element_contact as ec, ".MAIN_DB_PREFIX.
"c_type_contact as ctc";
792 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->
db->escape($originforcontact).
"'";
794 $resqlcontact = $this->
db->query($sqlcontact);
796 while ($objcontact = $this->
db->fetch_object($resqlcontact)) {
798 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
808 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
811 dol_syslog(
"There is ".count($this->lines).
" lines that are invoice lines objects");
812 foreach ($this->lines as $i => $val) {
813 $newinvoiceline = $this->lines[$i];
815 $newinvoiceline->context = $this->context;
817 $newinvoiceline->fk_facture = $this->id;
819 $newinvoiceline->origin = $this->lines[$i]->element;
820 $newinvoiceline->origin_id = $this->lines[$i]->id;
823 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
824 $newinvoiceline->date_start = $originaldatewhen;
826 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
827 $newinvoiceline->date_end = $previousdaynextdatewhen;
832 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
837 $vatrate = $newinvoiceline->tva_tx;
838 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', $vatrate)) $vatrate.=
' ('.$newinvoiceline->vat_src_code.
')';
840 $newinvoiceline->fk_parent_line = $fk_parent_line;
844 $discount->fetch($newinvoiceline->fk_remise_except);
846 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
847 $newinvoiceline->fk_remise_except = $discountId;
851 $newinvoiceline->desc,
852 $newinvoiceline->subprice,
853 $newinvoiceline->qty,
855 $newinvoiceline->localtax1_tx,
856 $newinvoiceline->localtax2_tx,
857 $newinvoiceline->fk_product,
858 $newinvoiceline->remise_percent,
859 $newinvoiceline->date_start,
860 $newinvoiceline->date_end,
861 $newinvoiceline->fk_code_ventilation,
862 $newinvoiceline->info_bits,
863 $newinvoiceline->fk_remise_except,
866 $newinvoiceline->product_type,
867 $newinvoiceline->rang,
868 $newinvoiceline->special_code,
869 $newinvoiceline->element,
872 $newinvoiceline->fk_fournprice,
873 $newinvoiceline->pa_ht,
874 $newinvoiceline->label,
875 $newinvoiceline->array_options,
876 $newinvoiceline->situation_percent,
877 $newinvoiceline->fk_prev_id,
878 $newinvoiceline->fk_unit,
879 $newinvoiceline->multicurrency_subprice,
880 $newinvoiceline->ref_ext,
885 if ($result > 0 && $newinvoiceline->product_type == 9) {
886 $fk_parent_line = $result;
890 $this->error = $newinvoiceline->error;
891 $this->errors = $newinvoiceline->errors;
896 } elseif (!$error && empty($this->fac_rec)) {
899 dol_syslog(
"There is ".count($this->lines).
" lines that are array lines");
901 foreach ($this->lines as $i => $val) {
902 $line = $this->lines[$i];
906 if (!is_object($line)) {
907 $line = (object) $line;
912 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
917 $vatrate = $line->tva_tx;
918 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', $vatrate)) {
919 $vatrate .=
' ('.$line->vat_src_code.
')';
922 if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
923 $originid = $line->origin_id;
924 $origintype = $line->origin;
926 $originid = $line->id;
927 $origintype = $this->element;
931 if (empty($line->ref_ext)) {
943 $line->remise_percent,
946 $line->fk_code_ventilation,
948 $line->fk_remise_except,
957 $line->fk_fournprice,
960 $line->array_options,
961 $line->situation_percent,
964 $line->multicurrency_subprice,
969 $this->error = $this->
db->lasterror();
971 $this->
db->rollback();
976 if ($result > 0 && $line->product_type == 9) {
977 $fk_parent_line = $result;
986 if (!$error && $this->fac_rec > 0) {
987 foreach ($_facrec->lines as $i => $val) {
988 if ($_facrec->lines[$i]->fk_product) {
990 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
1001 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
1002 $tva_npr = $_facrec->lines[$i]->info_bits;
1003 if (empty($tva_tx)) {
1006 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
1007 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1009 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1010 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1013 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1014 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1016 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1021 if ($conf->global->MARGIN_TYPE ==
'costprice' && !empty($producttmp->cost_price)) {
1022 $buyprice = $producttmp->cost_price;
1023 } elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE ==
'costprice' || $conf->global->MARGIN_TYPE ==
'pmp') && !empty($producttmp->pmp)) {
1024 $buyprice = $producttmp->pmp;
1026 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1027 if ($producttmp->product_fourn_price_id > 0) {
1028 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1034 $result_insert = $this->
addline(
1035 $_facrec->lines[$i]->desc,
1036 $_facrec->lines[$i]->subprice,
1037 $_facrec->lines[$i]->qty,
1041 $_facrec->lines[$i]->fk_product,
1042 $_facrec->lines[$i]->remise_percent,
1043 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1044 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1050 $_facrec->lines[$i]->product_type,
1051 $_facrec->lines[$i]->rang,
1052 $_facrec->lines[$i]->special_code,
1056 $fk_product_fournisseur_price,
1058 $_facrec->lines[$i]->label,
1059 empty($_facrec->lines[$i]->array_options) ?
null:$_facrec->lines[$i]->array_options,
1060 $_facrec->lines[$i]->situation_percent,
1062 $_facrec->lines[$i]->fk_unit,
1063 $_facrec->lines[$i]->multicurrency_subprice,
1064 $_facrec->lines[$i]->ref_ext,
1068 if ($result_insert < 0) {
1070 $this->error = $this->
db->error();
1089 if (!$error && !$notrigger) {
1099 $this->
db->commit();
1102 $this->
db->rollback();
1106 $this->error = $langs->trans(
'FailedToUpdatePrice');
1107 $this->
db->rollback();
1111 dol_syslog(get_class($this).
"::create error ".$this->error, LOG_ERR);
1112 $this->
db->rollback();
1116 $this->error = $this->
db->error();
1117 $this->
db->rollback();
1141 if (!empty($this->array_options)) {
1142 $facture->array_options = $this->array_options;
1145 foreach ($this->lines as &$line) {
1146 $line->fetch_optionals();
1150 $facture->type = $this->type;
1151 $facture->socid = $this->socid;
1152 $facture->date = $this->date;
1153 $facture->date_pointoftax = $this->date_pointoftax;
1154 $facture->note_public = $this->note_public;
1155 $facture->note_private = $this->note_private;
1156 $facture->ref_client = $this->ref_client;
1157 $facture->modelpdf = $this->model_pdf;
1158 $facture->model_pdf = $this->model_pdf;
1159 $facture->fk_project = $this->fk_project;
1160 $facture->cond_reglement_id = $this->cond_reglement_id;
1161 $facture->mode_reglement_id = $this->mode_reglement_id;
1162 $facture->remise_absolue = $this->remise_absolue;
1163 $facture->remise_percent = $this->remise_percent;
1165 $facture->origin = $this->origin;
1166 $facture->origin_id = $this->origin_id;
1168 $facture->lines = $this->lines;
1169 $facture->situation_counter = $this->situation_counter;
1170 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1171 $facture->situation_final = $this->situation_final;
1173 $facture->retained_warranty = $this->retained_warranty;
1174 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1175 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1177 $facture->fk_user_author = $user->id;
1181 foreach ($facture->lines as $i => $tmpline) {
1182 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1183 if ($invertdetail) {
1184 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1185 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1186 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1187 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1188 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1189 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1190 $facture->lines[$i]->ref_ext =
'';
1194 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1196 $facid = $facture->create($user);
1198 $this->error = $facture->error;
1199 $this->errors = $facture->errors;
1200 } elseif ($this->
type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
1203 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1204 foreach ($Tfk_object as $fk_object) {
1205 $facture->add_object_linked($typeObject, $fk_object);
1209 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1225 global $conf, $hookmanager;
1233 $object->fetch($fromid);
1236 $objFrom = clone $object;
1239 if (!empty($this->socid) && $this->socid != $object->socid) {
1242 if ($objsoc->fetch($this->socid) > 0) {
1243 $object->socid = $objsoc->id;
1244 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1245 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1246 $object->fk_project =
'';
1247 $object->fk_delivery_address =
'';
1258 $object->date = (empty($this->date) ?
dol_now() : $this->date);
1259 $object->user_author = $user->id;
1260 $object->user_valid =
null;
1261 $object->fk_user_author = $user->id;
1262 $object->fk_user_valid =
null;
1263 $object->fk_facture_source = 0;
1264 $object->date_creation =
'';
1265 $object->date_modification =
'';
1266 $object->date_validation =
'';
1267 $object->ref_client =
'';
1268 $object->close_code =
'';
1269 $object->close_note =
'';
1270 if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) {
1271 $object->note_private =
'';
1272 $object->note_public =
'';
1276 foreach ($object->lines as $i => $line) {
1277 if (($object->lines[$i]->info_bits & 0x02) == 0x02) {
1278 unset($object->lines[$i]);
1284 if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
1296 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1297 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1301 $object->lines[$i]->date_start = $newFirst;
1302 $object->lines[$i]->date_end = $newLast;
1306 $object->lines[$i]->ref_ext =
'';
1310 $object->context[
'createfromclone'] =
'createfromclone';
1311 $result = $object->create($user);
1314 $this->error = $object->error;
1315 $this->errors = $object->errors;
1318 if ($object->copy_linked_contact($objFrom,
'internal') < 0) {
1320 $this->error = $object->error;
1321 $this->errors = $object->errors;
1322 } elseif ($object->socid == $objFrom->socid) {
1324 if ($object->copy_linked_contact($objFrom,
'external') < 0) {
1326 $this->error = $object->error;
1327 $this->errors = $object->errors;
1334 if (is_object($hookmanager)) {
1335 $parameters = array(
'objFrom'=>$objFrom);
1337 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $object, $action);
1339 $this->errors += $hookmanager->errors;
1340 $this->error = $hookmanager->error;
1346 unset($object->context[
'createfromclone']);
1350 $this->
db->commit();
1353 $this->
db->rollback();
1367 global $conf, $hookmanager;
1375 $num = count($object->lines);
1376 for ($i = 0; $i < $num; $i++) {
1379 $line->libelle = $object->lines[$i]->libelle;
1380 $line->label = $object->lines[$i]->label;
1381 $line->desc = $object->lines[$i]->desc;
1382 $line->subprice = $object->lines[$i]->subprice;
1383 $line->total_ht = $object->lines[$i]->total_ht;
1384 $line->total_tva = $object->lines[$i]->total_tva;
1385 $line->total_localtax1 = $object->lines[$i]->total_localtax1;
1386 $line->total_localtax2 = $object->lines[$i]->total_localtax2;
1387 $line->total_ttc = $object->lines[$i]->total_ttc;
1388 $line->vat_src_code = $object->lines[$i]->vat_src_code;
1389 $line->tva_tx = $object->lines[$i]->tva_tx;
1390 $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
1391 $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
1392 $line->qty = $object->lines[$i]->qty;
1393 $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
1394 $line->remise_percent = $object->lines[$i]->remise_percent;
1395 $line->fk_product = $object->lines[$i]->fk_product;
1396 $line->info_bits = $object->lines[$i]->info_bits;
1397 $line->product_type = $object->lines[$i]->product_type;
1398 $line->rang = $object->lines[$i]->rang;
1399 $line->special_code = $object->lines[$i]->special_code;
1400 $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
1401 $line->fk_unit = $object->lines[$i]->fk_unit;
1402 $line->date_start = $object->lines[$i]->date_start;
1403 $line->date_end = $object->lines[$i]->date_end;
1406 $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
1407 $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
1408 $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
1409 $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
1410 $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
1411 $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
1413 $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
1414 $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);
1415 $line->pa_ht = $marginInfos[0];
1418 $object->lines[$i]->fetch_optionals();
1419 foreach ($object->lines[$i]->array_options as $options_key => $value) {
1420 $line->array_options[$options_key] = $value;
1423 $this->lines[$i] = $line;
1426 $this->socid = $object->socid;
1427 $this->fk_project = $object->fk_project;
1428 $this->fk_account = $object->fk_account;
1429 $this->cond_reglement_id = $object->cond_reglement_id;
1430 $this->mode_reglement_id = $object->mode_reglement_id;
1431 $this->availability_id = $object->availability_id;
1432 $this->demand_reason_id = $object->demand_reason_id;
1433 $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
1434 $this->date_livraison = $object->delivery_date;
1435 $this->fk_delivery_address = $object->fk_delivery_address;
1436 $this->contact_id = $object->contact_id;
1437 $this->ref_client = $object->ref_client;
1439 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1440 $this->note_private = $object->note_private;
1441 $this->note_public = $object->note_public;
1444 $this->module_source = $object->module_source;
1445 $this->pos_source = $object->pos_source;
1447 $this->origin = $object->element;
1448 $this->origin_id = $object->id;
1450 $this->fk_user_author = $user->id;
1453 $object->fetch_optionals();
1454 foreach ($object->array_options as $options_key => $value) {
1455 $this->array_options[$options_key] = $value;
1459 $this->linked_objects[$this->origin] = $this->origin_id;
1460 if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
1461 $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
1464 $ret = $this->
create($user);
1468 $hookmanager->initHooks(array(
'invoicedao'));
1470 $parameters = array(
'objFrom'=>$object);
1472 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1474 $this->errors += $hookmanager->errors;
1475 $this->error = $hookmanager->error;
1503 global $conf, $langs, $hookmanager, $action;
1505 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1506 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1511 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1515 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1517 if ($date > (
dol_get_last_hour(
dol_now(
'tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1518 $origin->error =
'ErrorDateIsInFuture';
1522 if ($payment_terms_id <= 0) {
1523 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1527 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1529 if (empty($payment_conditions_deposit_percent)) {
1530 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1534 if (empty($origin->deposit_percent)) {
1535 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1539 $deposit =
new self($origin->db);
1540 $deposit->socid = $origin->socid;
1542 $deposit->fk_project = $origin->fk_project;
1543 $deposit->ref_client = $origin->ref_client;
1544 $deposit->date = $date;
1545 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1546 $deposit->cond_reglement_id = $payment_terms_id;
1547 $deposit->availability_id = $origin->availability_id;
1548 $deposit->demand_reason_id = $origin->demand_reason_id;
1549 $deposit->fk_account = $origin->fk_account;
1550 $deposit->fk_incoterms = $origin->fk_incoterms;
1551 $deposit->location_incoterms = $origin->location_incoterms;
1552 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1553 $deposit->multicurrency_code = $origin->multicurrency_code;
1554 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1555 $deposit->module_source = $origin->module_source;
1556 $deposit->pos_source = $origin->pos_source;
1557 $deposit->model_pdf =
'crabe';
1559 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1561 if (!empty($conf->global->$modelByTypeConfName)) {
1562 $deposit->model_pdf = $conf->global->$modelByTypeConfName;
1563 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
1564 $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF;
1567 if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
1568 $deposit->note_private = $origin->note_private;
1569 $deposit->note_public = $origin->note_public;
1572 $deposit->origin = $origin->element;
1573 $deposit->origin_id = $origin->id;
1575 $origin->fetch_optionals();
1577 foreach ($origin->array_options as $extrakey => $value) {
1578 $deposit->array_options[$extrakey] = $value;
1581 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1583 foreach ($overrideFields as $key => $value) {
1584 $deposit->$key = $value;
1587 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1589 $origin->db->begin();
1592 $createReturn = $deposit->create($user, $notrigger);
1594 if ($createReturn <= 0) {
1595 $origin->db->rollback();
1596 $origin->error = $deposit->error;
1597 $origin->errors = $deposit->errors;
1601 $amount_ttc_diff = 0;
1602 $amountdeposit = array();
1603 $descriptions = array();
1605 if (! empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1606 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1608 $TTotalByTva = array();
1609 foreach ($origin->lines as &$line) {
1610 if (!empty($line->special_code)) {
1613 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1614 $descriptions[$line->tva_tx] .=
'<li>' . (! empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1615 $descriptions[$line->tva_tx] .= (! empty($line->product_label) ? $line->product_label .
' - ' :
'');
1616 $descriptions[$line->tva_tx] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1617 $descriptions[$line->tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1620 foreach ($TTotalByTva as $tva => &$total) {
1621 $coef = $total / $origin->total_ttc;
1622 $am = $amount * $coef;
1623 $amount_ttc_diff += $am;
1624 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1628 $lines = $origin->lines;
1629 $numlines = count($lines);
1630 for ($i = 0; $i < $numlines; $i++) {
1631 if (empty($lines[$i]->qty)) {
1634 if (!empty($lines[$i]->special_code)) {
1638 $totalamount += $lines[$i]->total_ht;
1639 $tva_tx = $lines[$i]->tva_tx;
1640 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1641 $descriptions[$tva_tx] .=
'<li>' . (! empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1642 $descriptions[$tva_tx] .= (! empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1643 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1644 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1647 if ($totalamount == 0) {
1648 $amountdeposit[0] = 0;
1651 $amount_ttc_diff = $amountdeposit[0];
1654 foreach ($amountdeposit as $tva => $amount) {
1655 if (empty($amount)) {
1659 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1662 if (! empty($conf->global->INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION) && ! empty($descriptions[$tva])) {
1663 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1666 $addlineResult = $deposit->addline(
1673 (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1693 if ($addlineResult < 0) {
1694 $origin->db->rollback();
1695 $origin->error = $deposit->error;
1696 $origin->errors = $deposit->errors;
1701 $diff = $deposit->total_ttc - $amount_ttc_diff;
1703 if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1704 $deposit->fetch_lines();
1705 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1707 $updatelineResult = $deposit->updateline(
1708 $deposit->lines[0]->id,
1709 $deposit->lines[0]->desc,
1711 $deposit->lines[0]->qty,
1712 $deposit->lines[0]->remise_percent,
1713 $deposit->lines[0]->date_start,
1714 $deposit->lines[0]->date_end,
1715 $deposit->lines[0]->tva_tx,
1719 $deposit->lines[0]->info_bits,
1720 $deposit->lines[0]->product_type,
1724 $deposit->lines[0]->pa_ht,
1725 $deposit->lines[0]->label,
1731 if ($updatelineResult < 0) {
1732 $origin->db->rollback();
1733 $origin->error = $deposit->error;
1734 $origin->errors = $deposit->errors;
1740 if (! is_object($hookmanager)) {
1741 require_once DOL_DOCUMENT_ROOT .
'/core/class/hookmanager.class.php';
1745 $hookmanager->initHooks(array(
'invoicedao'));
1747 $parameters = array(
'objFrom' => $origin);
1748 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1751 $origin->db->rollback();
1752 $origin->error = $hookmanager->error;
1753 $origin->errors = $hookmanager->errors;
1757 if (! empty($autoValidateDeposit)) {
1758 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1760 if ($validateReturn < 0) {
1761 $origin->db->rollback();
1762 $origin->error = $deposit->error;
1763 $origin->errors = $deposit->errors;
1768 unset($deposit->context[
'createdepositfromorigin']);
1770 $origin->db->commit();
1789 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
1791 global $langs, $conf, $user, $mysoc;
1793 if (!empty($conf->dol_no_mouse_hover)) {
1799 if ($option ==
'withdraw') {
1800 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
1802 $url = DOL_URL_ROOT.
'/compta/facture/card.php?facid='.$this->id;
1805 if (!$user->rights->facture->lire) {
1809 if ($option !==
'nolink') {
1811 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1812 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
1813 $add_save_lastsearch_values = 1;
1815 if ($add_save_lastsearch_values) {
1816 $url .=
'&save_lastsearch_values=1';
1824 $picto = $this->picto;
1825 if ($this->
type == self::TYPE_REPLACEMENT) {
1828 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1831 if ($this->
type == self::TYPE_DEPOSIT) {
1836 if ($user->rights->facture->lire) {
1837 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1838 if ($this->
type == self::TYPE_REPLACEMENT) {
1839 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv(
"ReplacementInvoice").
'</u>';
1841 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1842 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv(
"CreditNote").
'</u>';
1844 if ($this->
type == self::TYPE_DEPOSIT) {
1845 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv(
"Deposit").
'</u>';
1847 if ($this->
type == self::TYPE_SITUATION) {
1848 $label =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv(
"InvoiceSituation").
'</u>';
1850 if (isset($this->statut) && isset($this->alreadypaid)) {
1851 $label .=
' '.$this->getLibStatut(5, $this->alreadypaid);
1853 if (!empty($this->
ref)) {
1854 $label .=
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
1856 if (!empty($this->ref_client)) {
1857 $label .=
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_client;
1859 if (!empty($this->date)) {
1860 $label .=
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
1862 if (!empty($this->total_ht)) {
1863 $label .=
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1865 if (!empty($this->total_tva)) {
1866 $label .=
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1868 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1869 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1871 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1872 $label .=
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1874 if (!empty($this->total_ttc)) {
1875 $label .=
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1878 $label .=
' - '.$moretitle;
1882 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
1883 if (empty($notooltip) && $user->rights->facture->lire) {
1884 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1885 $label = $langs->trans(
"Invoice");
1886 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
1888 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
1889 $linkclose .=
' class="classfortooltip"';
1892 $linkstart =
'<a href="'.$url.
'"';
1893 $linkstart .= $linkclose.
'>';
1896 if ($option ==
'nolink') {
1901 $result .= $linkstart;
1903 $result .=
img_object(($notooltip ?
'' : $label), $picto, ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1905 if ($withpicto != 2) {
1906 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
1908 $result .= $linkend;
1910 if ($addlinktonotes) {
1911 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1914 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
1915 $result .=
' <span class="note inline-block">';
1916 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
1921 $result .=
'</span>';
1925 global $action, $hookmanager;
1926 $hookmanager->initHooks(array(
'invoicedao'));
1927 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value'=> $save_lastsearch_value,
'target' => $target);
1928 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
1930 $result = $hookmanager->resPrint;
1932 $result .= $hookmanager->resPrint;
1948 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused =
'', $fetch_situation =
false)
1950 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
1954 $sql =
'SELECT f.rowid,f.entity,f.ref,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc';
1955 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
1956 $sql .=
', f.remise_percent, f.remise_absolue, f.remise';
1957 $sql .=
', f.datef as df, f.date_pointoftax';
1958 $sql .=
', f.date_lim_reglement as dlr';
1959 $sql .=
', f.datec as datec';
1960 $sql .=
', f.date_valid as datev';
1961 $sql .=
', f.tms as datem';
1962 $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';
1963 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
1964 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
1965 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
1966 $sql .=
', f.fk_account';
1967 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
1968 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
1969 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
1970 $sql .=
', f.fk_incoterms, f.location_incoterms';
1971 $sql .=
', f.module_source, f.pos_source';
1972 $sql .=
", i.libelle as label_incoterms";
1973 $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";
1974 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
1975 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
1976 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
1977 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
1980 $sql .=
" WHERE f.rowid=".((int) $rowid);
1982 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
1984 $sql .=
" AND f.ref='".$this->db->escape($ref).
"'";
1987 $sql .=
" AND f.ref_ext='".$this->db->escape($ref_ext).
"'";
1990 $sql .=
" AND f.ref_int='".$this->db->escape($notused).
"'";
1994 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
1998 $obj = $this->
db->fetch_object(
$resql);
2000 $this->
id = $obj->rowid;
2001 $this->entity = $obj->entity;
2003 $this->
ref = $obj->ref;
2004 $this->ref_client = $obj->ref_client;
2005 $this->ref_customer = $obj->ref_client;
2006 $this->ref_ext = $obj->ref_ext;
2007 $this->
type = $obj->type;
2008 $this->date = $this->
db->jdate($obj->df);
2009 $this->date_pointoftax = $this->
db->jdate($obj->date_pointoftax);
2010 $this->date_creation = $this->
db->jdate($obj->datec);
2011 $this->date_validation = $this->
db->jdate($obj->datev);
2012 $this->date_modification = $this->
db->jdate($obj->datem);
2013 $this->datem = $this->
db->jdate($obj->datem);
2014 $this->remise_percent = $obj->remise_percent;
2015 $this->remise_absolue = $obj->remise_absolue;
2016 $this->total_ht = $obj->total_ht;
2017 $this->total_tva = $obj->total_tva;
2018 $this->total_localtax1 = $obj->localtax1;
2019 $this->total_localtax2 = $obj->localtax2;
2020 $this->total_ttc = $obj->total_ttc;
2021 $this->revenuestamp = $obj->revenuestamp;
2022 $this->paye = $obj->paye;
2023 $this->close_code = $obj->close_code;
2024 $this->close_note = $obj->close_note;
2026 $this->socid = $obj->fk_soc;
2027 $this->thirdparty =
null;
2029 $this->fk_project = $obj->fk_project;
2030 $this->project =
null;
2032 $this->statut = $obj->fk_statut;
2033 $this->status = $obj->fk_statut;
2035 $this->date_lim_reglement = $this->
db->jdate($obj->dlr);
2036 $this->mode_reglement_id = $obj->fk_mode_reglement;
2037 $this->mode_reglement_code = $obj->mode_reglement_code;
2038 $this->mode_reglement = $obj->mode_reglement_libelle;
2039 $this->cond_reglement_id = $obj->fk_cond_reglement;
2040 $this->cond_reglement_code = $obj->cond_reglement_code;
2041 $this->cond_reglement = $obj->cond_reglement_libelle;
2042 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2043 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2044 $this->fk_facture_source = $obj->fk_facture_source;
2045 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2046 $this->note = $obj->note_private;
2047 $this->note_private = $obj->note_private;
2048 $this->note_public = $obj->note_public;
2049 $this->user_author = $obj->fk_user_author;
2050 $this->user_valid = $obj->fk_user_valid;
2051 $this->user_modification = $obj->fk_user_modif;
2052 $this->fk_user_author = $obj->fk_user_author;
2053 $this->fk_user_valid = $obj->fk_user_valid;
2054 $this->fk_user_modif = $obj->fk_user_modif;
2055 $this->model_pdf = $obj->model_pdf;
2056 $this->modelpdf = $obj->model_pdf;
2057 $this->last_main_doc = $obj->last_main_doc;
2058 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2059 $this->situation_counter = $obj->situation_counter;
2060 $this->situation_final = $obj->situation_final;
2061 $this->retained_warranty = $obj->retained_warranty;
2062 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2063 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2065 $this->extraparams = (array) json_decode($obj->extraparams,
true);
2068 $this->fk_incoterms = $obj->fk_incoterms;
2069 $this->location_incoterms = $obj->location_incoterms;
2070 $this->label_incoterms = $obj->label_incoterms;
2072 $this->module_source = $obj->module_source;
2073 $this->pos_source = $obj->pos_source;
2076 $this->fk_multicurrency = $obj->fk_multicurrency;
2077 $this->multicurrency_code = $obj->multicurrency_code;
2078 $this->multicurrency_tx = $obj->multicurrency_tx;
2079 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2080 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2081 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2083 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2087 if ($this->status == self::STATUS_DRAFT) {
2088 $this->brouillon = 1;
2096 $this->lines = array();
2100 $this->error = $this->
db->error();
2108 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2110 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2114 $this->error = $this->
db->lasterror();
2129 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2132 global $langs, $conf;
2134 $this->lines = array();
2136 $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,';
2137 $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,';
2138 $sql .=
' l.situation_percent, l.fk_prev_id,';
2139 $sql .=
' l.rang, l.special_code,';
2140 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2141 $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,';
2142 $sql .=
' l.fk_unit,';
2143 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2144 $sql .=
' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
2145 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2146 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2147 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2148 $sql .=
' ORDER BY l.rang, l.rowid';
2150 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2151 $result = $this->
db->query($sql);
2153 $num = $this->
db->num_rows($result);
2156 $objp = $this->
db->fetch_object($result);
2159 $line->id = $objp->rowid;
2160 $line->rowid = $objp->rowid;
2161 $line->fk_facture = $objp->fk_facture;
2162 $line->label = $objp->custom_label;
2163 $line->desc = $objp->description;
2164 $line->description = $objp->description;
2165 $line->product_type = $objp->product_type;
2166 $line->ref = $objp->product_ref;
2167 $line->product_ref = $objp->product_ref;
2168 $line->libelle = $objp->product_label;
2169 $line->product_label = $objp->product_label;
2170 $line->product_desc = $objp->product_desc;
2171 $line->fk_product_type = $objp->fk_product_type;
2172 $line->qty = $objp->qty;
2173 $line->subprice = $objp->subprice;
2174 $line->ref_ext = $objp->ref_ext;
2176 $line->vat_src_code = $objp->vat_src_code;
2177 $line->tva_tx = $objp->tva_tx;
2178 $line->localtax1_tx = $objp->localtax1_tx;
2179 $line->localtax2_tx = $objp->localtax2_tx;
2180 $line->localtax1_type = $objp->localtax1_type;
2181 $line->localtax2_type = $objp->localtax2_type;
2182 $line->remise_percent = $objp->remise_percent;
2183 $line->fk_remise_except = $objp->fk_remise_except;
2184 $line->fk_product = $objp->fk_product;
2185 $line->date_start = $this->
db->jdate($objp->date_start);
2186 $line->date_end = $this->
db->jdate($objp->date_end);
2187 $line->date_start = $this->
db->jdate($objp->date_start);
2188 $line->date_end = $this->
db->jdate($objp->date_end);
2189 $line->info_bits = $objp->info_bits;
2190 $line->total_ht = $objp->total_ht;
2191 $line->total_tva = $objp->total_tva;
2192 $line->total_localtax1 = $objp->total_localtax1;
2193 $line->total_localtax2 = $objp->total_localtax2;
2194 $line->total_ttc = $objp->total_ttc;
2195 $line->code_ventilation = $objp->fk_code_ventilation;
2196 $line->fk_fournprice = $objp->fk_fournprice;
2197 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2198 $line->pa_ht = $marginInfos[0];
2199 $line->marge_tx = $marginInfos[1];
2200 $line->marque_tx = $marginInfos[2];
2201 $line->rang = $objp->rang;
2202 $line->special_code = $objp->special_code;
2203 $line->fk_parent_line = $objp->fk_parent_line;
2204 $line->situation_percent = $objp->situation_percent;
2205 $line->fk_prev_id = $objp->fk_prev_id;
2206 $line->fk_unit = $objp->fk_unit;
2209 $line->fk_accounting_account = $objp->fk_code_ventilation;
2212 $line->fk_multicurrency = $objp->fk_multicurrency;
2213 $line->multicurrency_code = $objp->multicurrency_code;
2214 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2215 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2216 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2217 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2219 $line->fetch_optionals();
2222 if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2224 $tmpproduct->fetch($objp->fk_product);
2225 $tmpproduct->getMultiLangs();
2227 $line->multilangs = $tmpproduct->multilangs;
2230 $this->lines[$i] = $line;
2234 $this->
db->free($result);
2237 $this->error = $this->
db->error();
2252 $this->tab_previous_situation_invoice = array();
2253 $this->tab_next_situation_invoice = array();
2255 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2256 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2257 $sql .=
' AND entity = '.((int) $this->entity);
2258 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2259 $sql .=
' ORDER BY situation_counter ASC';
2261 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2262 $result = $this->
db->query($sql);
2263 if ($result && $this->
db->num_rows($result) > 0) {
2264 while ($objp = $this->
db->fetch_object($result)) {
2266 if ($invoice->fetch($objp->rowid) > 0) {
2267 if ($objp->situation_counter < $this->situation_counter
2268 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2270 $this->tab_previous_situation_invoice[] = $invoice;
2272 $this->tab_next_situation_invoice[] = $invoice;
2293 if (empty($this->
type)) {
2296 if (isset($this->
ref)) {
2297 $this->
ref = trim($this->
ref);
2299 if (isset($this->ref_ext)) {
2300 $this->ref_ext = trim($this->ref_ext);
2302 if (isset($this->ref_client)) {
2303 $this->ref_client = trim($this->ref_client);
2305 if (isset($this->increment)) {
2306 $this->increment = trim($this->increment);
2308 if (isset($this->close_code)) {
2309 $this->close_code = trim($this->close_code);
2311 if (isset($this->close_note)) {
2312 $this->close_note = trim($this->close_note);
2314 if (isset($this->note) || isset($this->note_private)) {
2315 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2317 if (isset($this->note) || isset($this->note_private)) {
2318 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2320 if (isset($this->note_public)) {
2321 $this->note_public = trim($this->note_public);
2323 if (isset($this->model_pdf)) {
2324 $this->model_pdf = trim($this->model_pdf);
2326 if (isset($this->import_key)) {
2327 $this->import_key = trim($this->import_key);
2329 if (isset($this->retained_warranty)) {
2330 $this->retained_warranty = floatval($this->retained_warranty);
2338 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2339 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2340 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2341 $sql .=
" type=".(isset($this->
type) ? $this->
db->escape($this->
type) :
"null").
",";
2342 $sql .=
" ref_client=".(isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null").
",";
2343 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2344 $sql .=
" fk_soc=".(isset($this->socid) ? $this->
db->escape($this->socid) :
"null").
",";
2345 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2346 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2347 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2348 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2349 $sql .=
" paye=".(isset($this->paye) ? $this->
db->escape($this->paye) : 0).
",";
2350 $sql .=
" remise_percent=".(isset($this->remise_percent) ? $this->
db->escape($this->remise_percent) :
"null").
",";
2351 $sql .=
" remise_absolue=".(isset($this->remise_absolue) ? $this->
db->escape($this->remise_absolue) :
"null").
",";
2352 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2353 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2354 $sql .=
" total_tva=".(isset($this->total_tva) ? $this->total_tva :
"null").
",";
2355 $sql .=
" localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 :
"null").
",";
2356 $sql .=
" localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 :
"null").
",";
2357 $sql .=
" total_ht=".(isset($this->total_ht) ? $this->total_ht :
"null").
",";
2358 $sql .=
" total_ttc=".(isset($this->total_ttc) ? $this->total_ttc :
"null").
",";
2359 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? $this->
db->escape($this->revenuestamp) :
"null").
",";
2360 $sql .=
" fk_statut=".(isset($this->statut) ? $this->
db->escape($this->statut) :
"null").
",";
2361 $sql .=
" fk_user_author=".(isset($this->user_author) ? $this->
db->escape($this->user_author) :
"null").
",";
2362 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? $this->
db->escape($this->fk_user_valid) :
"null").
",";
2363 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? $this->
db->escape($this->fk_facture_source) :
"null").
",";
2364 $sql .=
" fk_projet=".(isset($this->fk_project) ? $this->
db->escape($this->fk_project) :
"null").
",";
2365 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->
db->escape($this->cond_reglement_id) :
"null").
",";
2366 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->
db->escape($this->mode_reglement_id) :
"null").
",";
2367 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2368 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2369 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2370 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2371 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2372 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : $this->
db->escape($this->situation_cycle_ref)).
",";
2373 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : $this->
db->escape($this->situation_counter)).
",";
2374 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : $this->
db->escape($this->situation_final)).
",";
2375 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : $this->
db->escape($this->retained_warranty)).
",";
2376 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2377 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) :
"null");
2378 $sql .=
" WHERE rowid=".((int) $this->
id);
2382 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2386 $this->errors[] =
"Error ".$this->db->lasterror();
2396 if (!$error && !$notrigger) {
2407 foreach ($this->errors as $errmsg) {
2408 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2409 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2411 $this->
db->rollback();
2414 $this->
db->commit();
2430 global $conf, $langs;
2432 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2433 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2438 $result = $remise->fetch($idremise);
2441 if ($remise->fk_facture) {
2442 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2443 $this->
db->rollback();
2448 $facligne->fk_facture = $this->id;
2449 $facligne->fk_remise_except = $remise->id;
2450 $facligne->desc = $remise->description;
2451 $facligne->vat_src_code = $remise->vat_src_code;
2452 $facligne->tva_tx = $remise->tva_tx;
2453 $facligne->subprice = -$remise->amount_ht;
2454 $facligne->fk_product = 0;
2456 $facligne->remise_percent = 0;
2457 $facligne->rang = -1;
2458 $facligne->info_bits = 2;
2460 if (!empty($conf->global->MAIN_ADD_LINE_AT_POSITION)) {
2461 $facligne->rang = 1;
2462 $linecount = count($this->lines);
2463 for ($ii = 1; $ii <= $linecount; $ii++) {
2469 if ($remise->fk_facture_source > 0) {
2471 $srcinvoice->fetch($remise->fk_facture_source);
2472 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2474 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2475 $facligne->pa_ht = $arraytmp[
'pa_total'];
2478 $facligne->total_ht = -$remise->amount_ht;
2479 $facligne->total_tva = -$remise->amount_tva;
2480 $facligne->total_ttc = -$remise->amount_ttc;
2482 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2483 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2484 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2485 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2487 $lineid = $facligne->insert();
2492 $result = $remise->link_to_invoice($lineid, 0);
2494 $this->error = $remise->error;
2495 $this->
db->rollback();
2499 $this->
db->commit();
2502 $this->error = $facligne->error;
2503 $this->
db->rollback();
2507 $this->error = $facligne->error;
2508 $this->
db->rollback();
2512 $this->
db->rollback();
2534 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2535 if (empty($ref_client)) {
2536 $sql .=
' SET ref_client = NULL';
2538 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2540 $sql .=
" WHERE rowid = ".((int) $this->
id);
2542 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2545 $this->errors[] = $this->
db->error();
2550 $this->ref_client = $ref_client;
2553 if (!$notrigger && empty($error)) {
2563 $this->ref_client = $ref_client;
2565 $this->
db->commit();
2568 foreach ($this->errors as $errmsg) {
2569 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2570 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2572 $this->
db->rollback();
2585 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2587 global $langs, $conf;
2588 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2592 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2605 if (!$error && !$notrigger) {
2619 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2633 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2634 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2635 $sql .=
' AND fk_facture_line IS NULL';
2640 $list_rowid_det = array();
2641 foreach ($this->lines as $key => $invoiceline) {
2642 $list_rowid_det[] = $invoiceline->id;
2646 if (count($list_rowid_det)) {
2647 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2648 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2649 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(join(
',', $list_rowid_det)).
')';
2651 if (!$this->
db->query($sql)) {
2652 $this->error = $this->
db->error().
" sql=".$sql;
2653 $this->errors[] = $this->error;
2654 $this->
db->rollback();
2661 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2662 $sql .=
' SET fk_invoice = NULL';
2663 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2665 if (!$this->
db->query($sql)) {
2666 $this->error = $this->
db->error().
" sql=".$sql;
2667 $this->errors[] = $this->error;
2668 $this->
db->rollback();
2672 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'projet_task_time';
2673 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2674 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2676 if (!$this->
db->query($sql)) {
2677 $this->error = $this->
db->error().
" sql=".$sql;
2678 $this->errors[] = $this->error;
2679 $this->
db->rollback();
2684 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
2685 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2686 $langs->load(
"agenda");
2688 $num = count($this->lines);
2689 for ($i = 0; $i < $num; $i++) {
2690 if ($this->lines[$i]->fk_product > 0) {
2692 $mouvP->origin = &$this;
2693 $mouvP->setOrigin($this->element, $this->
id);
2695 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2696 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2698 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2705 $main = MAIN_DB_PREFIX.
'facturedet';
2706 $ef = $main.
"_extrafields";
2707 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2709 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2712 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2721 if ($conf->facture->dir_output && !empty($this->
ref)) {
2722 $dir = $conf->facture->dir_output.
"/".$ref;
2723 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2724 if (file_exists($file)) {
2728 $langs->load(
"errors");
2729 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2730 $this->errors[] = $this->error;
2731 $this->
db->rollback();
2735 if (file_exists($dir)) {
2737 $langs->load(
"errors");
2738 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2739 $this->errors[] = $this->error;
2740 $this->
db->rollback();
2746 $this->
db->commit();
2749 $this->error = $this->
db->lasterror().
" sql=".$sql;
2750 $this->errors[] = $this->error;
2751 $this->
db->rollback();
2755 $this->error = $this->
db->lasterror().
" sql=".$sql;
2756 $this->errors[] = $this->error;
2757 $this->
db->rollback();
2761 $this->
db->rollback();
2778 public function set_paid($user, $close_code =
'', $close_note =
'')
2781 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2782 return $this->
setPaid($user, $close_code, $close_note);
2794 public function setPaid($user, $close_code =
'', $close_note =
'')
2798 if ($this->paye != 1) {
2803 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
2805 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2806 $sql .=
' fk_statut='.self::STATUS_CLOSED;
2811 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2814 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2816 $sql .=
', fk_user_closing = '.((int) $user->id);
2817 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
2818 $sql .=
" WHERE rowid = ".((int) $this->
id);
2830 $this->error = $this->
db->lasterror();
2834 $this->
db->commit();
2837 $this->
db->rollback();
2860 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
2878 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2879 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
2880 $sql .=
' date_closing=null,';
2881 $sql .=
' fk_user_closing=null';
2882 $sql .=
" WHERE rowid = ".((int) $this->
id);
2884 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
2895 $this->error = $this->
db->error();
2900 $this->
db->commit();
2903 $this->
db->rollback();
2925 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
2926 return $this->
setCanceled($user, $close_code, $close_note);
2939 public function setCanceled($user, $close_code =
'', $close_note =
'')
2941 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
2945 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2946 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
2948 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2951 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2953 $sql .=
" WHERE rowid = ".((int) $this->
id);
2959 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2960 $sql .=
' SET fk_facture = NULL';
2961 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
2968 $this->
db->rollback();
2973 $this->
db->commit();
2976 $this->error = $this->
db->error().
" sql=".$sql;
2977 $this->
db->rollback();
2981 $this->error = $this->
db->error().
" sql=".$sql;
2982 $this->
db->rollback();
2998 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3000 global $conf, $langs, $mysoc;
3001 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3003 $productStatic =
null;
3004 $warehouseStatic =
null;
3005 if ($batch_rule > 0) {
3006 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3007 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3008 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3009 $productStatic =
new Product($this->
db);
3011 $productbatch =
new ProductBatch($this->
db);
3017 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3024 if ($this->statut != self::STATUS_DRAFT) {
3025 dol_syslog(get_class($this).
"::validate status is not draft. operation canceled.", LOG_WARNING);
3028 if (count($this->lines) <= 0) {
3029 $langs->load(
"errors");
3030 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3033 if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
3034 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
3035 $this->error =
'Permission denied';
3036 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
3039 if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
3041 if (!$last_of_type[0]) {
3042 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3048 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3049 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3050 foreach ($array_to_check as $key) {
3051 $keymin = strtolower($key);
3052 if (!property_exists($this->thirdparty, $keymin)) {
3055 $vallabel = $this->thirdparty->$keymin;
3057 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3059 if ($this->thirdparty->isACompany()) {
3061 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3062 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3063 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3064 $langs->load(
"errors");
3065 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3066 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3072 if ($key ==
'EMAIL') {
3074 if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($this->thirdparty->email)) {
3075 $langs->load(
"errors");
3076 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3077 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3081 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3083 if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY) && empty($this->thirdparty->code_compta)) {
3084 $langs->load(
"errors");
3085 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3086 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3095 $array_to_check = array(
'REF_CLIENT'=>
'RefCustomer');
3096 foreach ($array_to_check as $key => $val) {
3097 $keymin = strtolower($key);
3098 $vallabel = $this->$keymin;
3101 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3102 if (!$vallabel && !empty($conf->global->$keymandatory)) {
3103 $langs->load(
"errors");
3105 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val)),
null,
'errors');
3112 if ($this->
type == self::TYPE_REPLACEMENT) {
3114 if ($this->fk_facture_source <= 0) {
3115 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3116 $this->
db->rollback();
3122 $result = $facreplaced->fetch($this->fk_facture_source);
3124 $this->error = $langs->trans(
"ErrorBadInvoice");
3125 $this->
db->rollback();
3130 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3131 if ($idreplacement && $idreplacement != $this->
id) {
3132 $facreplacement =
new Facture($this->
db);
3133 $facreplacement->fetch($idreplacement);
3134 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3135 $this->
db->rollback();
3139 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3141 $this->error = $facreplaced->error;
3142 $this->
db->rollback();
3148 if ($force_number) {
3149 $num = $force_number;
3150 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3151 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3166 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3167 $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).
"'";
3168 if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
3169 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3170 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3172 $sql .=
" WHERE rowid = ".((int) $this->
id);
3174 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3182 if (!$error && (preg_match(
'/^[\(]?PROV/i', $this->
ref))) {
3188 $result = $this->thirdparty->set_as_client();
3191 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
3192 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3193 $langs->load(
"agenda");
3196 $cpt = count($this->lines);
3197 for ($i = 0; $i < $cpt; $i++) {
3198 if ($this->lines[$i]->fk_product > 0) {
3200 $mouvP->origin = &$this;
3201 $mouvP->setOrigin($this->element, $this->
id);
3203 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3204 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3207 $this->error = $mouvP->error;
3210 $is_batch_line =
false;
3211 if ($batch_rule > 0) {
3212 $productStatic->fetch($this->lines[$i]->fk_product);
3213 if ($productStatic->hasbatch()) {
3214 $is_batch_line =
true;
3215 $product_qty_remain = $this->lines[$i]->qty;
3221 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3222 $sortorder =
'ASC,ASC,ASC,ASC';
3225 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ?
null : 0), $sortfield, $sortorder);
3226 if (!is_array($resBatchList)) {
3228 $this->error = $this->
db->lasterror();
3232 $batchList = $resBatchList;
3233 if (empty($batchList)) {
3235 $langs->load(
'errors');
3236 $warehouseStatic->fetch($idwarehouse);
3237 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3238 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3241 foreach ($batchList as $batch) {
3242 if ($batch->qty <= 0) {
3247 if ($batch->qty >= $product_qty_remain) {
3248 $product_batch_qty = $product_qty_remain;
3251 $product_batch_qty = $batch->qty;
3253 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3256 $this->error = $mouvP->error;
3260 $product_qty_remain -= $product_batch_qty;
3262 if ($product_qty_remain <= 0) {
3267 if (!$error && $product_qty_remain > 0) {
3268 if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
3270 $batch = $batchList[0];
3271 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3274 $this->error = $mouvP->error;
3278 $langs->load(
'errors');
3279 $warehouseStatic->fetch($idwarehouse);
3280 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3281 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3288 if (!$is_batch_line) {
3289 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3292 $this->error = $mouvP->error;
3305 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3306 $invoice_situation =
new Facture($this->
db);
3307 $result = $invoice_situation->fetch($this->fk_facture_source);
3308 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3309 $invoice_situation->situation_final = 0;
3311 $result = $invoice_situation->setFinal($user, 1);
3314 $this->error = $invoice_situation->error;
3315 $this->errors = $invoice_situation->errors;
3321 if (!$error && !$notrigger) {
3331 $this->oldref = $this->ref;
3334 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3336 $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).
"'";
3337 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->
db->escape($this->
ref).
"' and entity = ".$conf->entity;
3341 $this->error = $this->
db->lasterror();
3347 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3348 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3349 if (!$error && file_exists($dirsource)) {
3350 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3352 if (@rename($dirsource, $dirdest)) {
3355 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3356 foreach ($listoffiles as $fileentry) {
3357 $dirsource = $fileentry[
'name'];
3358 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3359 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3360 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3361 @rename($dirsource, $dirdest);
3380 $this->brouillon = 0;
3381 $this->date_validation = $now;
3384 if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3386 $nboflines = count($this->lines);
3387 while (($i < $nboflines) && $final) {
3388 $final = ($this->lines[$i]->situation_percent == 100);
3392 if (empty($final)) {
3393 $this->situation_final = 0;
3395 $this->situation_final = 1;
3406 $this->
db->commit();
3409 $this->
db->rollback();
3422 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3423 $is_last = $next_invoice->is_last_in_cycle();
3425 if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
3426 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3430 $next_invoice->brouillon = 1;
3432 foreach ($next_invoice->lines as $line) {
3433 $result = $next_invoice->updateline(
3438 $line->remise_percent,
3442 $line->localtax1_tx,
3443 $line->localtax2_tx,
3446 $line->product_type,
3447 $line->fk_parent_line,
3449 $line->fk_fournprice,
3452 $line->special_code,
3453 $line->array_options,
3454 $line->situation_percent,
3459 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3480 global $conf, $langs;
3484 if ($this->statut == self::STATUS_DRAFT) {
3485 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3493 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3494 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3495 $sql .=
" WHERE rowid = ".((int) $this->
id);
3497 $result = $this->
db->query($sql);
3500 $this->oldcopy = clone $this;
3504 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
3505 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3506 $langs->load(
"agenda");
3508 $num = count($this->lines);
3509 for ($i = 0; $i < $num; $i++) {
3510 if ($this->lines[$i]->fk_product > 0) {
3512 $mouvP->origin = &$this;
3513 $mouvP->setOrigin($this->element, $this->
id);
3515 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3516 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3518 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3525 $old_statut = $this->statut;
3526 $this->brouillon = 1;
3531 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3534 $this->statut = $old_statut;
3535 $this->status = $old_statut;
3536 $this->brouillon = 0;
3540 $this->
db->rollback();
3545 $this->
db->commit();
3548 $this->
db->rollback();
3552 $this->error = $this->
db->error();
3553 $this->
db->rollback();
3608 $remise_percent = 0,
3613 $fk_remise_except =
'',
3614 $price_base_type =
'HT',
3621 $fk_parent_line = 0,
3622 $fk_fournprice =
null,
3626 $situation_percent = 100,
3631 $noupdateafterinsertline = 0
3635 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3639 global $mysoc, $conf, $langs;
3641 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);
3643 if ($this->statut == self::STATUS_DRAFT) {
3644 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3647 if (empty($remise_percent)) {
3648 $remise_percent = 0;
3653 if (empty($info_bits)) {
3659 if (empty($ventil)) {
3662 if (empty($txtva)) {
3665 if (empty($txlocaltax1)) {
3668 if (empty($txlocaltax2)) {
3671 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3672 $fk_parent_line = 0;
3674 if (empty($fk_prev_id)) {
3675 $fk_prev_id =
'null';
3677 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3678 $situation_percent = 100;
3680 if (empty($ref_ext)) {
3684 $remise_percent =
price2num($remise_percent);
3687 $pu_ht_devise =
price2num($pu_ht_devise);
3690 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3696 if ($price_base_type ==
'HT') {
3707 if ($date_start && $date_end && $date_start > $date_end) {
3708 $langs->load(
"errors");
3709 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3715 $product_type = $type;
3716 if (!empty($fk_product) && $fk_product > 0) {
3718 $result = $product->fetch($fk_product);
3719 $product_type = $product->type;
3721 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
3722 $langs->load(
"errors");
3723 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3724 $this->
db->rollback();
3734 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3735 $vat_src_code = $reg[1];
3736 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3744 $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);
3746 $total_ht = $tabprice[0];
3747 $total_tva = $tabprice[1];
3748 $total_ttc = $tabprice[2];
3749 $total_localtax1 = $tabprice[9];
3750 $total_localtax2 = $tabprice[10];
3751 $pu_ht = $tabprice[3];
3754 $multicurrency_total_ht = $tabprice[16];
3755 $multicurrency_total_tva = $tabprice[17];
3756 $multicurrency_total_ttc = $tabprice[18];
3757 $pu_ht_devise = $tabprice[19];
3761 if ($ranktouse == -1) {
3762 $rangmax = $this->
line_max($fk_parent_line);
3763 $ranktouse = $rangmax + 1;
3769 $this->line->context = $this->context;
3771 $this->line->fk_facture = $this->id;
3772 $this->line->label = $label;
3773 $this->line->desc = $desc;
3774 $this->line->ref_ext = $ref_ext;
3776 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs($qty) : $qty);
3777 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
3779 $this->line->vat_src_code = $vat_src_code;
3780 $this->line->tva_tx = $txtva;
3781 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3782 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3783 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
3784 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
3786 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
3787 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
3788 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
3789 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
3790 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
3792 $this->line->fk_product = $fk_product;
3793 $this->line->product_type = $product_type;
3794 $this->line->remise_percent = $remise_percent;
3795 $this->line->date_start = $date_start;
3796 $this->line->date_end = $date_end;
3797 $this->line->ventil = $ventil;
3798 $this->line->rang = $ranktouse;
3799 $this->line->info_bits = $info_bits;
3800 $this->line->fk_remise_except = $fk_remise_except;
3802 $this->line->special_code = $special_code;
3803 $this->line->fk_parent_line = $fk_parent_line;
3804 $this->line->origin = $origin;
3805 $this->line->origin_id = $origin_id;
3806 $this->line->situation_percent = $situation_percent;
3807 $this->line->fk_prev_id = $fk_prev_id;
3808 $this->line->fk_unit = $fk_unit;
3811 $this->line->fk_fournprice = $fk_fournprice;
3812 $this->line->pa_ht = $pa_ht;
3815 $this->line->fk_multicurrency = $this->fk_multicurrency;
3816 $this->line->multicurrency_code = $this->multicurrency_code;
3817 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
3819 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
3820 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
3821 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
3823 if (is_array($array_options) && count($array_options) > 0) {
3824 $this->line->array_options = $array_options;
3827 $result = $this->line->insert();
3830 if (!empty($fk_parent_line)) {
3832 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
3833 $linecount = count($this->lines);
3834 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
3840 if (empty($noupdateafterinsertline)) {
3845 $this->
db->commit();
3846 return $this->line->id;
3848 $this->error = $this->
db->lasterror();
3849 $this->
db->rollback();
3853 $this->error = $this->line->error;
3854 $this->errors = $this->line->errors;
3855 $this->
db->rollback();
3859 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
3895 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)
3897 global $conf, $user;
3900 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3903 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3905 global $mysoc, $langs;
3907 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);
3909 if ($this->statut == self::STATUS_DRAFT) {
3912 if (!$this->error) {
3913 $this->error = $langs->trans(
'invoiceLineProgressError');
3919 if ($date_start && $date_end && $date_start > $date_end) {
3920 $langs->load(
"errors");
3921 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3931 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3932 $fk_parent_line = 0;
3934 if (empty($special_code) || $special_code == 3) {
3937 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3938 $situation_percent = 100;
3940 if (empty($ref_ext)) {
3944 $remise_percent =
price2num($remise_percent);
3947 $pu_ht_devise =
price2num($pu_ht_devise);
3949 if (!preg_match(
'/\((.*)\)/', $txtva)) {
3969 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3970 $vat_src_code = $reg[1];
3971 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3974 $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);
3976 $total_ht = $tabprice[0];
3977 $total_tva = $tabprice[1];
3978 $total_ttc = $tabprice[2];
3979 $total_localtax1 = $tabprice[9];
3980 $total_localtax2 = $tabprice[10];
3981 $pu_ht = $tabprice[3];
3982 $pu_tva = $tabprice[4];
3983 $pu_ttc = $tabprice[5];
3986 $multicurrency_total_ht = $tabprice[16];
3987 $multicurrency_total_tva = $tabprice[17];
3988 $multicurrency_total_ttc = $tabprice[18];
3989 $pu_ht_devise = $tabprice[19];
3994 if ($remise_percent > 0) {
3995 $remise = round(($pu * $remise_percent / 100), 2);
3996 $price = ($pu - $remise);
4002 $line->fetch($rowid);
4003 $line->fetch_optionals();
4005 if (!empty($line->fk_product)) {
4007 $result = $product->fetch($line->fk_product);
4008 $product_type = $product->type;
4010 if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
4011 $langs->load(
"errors");
4012 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4013 $this->
db->rollback();
4018 $staticline = clone $line;
4020 $line->oldline = $staticline;
4021 $this->line = $line;
4022 $this->line->context = $this->context;
4023 $this->line->rang = $rang;
4026 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4027 $rangmax = $this->
line_max($fk_parent_line);
4028 $this->line->rang = $rangmax + 1;
4031 $this->line->id = $rowid;
4032 $this->line->rowid = $rowid;
4033 $this->line->label = $label;
4034 $this->line->desc = $desc;
4035 $this->line->ref_ext = $ref_ext;
4036 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty);
4038 $this->line->vat_src_code = $vat_src_code;
4039 $this->line->tva_tx = $txtva;
4040 $this->line->localtax1_tx = $txlocaltax1;
4041 $this->line->localtax2_tx = $txlocaltax2;
4042 $this->line->localtax1_type = empty($localtaxes_type[0]) ?
'' : $localtaxes_type[0];
4043 $this->line->localtax2_type = empty($localtaxes_type[2]) ?
'' : $localtaxes_type[2];
4045 $this->line->remise_percent = $remise_percent;
4046 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht);
4047 $this->line->date_start = $date_start;
4048 $this->line->date_end = $date_end;
4049 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht);
4050 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
4051 $this->line->total_localtax1 = $total_localtax1;
4052 $this->line->total_localtax2 = $total_localtax2;
4053 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
4054 $this->line->info_bits = $info_bits;
4055 $this->line->special_code = $special_code;
4056 $this->line->product_type = $type;
4057 $this->line->fk_parent_line = $fk_parent_line;
4058 $this->line->skip_update_total = $skip_update_total;
4059 $this->line->situation_percent = $situation_percent;
4060 $this->line->fk_unit = $fk_unit;
4062 $this->line->fk_fournprice = $fk_fournprice;
4063 $this->line->pa_ht = $pa_ht;
4066 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise);
4067 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht);
4068 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
4069 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4071 if (is_array($array_options) && count($array_options) > 0) {
4073 foreach ($array_options as $key => $value) {
4074 $this->line->array_options[$key] = $array_options[$key];
4078 $result = $this->line->update($user, $notrigger);
4081 if (!empty($fk_parent_line)) {
4087 $this->
db->commit();
4090 $this->error = $this->line->error;
4091 $this->
db->rollback();
4095 $this->error =
"Invoice statut makes operation forbidden";
4109 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4110 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4111 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4113 $result = $this->
db->query($sql);
4115 $this->error = $this->
db->error();
4119 $obj = $this->
db->fetch_object($result);
4121 if ($obj ===
null) {
4124 return $situation_percent < $obj->situation_percent;
4140 global $mysoc, $user;
4143 if (($line->info_bits & 2) == 2) {
4147 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4150 if ($percent > 100) {
4153 $line->situation_percent = $percent;
4154 $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);
4155 $line->total_ht = $tabprice[0];
4156 $line->total_tva = $tabprice[1];
4157 $line->total_ttc = $tabprice[2];
4158 $line->total_localtax1 = $tabprice[9];
4159 $line->total_localtax2 = $tabprice[10];
4160 $line->multicurrency_total_ht = $tabprice[16];
4161 $line->multicurrency_total_tva = $tabprice[17];
4162 $line->multicurrency_total_ttc = $tabprice[18];
4163 $line->update($user);
4166 if ($update_price) {
4181 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4183 if ($this->statut != self::STATUS_DRAFT) {
4184 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4191 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
4192 $sql .=
' SET fk_facture_line = NULL';
4193 $sql .=
' WHERE fk_facture_line = '.((int) $rowid);
4195 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
4196 $result = $this->
db->query($sql);
4198 $this->error = $this->
db->error();
4199 $this->
db->rollback();
4205 $line->context = $this->context;
4208 $result = $line->fetch($rowid);
4209 if (!($result > 0)) {
4213 if ($line->delete($user) > 0) {
4217 $this->
db->commit();
4220 $this->
db->rollback();
4221 $this->error = $this->
db->lasterror();
4225 $this->
db->rollback();
4226 $this->error = $line->error;
4245 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4246 return $this->
setDiscount($user, $remise, $notrigger);
4260 if (empty($remise)) {
4264 if ($user->rights->facture->creer) {
4271 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4272 $sql .=
' SET remise_percent = '.((float) $remise);
4273 $sql .=
" WHERE rowid = ".((int) $this->
id);
4274 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4279 $this->errors[] = $this->
db->error();
4283 if (!$notrigger && empty($error)) {
4293 $this->remise_percent = $remise;
4296 $this->
db->commit();
4299 foreach ($this->errors as $errmsg) {
4300 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4301 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4303 $this->
db->rollback();
4322 if (empty($remise)) {
4326 if ($user->rights->facture->creer) {
4333 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
4334 $sql .=
' SET remise_absolue = '.((float) $remise);
4335 $sql .=
" WHERE rowid = ".((int) $this->
id);
4336 $sql .=
' AND fk_statut = '.self::STATUS_DRAFT;
4341 $this->errors[] = $this->
db->error();
4346 $this->oldcopy = clone $this;
4347 $this->remise_absolue = $remise;
4351 if (!$notrigger && empty($error)) {
4361 $this->
db->commit();
4364 foreach ($this->errors as $errmsg) {
4365 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4366 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4368 $this->
db->rollback();
4384 global $conf, $langs;
4386 if ($this->module_source ==
'takepos') {
4387 $langs->load(
'cashdesk');
4389 $moduleName =
'takepos';
4390 $moduleSourceName =
'Takepos';
4391 $addonConstName =
'TAKEPOS_REF_ADDON';
4394 if (empty($conf->global->TAKEPOS_REF_ADDON)) {
4395 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4398 $addon = $conf->global->TAKEPOS_REF_ADDON;
4400 $langs->load(
'bills');
4402 $moduleName =
'facture';
4403 $moduleSourceName =
'Invoice';
4404 $addonConstName =
'FACTURE_ADDON';
4407 if (empty($conf->global->FACTURE_ADDON)) {
4408 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4409 } elseif ($conf->global->FACTURE_ADDON ==
'terre') {
4410 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4411 } elseif ($conf->global->FACTURE_ADDON ==
'mercure') {
4412 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4415 $addon = $conf->global->FACTURE_ADDON;
4418 if (!empty($addon)) {
4419 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = ".$conf->global->FACTURE_ADDON.
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4423 $file = $addon.
'.php';
4424 $classname = $addon;
4428 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4429 foreach ($dirmodels as $reldir) {
4430 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4433 if (is_file($dir.$file) && is_readable($dir.$file)) {
4434 $mybool |= include_once $dir.$file;
4440 $file = $addon.
'/'.$addon.
'.modules.php';
4441 $classname =
'mod_'.$moduleName.
'_'.$addon;
4442 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4444 foreach ($conf->file->dol_document_root as $dirroot) {
4445 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4448 if (is_file($dir.$file) && is_readable($dir.$file)) {
4449 $mybool |= include_once $dir.$file;
4459 $obj =
new $classname();
4461 $numref = $obj->getNextValue($soc, $this, $mode);
4468 if ($mode !=
'last' && !$numref) {
4469 $this->error = $obj->error;
4475 $langs->load(
'errors');
4476 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4489 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4490 $sql .=
' date_closing as dateclosing,';
4491 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4492 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4493 $sql .=
' WHERE c.rowid = '.((int) $id);
4495 $result = $this->
db->query($sql);
4497 if ($this->
db->num_rows($result)) {
4498 $obj = $this->
db->fetch_object($result);
4499 $this->
id = $obj->rowid;
4500 if ($obj->fk_user_author) {
4501 $cuser =
new User($this->
db);
4502 $cuser->fetch($obj->fk_user_author);
4503 $this->user_creation = $cuser;
4505 if ($obj->fk_user_valid) {
4506 $vuser =
new User($this->
db);
4507 $vuser->fetch($obj->fk_user_valid);
4508 $this->user_validation = $vuser;
4510 if ($obj->fk_user_closing) {
4511 $cluser =
new User($this->
db);
4512 $cluser->fetch($obj->fk_user_closing);
4513 $this->user_closing = $cluser;
4516 $this->date_creation = $this->
db->jdate($obj->datec);
4517 $this->date_modification = $this->
db->jdate($obj->datem);
4518 $this->date_validation = $this->
db->jdate($obj->datev);
4519 $this->date_closing = $this->
db->jdate($obj->dateclosing);
4521 $this->
db->free($result);
4542 public function liste_array($shortlist = 0, $draft = 0, $excluser =
'', $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4545 global $conf, $user;
4549 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4550 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4551 if (empty($user->rights->societe->client->voir) && !$socid) {
4552 $sql .=
", sc.fk_soc, sc.fk_user";
4554 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4555 if (empty($user->rights->societe->client->voir) && !$socid) {
4556 $sql .=
", ".MAIN_DB_PREFIX.
"societe_commerciaux as sc";
4558 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4559 $sql .=
" AND f.fk_soc = s.rowid";
4560 if (empty($user->rights->societe->client->voir) && !$socid) {
4561 $sql .=
" AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
4564 $sql .=
" AND s.rowid = ".((int) $socid);
4567 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4569 if (is_object($excluser)) {
4570 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4572 $sql .= $this->
db->order($sortfield, $sortorder);
4573 $sql .= $this->
db->plimit($limit, $offset);
4575 $result = $this->
db->query($sql);
4577 $numc = $this->
db->num_rows($result);
4580 while ($i < $numc) {
4581 $obj = $this->
db->fetch_object($result);
4583 if ($shortlist == 1) {
4584 $ga[$obj->fid] = $obj->ref;
4585 } elseif ($shortlist == 2) {
4586 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4588 $ga[$i][
'id'] = $obj->fid;
4589 $ga[$i][
'ref'] = $obj->ref;
4590 $ga[$i][
'name'] = $obj->name;
4619 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4620 $sql .=
" ff.rowid as rowidnext";
4622 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4623 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4624 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4625 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4626 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4627 $sql .=
" AND f.paye = 0";
4628 $sql .=
" AND pf.fk_paiement IS NULL";
4629 $sql .=
" AND ff.fk_statut IS NULL";
4631 $sql .=
" AND f.fk_soc = ".((int) $socid);
4634 $sql .=
" ORDER BY f.ref";
4636 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4639 while ($obj = $this->
db->fetch_object(
$resql)) {
4640 $return[$obj->rowid] = array(
4641 'id' => $obj->rowid,
4643 'status' => $obj->status,
4644 'paid' => $obj->paid,
4651 $this->error = $this->
db->error();
4674 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
4675 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4676 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4677 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4678 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4679 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4683 $sql .=
" AND ff.type IS NULL";
4684 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4686 if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
4688 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4689 $sql .=
'(SELECT MAX(fs.rowid)';
4690 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4691 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4692 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4693 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4695 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4697 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4700 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4704 $sql .=
" AND f.fk_soc = ".((int) $socid);
4706 $sql .=
" ORDER BY f.ref";
4708 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4711 while ($obj = $this->
db->fetch_object(
$resql)) {
4713 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4716 if ($obj->fk_statut == self::STATUS_CLOSED) {
4721 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4722 $return[$obj->rowid] = array(
'ref'=>$obj->ref,
'status'=>$obj->fk_statut,
'type'=>$obj->type,
'paye'=>$obj->paye,
'paymentornot'=>$paymentornot);
4728 $this->error = $this->
db->error();
4744 global $conf, $langs;
4748 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut, f.total_ht";
4749 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4750 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4751 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4752 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4755 $sql .= $clause.
" f.paye=0";
4756 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4757 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
4759 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
4764 $langs->load(
"bills");
4768 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4769 $response->label = $langs->trans(
"CustomerBillsUnpaid");
4770 $response->labelShort = $langs->trans(
"Unpaid");
4771 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4774 $generic_facture =
new Facture($this->
db);
4776 while ($obj = $this->
db->fetch_object(
$resql)) {
4777 $generic_facture->date_lim_reglement = $this->
db->jdate($obj->datefin);
4778 $generic_facture->statut = $obj->fk_statut;
4780 $response->nbtodo++;
4781 $response->total += $obj->total_ht;
4783 if ($generic_facture->hasDelay()) {
4784 $response->nbtodolate++;
4785 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4793 $this->error = $this->
db->error();
4832 global $conf, $langs, $user;
4836 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
4841 $sql =
"SELECT rowid";
4842 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
4843 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
4844 $sql .= $this->
db->plimit(100);
4848 $num_prods = $this->
db->num_rows(
$resql);
4850 while ($i < $num_prods) {
4852 $row = $this->
db->fetch_row(
$resql);
4853 $prodids[$i] = $row[0];
4857 if (empty($num_prods)) {
4864 $this->
ref =
'SPECIMEN';
4865 $this->specimen = 1;
4867 $this->date = $nownotime;
4868 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
4869 $this->cond_reglement_id = 1;
4870 $this->cond_reglement_code =
'RECEP';
4872 $this->mode_reglement_id = 0;
4873 $this->mode_reglement_code =
'';
4875 $this->note_public =
'This is a comment (public)';
4876 $this->note_private =
'This is a comment (private)';
4877 $this->note =
'This is a comment (private)';
4879 $this->fk_user_author = $user->id;
4881 $this->multicurrency_tx = 1;
4882 $this->multicurrency_code = $conf->currency;
4884 $this->fk_incoterms = 0;
4885 $this->location_incoterms =
'';
4887 if (empty($option) || $option !=
'nolines') {
4891 while ($xnbp < $nbp) {
4893 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
4895 $line->subprice = 100;
4896 $line->tva_tx = 19.6;
4897 $line->localtax1_tx = 0;
4898 $line->localtax2_tx = 0;
4899 $line->remise_percent = 0;
4901 $prodid = mt_rand(1, $num_prods);
4902 $line->fk_product = $prodids[$prodid];
4904 $line->total_ht = -100;
4905 $line->total_ttc = -119.6;
4906 $line->total_tva = -19.6;
4907 $line->multicurrency_total_ht = -200;
4908 $line->multicurrency_total_ttc = -239.2;
4909 $line->multicurrency_total_tva = -39.2;
4910 } elseif ($xnbp == 2) {
4911 $line->subprice = -100;
4912 $line->total_ht = -100;
4913 $line->total_ttc = -119.6;
4914 $line->total_tva = -19.6;
4915 $line->remise_percent = 0;
4916 $line->multicurrency_total_ht = -200;
4917 $line->multicurrency_total_ttc = -239.2;
4918 $line->multicurrency_total_tva = -39.2;
4919 } elseif ($xnbp == 3) {
4920 $prodid = mt_rand(1, $num_prods);
4921 $line->fk_product = $prodids[$prodid];
4922 $line->total_ht = 50;
4923 $line->total_ttc = 59.8;
4924 $line->total_tva = 9.8;
4925 $line->multicurrency_total_ht = 100;
4926 $line->multicurrency_total_ttc = 119.6;
4927 $line->multicurrency_total_tva = 19.6;
4928 $line->remise_percent = 50;
4931 $prodid = mt_rand(1, $num_prods);
4932 $line->fk_product = $prodids[$prodid];
4933 $line->total_ht = 100;
4934 $line->total_ttc = 119.6;
4935 $line->total_tva = 19.6;
4936 $line->multicurrency_total_ht = 200;
4937 $line->multicurrency_total_ttc = 239.2;
4938 $line->multicurrency_total_tva = 39.2;
4939 $line->remise_percent = 0;
4942 $this->lines[$xnbp] = $line;
4945 $this->total_ht += $line->total_ht;
4946 $this->total_tva += $line->total_tva;
4947 $this->total_ttc += $line->total_ttc;
4949 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
4950 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
4951 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
4955 $this->revenuestamp = 0;
4959 $line->desc = $langs->trans(
"Description").
" (offered line)";
4961 $line->subprice = 100;
4962 $line->tva_tx = 19.6;
4963 $line->localtax1_tx = 0;
4964 $line->localtax2_tx = 0;
4965 $line->remise_percent = 100;
4966 $line->total_ht = 0;
4967 $line->total_ttc = 0;
4968 $line->total_tva = 0;
4969 $line->multicurrency_total_ht = 0;
4970 $line->multicurrency_total_ttc = 0;
4971 $line->multicurrency_total_tva = 0;
4972 $prodid = mt_rand(1, $num_prods);
4973 $line->fk_product = $prodids[$prodid];
4975 $this->lines[$xnbp] = $line;
4989 global $conf, $user;
4991 $this->nb = array();
4995 $sql =
"SELECT count(f.rowid) as nb";
4996 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4997 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
4998 if (empty($user->rights->societe->client->voir) && !$user->socid) {
4999 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5000 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5003 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
5007 while ($obj = $this->
db->fetch_object(
$resql)) {
5008 $this->nb[
"invoices"] = $obj->nb;
5014 $this->error = $this->
db->error();
5040 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5042 global $conf, $langs;
5044 $outputlangs->loadLangs(array(
"bills",
"products"));
5048 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5050 if (!empty($this->model_pdf)) {
5051 $modele = $this->model_pdf;
5052 } elseif (!empty($this->modelpdf)) {
5053 $modele = $this->modelpdf;
5054 } elseif (!empty($conf->global->$thisTypeConfName)) {
5055 $modele = $conf->global->$thisTypeConfName;
5056 } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
5057 $modele = $conf->global->FACTURE_ADDON_PDF;
5061 $modelpath =
"core/modules/facture/doc/";
5063 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5073 $sql =
'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.
'facture as f';
5074 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5077 if ($this->
db->num_rows(
$resql) > 0) {
5078 $res = $this->
db->fetch_array(
$resql);
5079 $ref = $res[
'max(situation_cycle_ref)'];
5087 $this->error = $this->
db->lasterror();
5088 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5102 return ($this->situation_counter == 1);
5116 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5117 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5118 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5119 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5123 while ($row = $this->
db->fetch_object(
$resql)) {
5126 $situation->fetch($id);
5127 $res[] = $situation;
5130 $this->error = $this->
db->error();
5131 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5151 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5156 $this->errors[] = $this->
db->error();
5160 if (!$notrigger && empty($error)) {
5170 $this->
db->commit();
5173 foreach ($this->errors as $errmsg) {
5174 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5175 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5177 $this->
db->rollback();
5193 if (!empty($this->situation_cycle_ref)) {
5195 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5196 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5197 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5201 $res = $this->
db->fetch_array(
$resql);
5202 $last = $res[
'max(situation_counter)'];
5203 return ($last == $this->situation_counter);
5205 $this->error = $this->
db->lasterror();
5206 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5264 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5265 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5267 $totalpaid = floatval($totalpaid);
5269 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5270 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5272 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5295 $displayWarranty =
false;
5296 if (!empty($this->retained_warranty)) {
5297 $displayWarranty =
true;
5301 $displayWarranty =
false;
5302 if (!empty($this->situation_final)) {
5303 $displayWarranty =
true;
5306 $displayWarranty =
true;
5308 foreach ($this->lines as $i => $line) {
5309 if ($line->product_type < 2 && $line->situation_percent < 100) {
5310 $displayWarranty =
false;
5318 return $displayWarranty;
5328 if (empty($this->retained_warranty)) {
5332 $retainedWarrantyAmount = 0;
5336 $displayWarranty =
true;
5338 if (!empty($this->lines)) {
5339 foreach ($this->lines as $i => $line) {
5340 if ($line->product_type < 2 && $line->situation_percent < 100) {
5341 $displayWarranty =
false;
5347 if ($displayWarranty && !empty($this->situation_final)) {
5349 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5352 foreach ($TPreviousIncoice as &$fac) {
5353 $total2BillWT += $fac->total_ttc;
5355 $total2BillWT += $this->total_ttc;
5357 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5363 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5366 if ($rounding < 0) {
5367 $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5370 if ($rounding > 0) {
5371 return round($retainedWarrantyAmount, $rounding);
5374 return $retainedWarrantyAmount;
5385 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5387 if ($this->statut >= 0) {
5388 $fieldname =
'retained_warranty';
5389 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5390 $sql .=
" SET ".$fieldname.
" = ".((
float) $value);
5391 $sql .=
' WHERE rowid='.((int) $this->
id);
5393 if ($this->
db->query($sql)) {
5394 $this->retained_warranty = floatval($value);
5397 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5398 $this->error = $this->
db->error();
5402 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5403 $this->error =
'Status of the object is incompatible '.$this->statut;
5418 if (!$timestamp && $dateYmd) {
5419 $timestamp = $this->
db->jdate($dateYmd);
5423 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5424 if ($this->statut >= 0) {
5425 $fieldname =
'retained_warranty_date_limit';
5426 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5427 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5428 $sql .=
' WHERE rowid = '.((int) $this->
id);
5430 if ($this->
db->query($sql)) {
5431 $this->retained_warranty_date_limit = $timestamp;
5434 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5435 $this->error = $this->
db->error();
5439 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5440 $this->error =
'Status of the object is incompatible '.$this->statut;
5457 global $conf, $langs, $user;
5463 $errorsMsg = array();
5465 $langs->load(
"bills");
5468 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5478 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5479 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5480 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5491 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5492 if (!empty($paymentmode) && $paymentmode !=
'all') {
5493 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5495 $sql .=
" WHERE f.paye = 0";
5496 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5497 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5498 $sql .=
" AND f.entity IN (".getEntity(
'facture').
")";
5499 if (!empty($paymentmode) && $paymentmode !=
'all') {
5500 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5503 $sql .= $this->
db->order(
"date_lim_reglement",
"ASC");
5508 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5509 if (!empty($paymentmode) && $paymentmode !=
'all') {
5510 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5512 $this->output .=
'<br>';
5515 while ($obj = $this->
db->fetch_object(
$resql)) {
5518 $res = $tmpinvoice->fetch($obj->id);
5520 $tmpinvoice->fetch_thirdparty();
5522 $outputlangs =
new Translate(
'', $conf);
5523 if ($tmpinvoice->thirdparty->default_lang) {
5524 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5525 $outputlangs->loadLangs(array(
"main",
"bills"));
5527 $outputlangs = $langs;
5531 $arraymessage = $formmail->getEMailTemplate($this->
db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5532 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5533 $langs->load(
"errors");
5534 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5547 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5550 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5556 $res = $tmpinvoice->fetch_thirdparty();
5557 $recipient = $tmpinvoice->thirdparty;
5559 if (!empty($recipient->email)) {
5560 $to = $recipient->email;
5562 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for user.";
5566 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5571 $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
5573 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5577 if (!$error && $to) {
5581 $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
5583 $trackid =
'inv'.$tmpinvoice->id;
5584 $sendcontext =
'standard';
5587 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(),
'',
"", 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5590 if ($cMailFile->sendfile()) {
5594 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5599 $actioncomm->type_code =
'AC_OTH_AUTO';
5600 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5601 $actioncomm->contact_id = 0;
5603 $actioncomm->code =
'AC_EMAIL';
5604 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK';
5605 $actioncomm->note_private = $sendContent;
5606 $actioncomm->fk_project = $tmpinvoice->fk_project;
5607 $actioncomm->datep =
dol_now();
5608 $actioncomm->datef = $actioncomm->datep;
5609 $actioncomm->percentage = -1;
5610 $actioncomm->authorid = $user->id;
5611 $actioncomm->userownerid = $user->id;
5613 $actioncomm->email_msgid = $cMailFile->msgid;
5614 $actioncomm->email_from = $from;
5615 $actioncomm->email_sender =
'';
5616 $actioncomm->email_to = $to;
5620 $actioncomm->errors_to = $errors_to;
5624 $actioncomm->create($user);
5626 $errormesg = $cMailFile->error.
' : '.$to;
5630 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5635 $actioncomm->type_code =
'AC_OTH_AUTO';
5636 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5637 $actioncomm->contact_id = 0;
5639 $actioncomm->code =
'AC_EMAIL';
5640 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5641 $actioncomm->note_private = $errormesg;
5642 $actioncomm->fk_project = $tmpinvoice->fk_project;
5643 $actioncomm->datep =
dol_now();
5644 $actioncomm->datef = $actioncomm->datep;
5645 $actioncomm->percentage = -1;
5646 $actioncomm->authorid = $user->id;
5647 $actioncomm->userownerid = $user->id;
5649 $actioncomm->email_msgid = $cMailFile->msgid;
5650 $actioncomm->email_from = $from;
5651 $actioncomm->email_sender =
'';
5652 $actioncomm->email_to = $to;
5656 $actioncomm->errors_to = $errors_to;
5660 $actioncomm->create($user);
5663 $this->
db->commit();
5667 $errorsMsg[] = $errormesg;
5670 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
5680 $this->output .=
'Nb of emails sent : '.$nbMailSend;
5683 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg)) ? join(
', ', $errorsMsg) : $error;
5697 $sql =
"SELECT datef";
5698 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
5699 $sql .=
" WHERE type = " . (int) $this->
type ;
5700 $sql .=
" AND date_valid IS NOT NULL";
5701 $sql .=
" ORDER BY datef DESC LIMIT 1";
5703 $result = $this->
db->query($sql);
5706 if ($this->
db->num_rows($result)) {
5707 $obj = $this->
db->fetch_object($result);
5708 $last_date = $this->
db->jdate($obj->datef);
5709 $invoice_date = $this->date;
5711 $is_last_of_same_type = $invoice_date >= $last_date;
5712 if ($allow_validated_drafts) {
5713 $is_last_of_same_type = $is_last_of_same_type || (!strpos($this->
ref,
'PROV') && $this->status ==
self::STATUS_DRAFT);
5716 return array($is_last_of_same_type, $last_date);
5736 public $element =
'facturedet';
5741 public $table_element =
'facturedet';
5755 public $localtax1_type;
5756 public $localtax2_type;
5757 public $fk_remise_except;
5760 public $fk_fournprice;
5765 public $remise_percent;
5767 public $special_code;
5775 public $fk_code_ventilation = 0;
5780 public $skip_update_total;
5785 public $situation_percent;
5793 public $fk_multicurrency;
5794 public $multicurrency_code;
5795 public $multicurrency_subprice;
5796 public $multicurrency_total_ht;
5797 public $multicurrency_total_tva;
5798 public $multicurrency_total_ttc;
5808 $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,';
5809 $sql .=
' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
5810 $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,';
5811 $sql .=
' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
5812 $sql .=
' fd.fk_code_ventilation,';
5813 $sql .=
' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
5814 $sql .=
' fd.situation_percent, fd.fk_prev_id,';
5815 $sql .=
' fd.multicurrency_subprice,';
5816 $sql .=
' fd.multicurrency_total_ht,';
5817 $sql .=
' fd.multicurrency_total_tva,';
5818 $sql .=
' fd.multicurrency_total_ttc,';
5819 $sql .=
' p.ref as product_ref, p.label as product_label, p.description as product_desc';
5820 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as fd';
5821 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON fd.fk_product = p.rowid';
5822 $sql .=
' WHERE fd.rowid = '.((int) $rowid);
5824 $result = $this->
db->query($sql);
5826 $objp = $this->
db->fetch_object($result);
5828 $this->
rowid = $objp->rowid;
5829 $this->
id = $objp->rowid;
5830 $this->fk_facture = $objp->fk_facture;
5831 $this->fk_parent_line = $objp->fk_parent_line;
5832 $this->label = $objp->custom_label;
5833 $this->desc = $objp->description;
5834 $this->qty = $objp->qty;
5835 $this->subprice = $objp->subprice;
5836 $this->ref_ext = $objp->ref_ext;
5837 $this->vat_src_code = $objp->vat_src_code;
5838 $this->tva_tx = $objp->tva_tx;
5839 $this->localtax1_tx = $objp->localtax1_tx;
5840 $this->localtax2_tx = $objp->localtax2_tx;
5841 $this->remise_percent = $objp->remise_percent;
5842 $this->fk_remise_except = $objp->fk_remise_except;
5843 $this->fk_product = $objp->fk_product;
5844 $this->product_type = $objp->product_type;
5845 $this->date_start = $this->
db->jdate($objp->date_start);
5846 $this->date_end = $this->
db->jdate($objp->date_end);
5847 $this->info_bits = $objp->info_bits;
5848 $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
5849 $this->special_code = $objp->special_code;
5850 $this->total_ht = $objp->total_ht;
5851 $this->total_tva = $objp->total_tva;
5852 $this->total_localtax1 = $objp->total_localtax1;
5853 $this->total_localtax2 = $objp->total_localtax2;
5854 $this->total_ttc = $objp->total_ttc;
5855 $this->fk_code_ventilation = $objp->fk_code_ventilation;
5856 $this->rang = $objp->rang;
5857 $this->fk_fournprice = $objp->fk_fournprice;
5858 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
5859 $this->pa_ht = $marginInfos[0];
5860 $this->marge_tx = $marginInfos[1];
5861 $this->marque_tx = $marginInfos[2];
5863 $this->
ref = $objp->product_ref;
5865 $this->product_ref = $objp->product_ref;
5866 $this->product_label = $objp->product_label;
5867 $this->product_desc = $objp->product_desc;
5869 $this->fk_unit = $objp->fk_unit;
5870 $this->fk_user_modif = $objp->fk_user_modif;
5871 $this->fk_user_author = $objp->fk_user_author;
5873 $this->situation_percent = $objp->situation_percent;
5874 $this->fk_prev_id = $objp->fk_prev_id;
5876 $this->multicurrency_subprice = $objp->multicurrency_subprice;
5877 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
5878 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
5879 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
5881 $this->
db->free($result);
5885 $this->error = $this->
db->lasterror();
5897 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
5899 global $langs, $user, $conf;
5903 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
5905 dol_syslog(get_class($this).
"::insert rang=".$this->rang, LOG_DEBUG);
5908 $this->desc = trim($this->desc);
5909 if (empty($this->tva_tx)) {
5912 if (empty($this->localtax1_tx)) {
5913 $this->localtax1_tx = 0;
5915 if (empty($this->localtax2_tx)) {
5916 $this->localtax2_tx = 0;
5918 if (empty($this->localtax1_type)) {
5919 $this->localtax1_type = 0;
5921 if (empty($this->localtax2_type)) {
5922 $this->localtax2_type = 0;
5924 if (empty($this->total_localtax1)) {
5925 $this->total_localtax1 = 0;
5927 if (empty($this->total_localtax2)) {
5928 $this->total_localtax2 = 0;
5930 if (empty($this->rang)) {
5933 if (empty($this->remise_percent)) {
5934 $this->remise_percent = 0;
5936 if (empty($this->info_bits)) {
5937 $this->info_bits = 0;
5939 if (empty($this->subprice)) {
5940 $this->subprice = 0;
5942 if (empty($this->ref_ext)) {
5943 $this->ref_ext =
'';
5945 if (empty($this->special_code)) {
5946 $this->special_code = 0;
5948 if (empty($this->fk_parent_line)) {
5949 $this->fk_parent_line = 0;
5951 if (empty($this->fk_prev_id)) {
5952 $this->fk_prev_id = 0;
5954 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
5955 $this->situation_percent = 100;
5958 if (empty($this->pa_ht)) {
5961 if (empty($this->multicurrency_subprice)) {
5962 $this->multicurrency_subprice = 0;
5964 if (empty($this->multicurrency_total_ht)) {
5965 $this->multicurrency_total_ht = 0;
5967 if (empty($this->multicurrency_total_tva)) {
5968 $this->multicurrency_total_tva = 0;
5970 if (empty($this->multicurrency_total_ttc)) {
5971 $this->multicurrency_total_ttc = 0;
5975 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
5976 if (($result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
5979 $this->pa_ht = $result;
5984 if ($this->product_type < 0) {
5985 $this->error =
'ErrorProductTypeMustBe0orMore';
5988 if (!empty($this->fk_product) && $this->fk_product > 0) {
5992 $this->error =
'ErrorProductIdDoesNotExists';
5993 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6001 $sql =
'INSERT INTO '.MAIN_DB_PREFIX.
'facturedet';
6002 $sql .=
' (fk_facture, fk_parent_line, label, description, qty,';
6003 $sql .=
' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6004 $sql .=
' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6005 $sql .=
' date_start, date_end, fk_code_ventilation, ';
6006 $sql .=
' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6007 $sql .=
' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6008 $sql .=
' situation_percent, fk_prev_id,';
6009 $sql .=
' fk_unit, fk_user_author, fk_user_modif,';
6010 $sql .=
' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
6012 $sql .=
" VALUES (".$this->fk_facture.
",";
6013 $sql .=
" ".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null").
",";
6014 $sql .=
" ".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null").
",";
6015 $sql .=
" '".$this->db->escape($this->desc).
"',";
6016 $sql .=
" ".price2num($this->qty).
",";
6017 $sql .=
" ".(empty($this->vat_src_code) ?
"''" :
"'".$this->db->escape($this->vat_src_code).
"'").
",";
6018 $sql .=
" ".price2num($this->tva_tx).
",";
6019 $sql .=
" ".price2num($this->localtax1_tx).
",";
6020 $sql .=
" ".price2num($this->localtax2_tx).
",";
6021 $sql .=
" '".$this->db->escape($this->localtax1_type).
"',";
6022 $sql .=
" '".$this->db->escape($this->localtax2_type).
"',";
6023 $sql .=
' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product :
"null").
',';
6024 $sql .=
" ".((int) $this->product_type).
",";
6025 $sql .=
" ".price2num($this->remise_percent).
",";
6026 $sql .=
" ".price2num($this->subprice).
",";
6027 $sql .=
" '".$this->db->escape($this->ref_ext).
"',";
6028 $sql .=
' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except :
"null").
',';
6029 $sql .=
" ".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null").
",";
6030 $sql .=
" ".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null").
",";
6031 $sql .=
' '.((int) $this->fk_code_ventilation).
',';
6032 $sql .=
' '.((int) $this->rang).
',';
6033 $sql .=
' '.((int) $this->special_code).
',';
6034 $sql .=
' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice :
"null").
',';
6035 $sql .=
' '.price2num($this->pa_ht).
',';
6036 $sql .=
" '".$this->db->escape($this->info_bits).
"',";
6037 $sql .=
" ".price2num($this->total_ht).
",";
6038 $sql .=
" ".price2num($this->total_tva).
",";
6039 $sql .=
" ".price2num($this->total_ttc).
",";
6040 $sql .=
" ".price2num($this->total_localtax1).
",";
6041 $sql .=
" ".price2num($this->total_localtax2);
6042 $sql .=
", ".((float) $this->situation_percent);
6043 $sql .=
", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id :
"null");
6044 $sql .=
", ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6045 $sql .=
", ".((int) $user->id);
6046 $sql .=
", ".((int) $user->id);
6047 $sql .=
", ".(int) $this->fk_multicurrency;
6048 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
6049 $sql .=
", ".price2num($this->multicurrency_subprice);
6050 $sql .=
", ".price2num($this->multicurrency_total_ht);
6051 $sql .=
", ".price2num($this->multicurrency_total_tva);
6052 $sql .=
", ".price2num($this->multicurrency_total_ttc);
6055 dol_syslog(get_class($this).
"::insert", LOG_DEBUG);
6058 $this->
id = $this->
db->last_insert_id(MAIN_DB_PREFIX.
'facturedet');
6059 $this->
rowid = $this->id;
6070 if ($this->fk_remise_except) {
6072 $result = $discount->fetch($this->fk_remise_except);
6077 if ($discount->fk_facture_line > 0) {
6078 if (empty($noerrorifdiscountalreadylinked)) {
6079 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed", $discount->id);
6080 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6081 $this->
db->rollback();
6085 $result = $discount->link_to_invoice($this->
rowid, 0);
6087 $this->error = $discount->error;
6088 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6089 $this->
db->rollback();
6094 $this->error = $langs->trans(
"ErrorADiscountThatHasBeenRemovedIsIncluded");
6095 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6096 $this->
db->rollback();
6100 $this->error = $discount->error;
6101 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6102 $this->
db->rollback();
6109 $result = $this->
call_trigger(
'LINEBILL_INSERT', $user);
6111 $this->
db->rollback();
6117 $this->
db->commit();
6120 $this->error = $this->
db->lasterror();
6121 $this->
db->rollback();
6133 public function update($user =
'', $notrigger = 0)
6135 global $user, $conf;
6139 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6142 $this->desc = trim($this->desc);
6143 if (empty($this->ref_ext)) {
6144 $this->ref_ext =
'';
6146 if (empty($this->tva_tx)) {
6149 if (empty($this->localtax1_tx)) {
6150 $this->localtax1_tx = 0;
6152 if (empty($this->localtax2_tx)) {
6153 $this->localtax2_tx = 0;
6155 if (empty($this->localtax1_type)) {
6156 $this->localtax1_type = 0;
6158 if (empty($this->localtax2_type)) {
6159 $this->localtax2_type = 0;
6161 if (empty($this->total_localtax1)) {
6162 $this->total_localtax1 = 0;
6164 if (empty($this->total_localtax2)) {
6165 $this->total_localtax2 = 0;
6167 if (empty($this->remise_percent)) {
6168 $this->remise_percent = 0;
6170 if (empty($this->info_bits)) {
6171 $this->info_bits = 0;
6173 if (empty($this->special_code)) {
6174 $this->special_code = 0;
6176 if (empty($this->product_type)) {
6177 $this->product_type = 0;
6179 if (empty($this->fk_parent_line)) {
6180 $this->fk_parent_line = 0;
6182 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6183 $this->situation_percent = 100;
6185 if (empty($this->pa_ht)) {
6189 if (empty($this->multicurrency_subprice)) {
6190 $this->multicurrency_subprice = 0;
6192 if (empty($this->multicurrency_total_ht)) {
6193 $this->multicurrency_total_ht = 0;
6195 if (empty($this->multicurrency_total_tva)) {
6196 $this->multicurrency_total_tva = 0;
6198 if (empty($this->multicurrency_total_ttc)) {
6199 $this->multicurrency_total_ttc = 0;
6203 if ($this->product_type < 0) {
6208 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6210 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6214 $this->pa_ht = $result;
6221 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6222 $sql .=
" description='".$this->db->escape($this->desc).
"'";
6223 $sql .=
", ref_ext='".$this->db->escape($this->ref_ext).
"'";
6224 $sql .=
", label=".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null");
6225 $sql .=
", subprice=".price2num($this->subprice);
6226 $sql .=
", remise_percent=".price2num($this->remise_percent);
6227 if ($this->fk_remise_except) {
6228 $sql .=
", fk_remise_except=".$this->fk_remise_except;
6230 $sql .=
", fk_remise_except=null";
6232 $sql .=
", vat_src_code = '".(empty($this->vat_src_code) ?
'' : $this->
db->escape($this->vat_src_code)).
"'";
6233 $sql .=
", tva_tx=".price2num($this->tva_tx);
6234 $sql .=
", localtax1_tx=".price2num($this->localtax1_tx);
6235 $sql .=
", localtax2_tx=".price2num($this->localtax2_tx);
6236 $sql .=
", localtax1_type='".$this->db->escape($this->localtax1_type).
"'";
6237 $sql .=
", localtax2_type='".$this->db->escape($this->localtax2_type).
"'";
6238 $sql .=
", qty=".price2num($this->qty);
6239 $sql .=
", date_start=".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null");
6240 $sql .=
", date_end=".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null");
6241 $sql .=
", product_type=".$this->product_type;
6242 $sql .=
", info_bits='".$this->db->escape($this->info_bits).
"'";
6243 $sql .=
", special_code='".$this->db->escape($this->special_code).
"'";
6244 if (empty($this->skip_update_total)) {
6245 $sql .=
", total_ht=".price2num($this->total_ht);
6246 $sql .=
", total_tva=".price2num($this->total_tva);
6247 $sql .=
", total_ttc=".price2num($this->total_ttc);
6248 $sql .=
", total_localtax1=".price2num($this->total_localtax1);
6249 $sql .=
", total_localtax2=".price2num($this->total_localtax2);
6251 $sql .=
", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ?
"'".$this->db->escape($this->fk_fournprice).
"'" :
"null");
6252 $sql .=
", buy_price_ht=".(($this->pa_ht || $this->pa_ht === 0 || $this->pa_ht ===
'0') ?
price2num($this->pa_ht) :
"null");
6253 $sql .=
", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null");
6254 if (!empty($this->rang)) {
6255 $sql .=
", rang=".((int) $this->rang);
6257 $sql .=
", situation_percent = ".((float) $this->situation_percent);
6258 $sql .=
", fk_unit = ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6259 $sql .=
", fk_user_modif = ".((int) $user->id);
6262 $sql .=
", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6263 $sql .=
", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6264 $sql .=
", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6265 $sql .=
", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6267 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6269 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
6273 $this->
id = $this->rowid;
6280 if (!$error && !$notrigger) {
6282 $result = $this->
call_trigger(
'LINEBILL_MODIFY', $user);
6284 $this->
db->rollback();
6289 $this->
db->commit();
6292 $this->error = $this->
db->error();
6293 $this->
db->rollback();
6305 public function delete($tmpuser =
null, $notrigger =
false)
6312 if (empty($notrigger)) {
6313 $result = $this->
call_trigger(
'LINEBILL_DELETE', $user);
6315 $this->
db->rollback();
6324 $this->
db->rollback();
6328 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->
rowid);
6330 if ($this->
db->query($sql)) {
6331 $this->
db->commit();
6334 $this->error = $this->
db->error().
" sql=".$sql;
6335 $this->
db->rollback();
6351 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6354 if (empty($this->total_localtax1)) {
6355 $this->total_localtax1 = 0;
6357 if (empty($this->total_localtax2)) {
6358 $this->total_localtax2 = 0;
6362 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6363 $sql .=
" total_ht=".price2num($this->total_ht).
"";
6364 $sql .=
",total_tva=".price2num($this->total_tva).
"";
6365 $sql .=
",total_localtax1=".price2num($this->total_localtax1).
"";
6366 $sql .=
",total_localtax2=".price2num($this->total_localtax2).
"";
6367 $sql .=
",total_ttc=".price2num($this->total_ttc).
"";
6368 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6370 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6374 $this->
db->commit();
6377 $this->error = $this->
db->error();
6378 $this->
db->rollback();
6395 global $invoicecache;
6396 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6400 if (!isset($invoicecache[$invoiceid])) {
6401 $invoicecache[$invoiceid] =
new Facture($this->
db);
6402 $invoicecache[$invoiceid]->fetch($invoiceid);
6408 $sql =
"SELECT situation_percent FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->fk_prev_id);
6411 $res = $this->
db->fetch_array(
$resql);
6413 $returnPercent = floatval($res[
'situation_percent']);
6415 if ($include_credit_note) {
6416 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6417 $sql .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6418 $sql .=
" WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6419 $sql .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6420 $sql .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6422 $res = $this->
db->query($sql);
6424 while ($obj = $this->
db->fetch_object($res)) {
6425 $returnPercent = $returnPercent + floatval($obj->situation_percent);
6432 return $returnPercent;
6434 $this->error = $this->
db->error();
6435 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6436 $this->
db->rollback();