46require_once DOL_DOCUMENT_ROOT.
'/core/class/commoninvoice.class.php';
47require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobjectline.class.php';
48require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
49require_once DOL_DOCUMENT_ROOT.
'/societe/class/client.class.php';
50require_once DOL_DOCUMENT_ROOT.
'/margin/lib/margins.lib.php';
51require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/multicurrency.class.php';
53if (isModEnabled(
'accounting')) {
54 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formaccounting.class.php';
56if (isModEnabled(
'accounting')) {
57 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingaccount.class.php';
68 public $element =
'facture';
73 public $table_element =
'facture';
78 public $table_element_line =
'facturedet';
83 public $fk_element =
'fk_facture';
88 public $picto =
'bill';
94 public $restrictiononfksoc = 1;
105 public $fk_user_author;
111 public $fk_user_valid;
117 public $fk_user_modif;
125 public $delivery_date;
137 public $ref_customer;
141 public $total_localtax1;
142 public $total_localtax2;
144 public $revenuestamp;
161 public $linked_objects = array();
171 public $lines = array();
177 public $extraparams = array();
184 public $date_pointoftax;
190 public $situation_cycle_ref;
195 public $situation_counter;
200 public $situation_final;
205 public $tab_previous_situation_invoice = array();
210 public $tab_next_situation_invoice = array();
220 public $retained_warranty;
225 public $retained_warranty_date_limit;
230 public $retained_warranty_fk_cond_reglement;
235 public $availability_id;
237 public $date_closing;
248 public $remise_percent;
253 public $online_payment_url;
285 public $fields = array(
286 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 1),
287 'ref' => array(
'type' =>
'varchar(30)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'position' => 5),
288 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'default' =>
'1',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 20,
'index' => 1),
289 'ref_client' => array(
'type' =>
'varchar(255)',
'label' =>
'RefCustomer',
'enabled' => 1,
'visible' => -1,
'position' => 10),
290 'ref_ext' => array(
'type' =>
'varchar(255)',
'label' =>
'Ref ext',
'enabled' => 1,
'visible' => 0,
'position' => 12),
291 'type' => array(
'type' =>
'smallint(6)',
'label' =>
'Type',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
292 'subtype' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoiceSubtype',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 15),
294 'fk_soc' => array(
'type' =>
'integer:Societe:societe/class/societe.class.php',
'label' =>
'ThirdParty',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 50),
295 'datef' => array(
'type' =>
'date',
'label' =>
'DateInvoice',
'enabled' => 1,
'visible' => 1,
'position' => 20),
296 'date_valid' => array(
'type' =>
'date',
'label' =>
'DateValidation',
'enabled' => 1,
'visible' => -1,
'position' => 22),
297 'date_lim_reglement' => array(
'type' =>
'date',
'label' =>
'DateDue',
'enabled' => 1,
'visible' => 1,
'position' => 25),
298 'date_closing' => array(
'type' =>
'datetime',
'label' =>
'DateClosing',
'enabled' => 1,
'visible' => -1,
'position' => 30),
299 'paye' => array(
'type' =>
'smallint(6)',
'label' =>
'InvoicePaidCompletely',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 80),
304 'close_code' => array(
'type' =>
'varchar(16)',
'label' =>
'EarlyClosingReason',
'enabled' => 1,
'visible' => -1,
'position' => 92),
305 'close_note' => array(
'type' =>
'varchar(128)',
'label' =>
'EarlyClosingComment',
'enabled' => 1,
'visible' => -1,
'position' => 93),
306 'total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountHT',
'enabled' => 1,
'visible' => 1,
'position' => 95,
'isameasure' => 1),
307 'total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountVAT',
'enabled' => 1,
'visible' => -1,
'position' => 100,
'isameasure' => 1),
308 'localtax1' => array(
'type' =>
'double(24,8)',
'label' =>
'LT1',
'enabled' => 1,
'visible' => -1,
'position' => 110,
'isameasure' => 1),
309 'localtax2' => array(
'type' =>
'double(24,8)',
'label' =>
'LT2',
'enabled' => 1,
'visible' => -1,
'position' => 120,
'isameasure' => 1),
310 'revenuestamp' => array(
'type' =>
'double(24,8)',
'label' =>
'RevenueStamp',
'enabled' => 1,
'visible' => -1,
'position' => 115,
'isameasure' => 1),
311 'total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'AmountTTC',
'enabled' => 1,
'visible' => 1,
'position' => 130,
'isameasure' => 1),
312 'fk_facture_source' => array(
'type' =>
'integer',
'label' =>
'SourceInvoice',
'enabled' => 1,
'visible' => -1,
'position' => 170),
313 'fk_projet' => array(
'type' =>
'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)',
'label' =>
'Project',
'enabled' => 1,
'visible' => -1,
'position' => 175),
314 'fk_account' => array(
'type' =>
'integer',
'label' =>
'Fk account',
'enabled' => 1,
'visible' => -1,
'position' => 180),
315 'fk_currency' => array(
'type' =>
'varchar(3)',
'label' =>
'CurrencyCode',
'enabled' => 1,
'visible' => -1,
'position' => 185),
316 'fk_cond_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentTerm',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 190),
317 'fk_mode_reglement' => array(
'type' =>
'integer',
'label' =>
'PaymentMode',
'enabled' => 1,
'visible' => -1,
'position' => 195),
318 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'enabled' => 1,
'visible' => 0,
'position' => 205),
319 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'enabled' => 1,
'visible' => 0,
'position' => 210),
320 'model_pdf' => array(
'type' =>
'varchar(255)',
'label' =>
'Model pdf',
'enabled' => 1,
'visible' => 0,
'position' => 215),
321 'extraparams' => array(
'type' =>
'varchar(255)',
'label' =>
'Extraparams',
'enabled' => 1,
'visible' => -1,
'position' => 225),
322 'situation_cycle_ref' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation cycle ref',
'enabled' =>
'$conf->global->INVOICE_USE_SITUATION',
'visible' => -1,
'position' => 230),
323 'situation_counter' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation counter',
'enabled' =>
'$conf->global->INVOICE_USE_SITUATION',
'visible' => -1,
'position' => 235),
324 'situation_final' => array(
'type' =>
'smallint(6)',
'label' =>
'Situation final',
'enabled' =>
'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1',
'visible' => -1,
'position' => 240),
325 'retained_warranty' => array(
'type' =>
'double',
'label' =>
'Retained warranty',
'enabled' =>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible' => -1,
'position' => 245),
326 'retained_warranty_date_limit' => array(
'type' =>
'date',
'label' =>
'Retained warranty date limit',
'enabled' =>
'$conf->global->INVOICE_USE_RETAINED_WARRANTY',
'visible' => -1,
'position' => 250),
327 '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),
328 'fk_incoterms' => array(
'type' =>
'integer',
'label' =>
'IncotermCode',
'enabled' =>
'$conf->incoterm->enabled',
'visible' => -1,
'position' => 260),
329 'location_incoterms' => array(
'type' =>
'varchar(255)',
'label' =>
'IncotermLabel',
'enabled' =>
'$conf->incoterm->enabled',
'visible' => -1,
'position' => 265),
330 'date_pointoftax' => array(
'type' =>
'date',
'label' =>
'DatePointOfTax',
'enabled' =>
'$conf->global->INVOICE_POINTOFTAX_DATE',
'visible' => -1,
'position' => 270),
331 'fk_multicurrency' => array(
'type' =>
'integer',
'label' =>
'MulticurrencyID',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 275),
332 'multicurrency_code' => array(
'type' =>
'varchar(255)',
'label' =>
'Currency',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 280),
333 'multicurrency_tx' => array(
'type' =>
'double(24,8)',
'label' =>
'CurrencyRate',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 285,
'isameasure' => 1),
334 'multicurrency_total_ht' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountHT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 290,
'isameasure' => 1),
335 'multicurrency_total_tva' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountVAT',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 291,
'isameasure' => 1),
336 'multicurrency_total_ttc' => array(
'type' =>
'double(24,8)',
'label' =>
'MulticurrencyAmountTTC',
'enabled' =>
'isModEnabled("multicurrency")',
'visible' => -1,
'position' => 292,
'isameasure' => 1),
337 'fk_fac_rec_source' => array(
'type' =>
'integer',
'label' =>
'RecurringInvoiceSource',
'enabled' => 1,
'visible' => -1,
'position' => 305),
338 'last_main_doc' => array(
'type' =>
'varchar(255)',
'label' =>
'LastMainDoc',
'enabled' => 1,
'visible' => -1,
'position' => 310),
339 'module_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSModule',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 315),
340 'pos_source' => array(
'type' =>
'varchar(32)',
'label' =>
'POSTerminal',
'enabled' =>
"(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))",
'visible' => -1,
'position' => 320),
341 'datec' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'enabled' => 1,
'visible' => -1,
'position' => 500),
342 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModificationShort',
'enabled' => 1,
'visible' => -1,
'notnull' => 1,
'position' => 502),
343 'fk_user_author' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'enabled' => 1,
'visible' => -1,
'position' => 506),
344 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModification',
'enabled' => 1,
'visible' => -1,
'notnull' => -1,
'position' => 508),
345 'fk_user_valid' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserValidation',
'enabled' => 1,
'visible' => -1,
'position' => 510),
346 'fk_user_closing' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserClosing',
'enabled' => 1,
'visible' => -1,
'position' => 512),
347 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'enabled' => 1,
'visible' => -2,
'position' => 900),
348 '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')),
410 const CLOSECODE_DISCOUNTVAT =
'discount_vat';
411 const CLOSECODE_BADDEBT =
'badcustomer';
412 const CLOSECODE_BANKCHARGE =
'bankcharge';
413 const CLOSECODE_OTHER =
'other';
415 const CLOSECODE_ABANDONED =
'abandon';
416 const CLOSECODE_REPLACED =
'replaced';
428 $this->ismultientitymanaged = 1;
429 $this->isextrafieldmanaged = 1;
442 public function create(
User $user, $notrigger = 0, $forceduedate = 0)
444 global $langs, $conf, $mysoc, $hookmanager;
446 $origin_user_author_id = ($user->id > 0 ? (int) $user->id : 0);
448 if (empty($this->
type)) {
452 $this->ref_client = trim($this->ref_client);
454 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
455 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
456 $this->note_public = (isset($this->note_public) ? trim($this->note_public) :
'');
458 if (!$this->cond_reglement_id) {
459 $this->cond_reglement_id = 0;
461 if (!$this->mode_reglement_id) {
462 $this->mode_reglement_id = 0;
467 if (!empty($this->multicurrency_code)) {
469 if (empty($this->multicurrency_tx)) {
477 $this->fk_multicurrency = 0;
479 if (empty($this->fk_multicurrency)) {
480 $this->multicurrency_code = $conf->currency;
481 $this->fk_multicurrency = 0;
482 $this->multicurrency_tx = 1;
485 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
488 if (empty($this->date)) {
489 $this->error =
"Try to create an invoice with an empty parameter (date)";
490 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
494 $result = $soc->fetch($this->socid);
496 $this->error =
"Failed to fetch company: ".$soc->error;
497 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
502 $this->date_creation = $now;
506 $originaldatewhen =
null;
507 $nextdatewhen =
null;
508 $previousdaynextdatewhen =
null;
511 if ($this->fac_rec > 0) {
512 $this->fk_fac_rec_source = $this->fac_rec;
515 $origin_user_author_id = ($this->fk_user_author > 0 ? $this->fk_user_author : $origin_user_author_id);
517 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
519 $result = $_facrec->fetch($this->fac_rec);
520 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
523 $originaldatewhen = $_facrec->date_when;
524 $nextdatewhen =
null;
525 $previousdaynextdatewhen =
null;
526 if ($originaldatewhen) {
527 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
531 if (!empty($_facrec->frequency)) {
532 $this->socid = $_facrec->socid;
534 $this->entity = $_facrec->entity;
539 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
540 $this->note_public = GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
541 $this->note_private = GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
542 $this->model_pdf = GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
543 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
544 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
545 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
548 $this->total_ht = $_facrec->total_ht;
549 $this->total_ttc = $_facrec->total_ttc;
554 $this->fk_incoterms = $_facrec->fk_incoterms;
555 $this->location_incoterms = $_facrec->location_incoterms;
561 $this->ref_client = trim($this->ref_client);
562 $this->ref_customer = trim($this->ref_customer);
563 $this->note_public = trim($this->note_public);
564 $this->note_private = trim($this->note_private);
565 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
567 $this->array_options = $_facrec->array_options;
569 if (!$this->mode_reglement_id) {
570 $this->mode_reglement_id = 0;
575 $this->linked_objects = $_facrec->linkedObjectsIds;
580 if ($_facrec->frequency > 0) {
581 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
582 if (empty($_facrec->date_when)) {
583 $_facrec->date_when = $now;
585 $next_date = $_facrec->getNextDate();
586 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
588 $result = $_facrec->setNextDate($next_date, 1);
592 $outputlangs = $langs;
595 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
596 $newlang = $this->thirdparty->default_lang;
598 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
599 $newlang = $this->default_lang;
601 if (!empty($newlang)) {
603 $outputlangs->setDefaultLang($newlang);
609 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
612 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
615 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
618 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
619 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
620 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
621 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
622 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
633 if (empty($forceduedate)) {
639 $this->date_lim_reglement = $duedate;
641 $this->date_lim_reglement = $forceduedate;
645 $socid = $this->socid;
647 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
656 $sql .=
", date_pointoftax";
657 $sql .=
", note_private";
658 $sql .=
", note_public";
659 $sql .=
", ref_client";
660 $sql .=
", fk_account";
661 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
662 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
663 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
664 $sql .=
", fk_incoterms, location_incoterms";
665 $sql .=
", fk_multicurrency";
666 $sql .=
", multicurrency_code";
667 $sql .=
", multicurrency_tx";
668 $sql .=
", retained_warranty";
669 $sql .=
", retained_warranty_date_limit";
670 $sql .=
", retained_warranty_fk_cond_reglement";
674 $sql .=
", ".setEntity($this);
675 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
676 $sql .=
", '".$this->db->escape($this->
type).
"'";
677 $sql .=
", ".($this->subtype ?
"'".$this->db->escape($this->subtype).
"'" :
"null");
678 $sql .=
", ".((int) $socid);
679 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
680 $sql .=
", '".$this->db->idate($this->date).
"'";
681 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
682 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
683 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
684 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
685 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
686 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
687 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape($this->pos_source).
"'" :
"null");
688 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape($this->fk_fac_rec_source).
"'" :
"null");
689 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape($this->fk_facture_source).
"'" :
"null");
690 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
691 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
692 $sql .=
", ".((int) $this->cond_reglement_id);
693 $sql .=
", ".((int) $this->mode_reglement_id);
694 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
695 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
696 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape($this->situation_cycle_ref).
"'" :
"null");
697 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape($this->situation_counter).
"'" :
"null");
698 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
699 $sql .=
", ".(int) $this->fk_incoterms;
700 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
701 $sql .=
", ".(int) $this->fk_multicurrency;
702 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
703 $sql .=
", ".(float) $this->multicurrency_tx;
704 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape($this->retained_warranty));
705 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
706 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
709 $resql = $this->db->query($sql);
711 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
714 $this->
ref =
'(PROV'.$this->id.
')';
715 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
717 $resql = $this->db->query($sql);
722 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
723 $this->linked_objects = $this->linkedObjectsIds;
727 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
728 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
729 if (is_array($tmp_origin_id)) {
730 foreach ($tmp_origin_id as $origin_id) {
733 $this->error = $this->db->lasterror();
738 $origin_id = $tmp_origin_id;
741 $this->error = $this->db->lasterror();
749 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) {
750 $originforcontact = $this->origin;
751 $originidforcontact = $this->origin_id;
752 if ($originforcontact ==
'shipping') {
753 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
755 $exp->fetch($this->origin_id);
756 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
757 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
758 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
759 $originforcontact =
'commande';
760 if (is_object($value)) {
761 $originidforcontact = $value->id;
763 $originidforcontact = $value;
770 $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";
771 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
773 $resqlcontact = $this->db->query($sqlcontact);
775 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
777 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
787 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
790 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
791 foreach ($this->lines as $i => $val) {
792 $newinvoiceline = $this->lines[$i];
794 $newinvoiceline->context = $this->context;
796 $newinvoiceline->fk_facture = $this->id;
798 $newinvoiceline->origin = $this->lines[$i]->element;
799 $newinvoiceline->origin_id = $this->lines[$i]->id;
802 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
803 $newinvoiceline->date_start = $originaldatewhen;
805 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
806 $newinvoiceline->date_end = $previousdaynextdatewhen;
811 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
816 $vatrate = $newinvoiceline->tva_tx;
817 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
818 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
821 $newinvoiceline->fk_parent_line = $fk_parent_line;
825 $discount->fetch($newinvoiceline->fk_remise_except);
827 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
828 $newinvoiceline->fk_remise_except = $discountId;
832 $newinvoiceline->desc,
833 $newinvoiceline->subprice,
834 $newinvoiceline->qty,
836 $newinvoiceline->localtax1_tx,
837 $newinvoiceline->localtax2_tx,
838 $newinvoiceline->fk_product,
839 $newinvoiceline->remise_percent,
840 $newinvoiceline->date_start,
841 $newinvoiceline->date_end,
842 $newinvoiceline->fk_code_ventilation,
843 $newinvoiceline->info_bits,
844 $newinvoiceline->fk_remise_except,
847 $newinvoiceline->product_type,
848 $newinvoiceline->rang,
849 $newinvoiceline->special_code,
850 $newinvoiceline->element,
853 $newinvoiceline->fk_fournprice,
854 $newinvoiceline->pa_ht,
855 $newinvoiceline->label,
856 $newinvoiceline->array_options,
857 $newinvoiceline->situation_percent,
858 $newinvoiceline->fk_prev_id,
859 $newinvoiceline->fk_unit,
860 $newinvoiceline->multicurrency_subprice,
861 $newinvoiceline->ref_ext,
866 if ($result > 0 && $newinvoiceline->product_type == 9) {
867 $fk_parent_line = $result;
871 $this->error = $newinvoiceline->error;
872 $this->errors = $newinvoiceline->errors;
877 } elseif (!$error && empty($this->fac_rec)) {
880 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
882 foreach ($this->lines as $i => $val) {
883 $line = $this->lines[$i];
887 if (!is_object($line)) {
888 $line = (object) $line;
893 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
898 $vatrate = $line->tva_tx;
899 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
900 $vatrate .=
' ('.$line->vat_src_code.
')';
904 $originid = $line->origin_id;
905 $origintype = $line->origin;
907 $originid = $line->id;
908 $origintype = $this->element;
912 if (empty($line->ref_ext)) {
924 $line->remise_percent,
927 $line->fk_code_ventilation,
929 $line->fk_remise_except,
938 $line->fk_fournprice,
941 $line->array_options,
942 $line->situation_percent,
945 $line->multicurrency_subprice,
950 $this->error = $this->db->lasterror();
952 $this->db->rollback();
957 if ($result > 0 && $line->product_type == 9) {
958 $fk_parent_line = $result;
967 if (!$error && $this->fac_rec > 0) {
968 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
971 foreach ($_facrec->lines as $i => $val) {
972 if ($_facrec->lines[$i]->fk_product) {
973 $prod =
new Product($this->db);
974 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
978 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
990 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
991 $tva_npr = $_facrec->lines[$i]->info_bits;
992 if (empty($tva_tx)) {
995 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
996 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
998 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
999 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1002 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1003 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1005 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1010 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1011 $buyprice = $producttmp->cost_price;
1013 $buyprice = $producttmp->pmp;
1015 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1016 if ($producttmp->product_fourn_price_id > 0) {
1017 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1023 $result_insert = $this->
addline(
1024 $_facrec->lines[$i]->desc,
1025 $_facrec->lines[$i]->subprice,
1026 $_facrec->lines[$i]->qty,
1030 $_facrec->lines[$i]->fk_product,
1031 $_facrec->lines[$i]->remise_percent,
1032 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1033 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1039 $_facrec->lines[$i]->product_type,
1040 $_facrec->lines[$i]->rang,
1041 $_facrec->lines[$i]->special_code,
1045 $fk_product_fournisseur_price,
1047 $_facrec->lines[$i]->label,
1048 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1051 $_facrec->lines[$i]->fk_unit,
1052 $_facrec->lines[$i]->multicurrency_subprice,
1053 $_facrec->lines[$i]->ref_ext,
1058 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1059 $fk_parent_line = $result_insert;
1062 if ($result_insert < 0) {
1064 $this->error = $this->db->error();
1083 if (!$error && !$notrigger) {
1092 $this->db->commit();
1095 $this->db->rollback();
1099 $this->error = $langs->trans(
'FailedToUpdatePrice');
1100 $this->db->rollback();
1104 dol_syslog(get_class($this).
"::create error ".$this->error, LOG_ERR);
1105 $this->db->rollback();
1109 $this->error = $this->db->error();
1110 $this->db->rollback();
1126 $facture =
new Facture($this->db);
1132 if (!empty($this->array_options)) {
1133 $facture->array_options = $this->array_options;
1136 foreach ($this->lines as &$line) {
1137 $line->fetch_optionals();
1141 $facture->type = $this->type;
1142 $facture->subtype = $this->subtype;
1143 $facture->socid = $this->socid;
1144 $facture->date = $this->date;
1145 $facture->date_pointoftax = $this->date_pointoftax;
1146 $facture->note_public = $this->note_public;
1147 $facture->note_private = $this->note_private;
1148 $facture->ref_client = $this->ref_client;
1149 $facture->ref_customer = $this->ref_customer;
1150 $facture->model_pdf = $this->model_pdf;
1151 $facture->fk_project = $this->fk_project;
1152 $facture->cond_reglement_id = $this->cond_reglement_id;
1153 $facture->mode_reglement_id = $this->mode_reglement_id;
1157 $facture->origin = $this->origin;
1158 $facture->origin_id = $this->origin_id;
1159 $facture->fk_account = $this->fk_account;
1161 $facture->lines = $this->lines;
1162 $facture->situation_counter = $this->situation_counter;
1163 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1164 $facture->situation_final = $this->situation_final;
1166 $facture->retained_warranty = $this->retained_warranty;
1167 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1168 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1170 $facture->fk_user_author = $user->id;
1171 $facture->user_creation_id = $user->id;
1175 foreach ($facture->lines as $i => $tmpline) {
1176 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1177 if ($invertdetail) {
1178 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1179 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1180 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1181 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1182 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1183 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1184 $facture->lines[$i]->ref_ext =
'';
1188 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1190 $facid = $facture->create($user);
1192 $this->error = $facture->error;
1193 $this->errors = $facture->errors;
1197 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1198 foreach ($Tfk_object as $fk_object) {
1199 $facture->add_object_linked($typeObject, $fk_object);
1203 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1219 global $conf, $hookmanager;
1233 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1234 $objsoc =
new Societe($this->db);
1236 if ($objsoc->fetch($this->socid) > 0) {
1238 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1239 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1241 $object->fk_delivery_address = 0;
1253 $object->user_creation_id = $user->id;
1254 $object->user_validation_id =
null;
1255 $object->fk_user_author = $user->id;
1256 $object->fk_user_valid =
null;
1257 $object->fk_facture_source = 0;
1259 $object->date_modification =
'';
1260 $object->date_validation =
'';
1270 foreach (
$object->lines as $i => $line) {
1271 if ((
$object->lines[$i]->info_bits & 0x02) == 0x02) {
1278 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1290 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1291 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1295 $object->lines[$i]->date_start = $newFirst;
1296 $object->lines[$i]->date_end = $newLast;
1300 $object->lines[$i]->ref_ext =
'';
1304 $object->context[
'createfromclone'] =
'createfromclone';
1305 $result =
$object->create($user);
1308 $this->error =
$object->error;
1309 $this->errors =
$object->errors;
1312 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1314 $this->error =
$object->error;
1315 $this->errors =
$object->errors;
1316 } elseif (
$object->socid == $objFrom->socid) {
1318 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1320 $this->error =
$object->error;
1321 $this->errors =
$object->errors;
1328 if (is_object($hookmanager)) {
1329 $parameters = array(
'objFrom' => $objFrom);
1331 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1339 unset(
$object->context[
'createfromclone']);
1343 $this->db->commit();
1346 $this->db->rollback();
1360 global $conf, $hookmanager;
1369 for ($i = 0; $i < $num; $i++) {
1372 $line->libelle =
$object->lines[$i]->libelle;
1373 $line->label =
$object->lines[$i]->label;
1374 $line->desc =
$object->lines[$i]->desc;
1375 $line->subprice =
$object->lines[$i]->subprice;
1376 $line->total_ht =
$object->lines[$i]->total_ht;
1377 $line->total_tva =
$object->lines[$i]->total_tva;
1378 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1379 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1380 $line->total_ttc =
$object->lines[$i]->total_ttc;
1381 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1382 $line->tva_tx =
$object->lines[$i]->tva_tx;
1383 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1384 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1385 $line->qty =
$object->lines[$i]->qty;
1386 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1387 $line->remise_percent =
$object->lines[$i]->remise_percent;
1388 $line->fk_product =
$object->lines[$i]->fk_product;
1389 $line->info_bits =
$object->lines[$i]->info_bits;
1390 $line->product_type =
$object->lines[$i]->product_type;
1391 $line->rang =
$object->lines[$i]->rang;
1392 $line->special_code =
$object->lines[$i]->special_code;
1393 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1394 $line->fk_unit =
$object->lines[$i]->fk_unit;
1395 $line->date_start =
$object->lines[$i]->date_start;
1396 $line->date_end =
$object->lines[$i]->date_end;
1399 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1400 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1401 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1402 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1403 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1404 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1406 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1408 $line->pa_ht = $marginInfos[0];
1411 $object->lines[$i]->fetch_optionals();
1412 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1413 $line->array_options[$options_key] = $value;
1416 $this->lines[$i] = $line;
1419 $this->socid =
$object->socid;
1420 $this->fk_project =
$object->fk_project;
1421 $this->fk_account =
$object->fk_account;
1422 $this->cond_reglement_id =
$object->cond_reglement_id;
1423 $this->mode_reglement_id =
$object->mode_reglement_id;
1424 $this->availability_id =
$object->availability_id;
1425 $this->demand_reason_id =
$object->demand_reason_id;
1426 $this->delivery_date =
$object->delivery_date;
1427 $this->fk_delivery_address =
$object->fk_delivery_address;
1428 $this->contact_id =
$object->contact_id;
1429 $this->ref_client =
$object->ref_client;
1432 $this->note_private =
$object->note_private;
1433 $this->note_public =
$object->note_public;
1436 $this->module_source =
$object->module_source;
1437 $this->pos_source =
$object->pos_source;
1439 $this->origin =
$object->element;
1440 $this->origin_id =
$object->id;
1442 $this->fk_user_author = $user->id;
1446 foreach (
$object->array_options as $options_key => $value) {
1447 $this->array_options[$options_key] = $value;
1451 $this->linked_objects[$this->origin] = $this->origin_id;
1452 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1453 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1456 $ret = $this->
create($user);
1460 $hookmanager->initHooks(array(
'invoicedao'));
1462 $parameters = array(
'objFrom' =>
$object);
1464 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1490 global $conf, $hookmanager;
1498 $use_all_lines = empty($lines);
1500 for ($i = 0; $i < $num; $i++) {
1501 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1507 $line->libelle =
$object->lines[$i]->libelle;
1508 $line->label =
$object->lines[$i]->label;
1509 $line->desc =
$object->lines[$i]->desc;
1510 $line->subprice =
$object->lines[$i]->subprice;
1511 $line->total_ht =
$object->lines[$i]->total_ht;
1512 $line->total_tva =
$object->lines[$i]->total_tva;
1513 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1514 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1515 $line->total_ttc =
$object->lines[$i]->total_ttc;
1516 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1517 $line->tva_tx =
$object->lines[$i]->tva_tx;
1518 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1519 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1520 $line->qty =
$object->lines[$i]->qty;
1521 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1522 $line->remise_percent =
$object->lines[$i]->remise_percent;
1523 $line->fk_product =
$object->lines[$i]->fk_product;
1524 $line->info_bits =
$object->lines[$i]->info_bits;
1525 $line->product_type =
$object->lines[$i]->product_type;
1526 $line->rang =
$object->lines[$i]->rang;
1527 $line->special_code =
$object->lines[$i]->special_code;
1528 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1529 $line->fk_unit =
$object->lines[$i]->fk_unit;
1530 $line->date_start =
$object->lines[$i]->date_start;
1531 $line->date_end =
$object->lines[$i]->date_end;
1534 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1535 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1536 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1537 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1538 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1539 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1541 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1543 $line->pa_ht = $marginInfos[0];
1546 $object->lines[$i]->fetch_optionals();
1547 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1548 $line->array_options[$options_key] = $value;
1551 $this->lines[$i] = $line;
1554 $this->socid =
$object->socid;
1555 $this->fk_project =
$object->fk_project;
1556 $this->fk_account =
$object->fk_account;
1557 $this->cond_reglement_id =
$object->cond_reglement_id;
1558 $this->mode_reglement_id =
$object->mode_reglement_id;
1559 $this->availability_id =
$object->availability_id;
1560 $this->demand_reason_id =
$object->demand_reason_id;
1561 $this->delivery_date =
$object->delivery_date;
1562 $this->fk_delivery_address =
$object->fk_delivery_address;
1563 $this->contact_id =
$object->contact_id;
1564 $this->ref_client =
$object->ref_client;
1567 $this->note_private =
$object->note_private;
1568 $this->note_public =
$object->note_public;
1571 $this->module_source =
$object->module_source;
1572 $this->pos_source =
$object->pos_source;
1574 $this->origin =
$object->element;
1575 $this->origin_id =
$object->id;
1577 $this->fk_user_author = $user->id;
1581 foreach (
$object->array_options as $options_key => $value) {
1582 $this->array_options[$options_key] = $value;
1586 $this->linked_objects[$this->origin] = $this->origin_id;
1587 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1588 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1591 $ret = $this->
create($user);
1595 $hookmanager->initHooks(array(
'invoicedao'));
1597 $parameters = array(
'objFrom' =>
$object);
1599 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1629 global $conf, $langs, $hookmanager, $action;
1631 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1632 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1637 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1641 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1644 $origin->error =
'ErrorDateIsInFuture';
1648 if ($payment_terms_id <= 0) {
1649 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1653 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1655 if (empty($payment_conditions_deposit_percent)) {
1656 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1660 if (empty($origin->deposit_percent)) {
1661 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1665 $deposit =
new self($origin->db);
1666 $deposit->socid = $origin->socid;
1668 $deposit->fk_project = $origin->fk_project;
1669 $deposit->ref_client = $origin->ref_client;
1670 $deposit->date = $date;
1671 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1672 $deposit->cond_reglement_id = $payment_terms_id;
1673 $deposit->availability_id = $origin->availability_id;
1674 $deposit->demand_reason_id = $origin->demand_reason_id;
1675 $deposit->fk_account = $origin->fk_account;
1676 $deposit->fk_incoterms = $origin->fk_incoterms;
1677 $deposit->location_incoterms = $origin->location_incoterms;
1678 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1679 $deposit->multicurrency_code = $origin->multicurrency_code;
1680 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1681 $deposit->module_source = $origin->module_source;
1682 $deposit->pos_source = $origin->pos_source;
1683 $deposit->model_pdf =
'crabe';
1685 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1694 $deposit->note_private = $origin->note_private;
1695 $deposit->note_public = $origin->note_public;
1698 $deposit->origin = $origin->element;
1699 $deposit->origin_id = $origin->id;
1701 $origin->fetch_optionals();
1703 foreach ($origin->array_options as $extrakey => $value) {
1704 $deposit->array_options[$extrakey] = $value;
1707 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1709 foreach ($overrideFields as $key => $value) {
1710 $deposit->$key = $value;
1713 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1715 $origin->db->begin();
1718 $createReturn = $deposit->create($user, $notrigger);
1720 if ($createReturn <= 0) {
1721 $origin->db->rollback();
1722 $origin->error = $deposit->error;
1723 $origin->errors = $deposit->errors;
1727 $amount_ttc_diff = 0;
1728 $amountdeposit = array();
1729 $descriptions = array();
1732 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1734 $TTotalByTva = array();
1735 foreach ($origin->lines as &$line) {
1736 if (!empty($line->special_code)) {
1739 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1740 $descriptions[$line->tva_tx] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1741 $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1742 $descriptions[$line->tva_tx] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1743 $descriptions[$line->tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1746 foreach ($TTotalByTva as $tva => &$total) {
1747 $coef = $total / $origin->total_ttc;
1748 $am = $amount * $coef;
1749 $amount_ttc_diff += $am;
1750 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1754 $lines = $origin->lines;
1755 $numlines = count($lines);
1756 for ($i = 0; $i < $numlines; $i++) {
1757 if (empty($lines[$i]->qty)) {
1760 if (!empty($lines[$i]->special_code)) {
1764 $totalamount += $lines[$i]->total_ht;
1765 $tva_tx = $lines[$i]->tva_tx;
1766 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1767 $descriptions[$tva_tx] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1768 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1769 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1770 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1773 if ($totalamount == 0) {
1774 $amountdeposit[0] = 0;
1777 $amount_ttc_diff = $amountdeposit[0];
1780 foreach ($amountdeposit as $tva => $amount) {
1781 if (empty($amount)) {
1785 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1788 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1789 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1792 $addlineResult = $deposit->addline(
1799 (!
getDolGlobalString(
'INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1819 if ($addlineResult < 0) {
1820 $origin->db->rollback();
1821 $origin->error = $deposit->error;
1822 $origin->errors = $deposit->errors;
1827 $diff = $deposit->total_ttc - $amount_ttc_diff;
1830 $deposit->fetch_lines();
1831 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1833 $updatelineResult = $deposit->updateline(
1834 $deposit->lines[0]->id,
1835 $deposit->lines[0]->desc,
1837 $deposit->lines[0]->qty,
1838 $deposit->lines[0]->remise_percent,
1839 $deposit->lines[0]->date_start,
1840 $deposit->lines[0]->date_end,
1841 $deposit->lines[0]->tva_tx,
1845 $deposit->lines[0]->info_bits,
1846 $deposit->lines[0]->product_type,
1850 $deposit->lines[0]->pa_ht,
1851 $deposit->lines[0]->label,
1857 if ($updatelineResult < 0) {
1858 $origin->db->rollback();
1859 $origin->error = $deposit->error;
1860 $origin->errors = $deposit->errors;
1865 $hookmanager->initHooks(array(
'invoicedao'));
1867 $parameters = array(
'objFrom' => $origin);
1868 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1871 $origin->db->rollback();
1872 $origin->error = $hookmanager->error;
1873 $origin->errors = $hookmanager->errors;
1877 if (!empty($autoValidateDeposit)) {
1878 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1880 if ($validateReturn < 0) {
1881 $origin->db->rollback();
1882 $origin->error = $deposit->error;
1883 $origin->errors = $deposit->errors;
1888 unset($deposit->context[
'createdepositfromorigin']);
1890 $origin->db->commit();
1904 global $conf, $langs, $mysoc, $user;
1906 $langs->load(
'bills');
1909 $moretitle = $params[
'moretitle'] ??
'';
1911 $picto = $this->picto;
1912 if ($this->
type == self::TYPE_REPLACEMENT) {
1915 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1918 if ($this->
type == self::TYPE_DEPOSIT) {
1922 if ($user->hasRight(
"facture",
"read")) {
1923 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1925 $datas[
'picto'] .=
' '.$this->getLibType(1);
1928 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
1932 if (isset($this->
status) && isset($this->totalpaid)) {
1933 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid);
1936 $datas[
'picto'] .=
' - '.$moretitle;
1938 if (!empty($this->
ref)) {
1939 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
1941 if (!empty($this->ref_customer)) {
1942 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
1944 if (!empty($this->date)) {
1945 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
1947 if (!empty($this->total_ht)) {
1948 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1950 if (!empty($this->total_tva)) {
1951 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1953 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
1954 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
1956 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1958 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1960 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1961 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1963 if (!empty($this->total_ttc)) {
1964 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1985 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
1987 global $langs, $conf, $user;
1989 if (!empty($conf->dol_no_mouse_hover)) {
1995 if ($option ==
'withdraw') {
1996 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
1998 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2001 if (!$user->hasRight(
"facture",
"read")) {
2005 if ($option !==
'nolink') {
2007 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2008 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2009 $add_save_lastsearch_values = 1;
2011 if ($add_save_lastsearch_values) {
2012 $url .=
'&save_lastsearch_values=1';
2020 $picto = $this->picto;
2021 if ($this->
type == self::TYPE_REPLACEMENT) {
2024 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2027 if ($this->
type == self::TYPE_DEPOSIT) {
2033 'objecttype' => $this->element,
2034 'moretitle' => $moretitle,
2035 'option' => $option,
2037 $classfortooltip =
'classfortooltip';
2040 $classfortooltip =
'classforajaxtooltip';
2041 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2047 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2048 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2050 $label = $langs->trans(
"Invoice");
2051 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
2053 $linkclose .= ($label ?
' title="'.dol_escape_htmltag($label, 1).
'"' :
' title="tocomplete"');
2054 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2057 $linkstart =
'<a href="'.$url.
'"';
2058 $linkstart .= $linkclose.
'>';
2061 if ($option ==
'nolink') {
2066 $result .= $linkstart;
2068 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2070 if ($withpicto != 2) {
2071 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2073 $result .= $linkend;
2075 if ($addlinktonotes) {
2076 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2079 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2080 $result .=
' <span class="note inline-block">';
2081 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
2086 $result .=
'</span>';
2090 global $action, $hookmanager;
2091 $hookmanager->initHooks(array(
'invoicedao'));
2092 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2093 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2095 $result = $hookmanager->resPrint;
2097 $result .= $hookmanager->resPrint;
2113 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2115 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2119 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2120 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2121 $sql .=
', f.datef as df, f.date_pointoftax';
2122 $sql .=
', f.date_lim_reglement as dlr';
2123 $sql .=
', f.datec as datec';
2124 $sql .=
', f.date_valid as datev';
2125 $sql .=
', f.tms as datem';
2126 $sql .=
', f.note_private, f.note_public, f.fk_statut as status, 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';
2127 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2128 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2129 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2130 $sql .=
', f.fk_account';
2131 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2132 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2133 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2134 $sql .=
', f.fk_incoterms, f.location_incoterms';
2135 $sql .=
', f.module_source, f.pos_source';
2136 $sql .=
", i.libelle as label_incoterms";
2137 $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";
2138 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
2139 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2140 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
2141 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2144 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2146 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2148 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2151 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2155 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2156 $resql = $this->db->query($sql);
2158 if ($this->db->num_rows($resql)) {
2159 $obj = $this->db->fetch_object($resql);
2161 $this->
id = $obj->rowid;
2162 $this->entity = $obj->entity;
2164 $this->
ref = $obj->ref;
2165 $this->ref_client = $obj->ref_client;
2166 $this->ref_customer = $obj->ref_client;
2167 $this->ref_ext = $obj->ref_ext;
2168 $this->
type = $obj->type;
2169 $this->subtype = $obj->subtype;
2170 $this->date = $this->db->jdate($obj->df);
2171 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2172 $this->date_creation = $this->db->jdate($obj->datec);
2173 $this->date_validation = $this->db->jdate($obj->datev);
2174 $this->date_modification = $this->db->jdate($obj->datem);
2175 $this->datem = $this->db->jdate($obj->datem);
2176 $this->total_ht = $obj->total_ht;
2177 $this->total_tva = $obj->total_tva;
2178 $this->total_localtax1 = $obj->localtax1;
2179 $this->total_localtax2 = $obj->localtax2;
2180 $this->total_ttc = $obj->total_ttc;
2181 $this->revenuestamp = $obj->revenuestamp;
2182 $this->paye = $obj->paye;
2183 $this->close_code = $obj->close_code;
2184 $this->close_note = $obj->close_note;
2186 $this->socid = $obj->fk_soc;
2187 $this->thirdparty =
null;
2189 $this->fk_project = $obj->fk_project;
2190 $this->project =
null;
2192 $this->
statut = $obj->status;
2193 $this->
status = $obj->status;
2195 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2196 $this->mode_reglement_id = $obj->fk_mode_reglement;
2197 $this->mode_reglement_code = $obj->mode_reglement_code;
2198 $this->mode_reglement = $obj->mode_reglement_libelle;
2199 $this->cond_reglement_id = $obj->fk_cond_reglement;
2200 $this->cond_reglement_code = $obj->cond_reglement_code;
2201 $this->cond_reglement = $obj->cond_reglement_libelle;
2202 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2203 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2204 $this->fk_facture_source = $obj->fk_facture_source;
2205 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2206 $this->note = $obj->note_private;
2207 $this->note_private = $obj->note_private;
2208 $this->note_public = $obj->note_public;
2209 $this->user_creation_id = $obj->fk_user_author;
2210 $this->user_validation_id = $obj->fk_user_valid;
2211 $this->user_modification_id = $obj->fk_user_modif;
2212 $this->fk_user_author = $obj->fk_user_author;
2213 $this->fk_user_valid = $obj->fk_user_valid;
2214 $this->fk_user_modif = $obj->fk_user_modif;
2215 $this->model_pdf = $obj->model_pdf;
2216 $this->last_main_doc = $obj->last_main_doc;
2217 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2218 $this->situation_counter = $obj->situation_counter;
2219 $this->situation_final = $obj->situation_final;
2220 $this->retained_warranty = $obj->retained_warranty;
2221 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2222 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2224 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2227 $this->fk_incoterms = $obj->fk_incoterms;
2228 $this->location_incoterms = $obj->location_incoterms;
2229 $this->label_incoterms = $obj->label_incoterms;
2231 $this->module_source = $obj->module_source;
2232 $this->pos_source = $obj->pos_source;
2235 $this->fk_multicurrency = $obj->fk_multicurrency;
2236 $this->multicurrency_code = $obj->multicurrency_code;
2237 $this->multicurrency_tx = $obj->multicurrency_tx;
2238 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2239 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2240 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2242 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2251 $this->lines = array();
2255 $this->error = $this->db->error();
2259 $this->db->free($resql);
2263 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2265 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2269 $this->error = $this->db->lasterror();
2284 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2287 $this->lines = array();
2289 $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,';
2290 $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,';
2291 $sql .=
' l.situation_percent, l.fk_prev_id,';
2292 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2293 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2294 $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,';
2295 $sql .=
' l.fk_unit,';
2296 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2297 $sql .=
' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc, p.barcode as product_barcode';
2298 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2299 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2300 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2301 $sql .=
' ORDER BY l.rang, l.rowid';
2303 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2304 $result = $this->db->query($sql);
2306 $num = $this->db->num_rows($result);
2309 $objp = $this->db->fetch_object($result);
2312 $line->id = $objp->rowid;
2313 $line->rowid = $objp->rowid;
2314 $line->fk_facture = $objp->fk_facture;
2315 $line->label = $objp->custom_label;
2316 $line->desc = $objp->description;
2317 $line->description = $objp->description;
2318 $line->product_type = $objp->product_type;
2319 $line->ref = $objp->product_ref;
2320 $line->product_ref = $objp->product_ref;
2321 $line->libelle = $objp->product_label;
2322 $line->product_label = $objp->product_label;
2323 $line->product_barcode = $objp->product_barcode;
2324 $line->product_desc = $objp->product_desc;
2325 $line->fk_product_type = $objp->fk_product_type;
2326 $line->qty = $objp->qty;
2327 $line->subprice = $objp->subprice;
2328 $line->ref_ext = $objp->ref_ext;
2330 $line->vat_src_code = $objp->vat_src_code;
2331 $line->tva_tx = $objp->tva_tx;
2332 $line->localtax1_tx = $objp->localtax1_tx;
2333 $line->localtax2_tx = $objp->localtax2_tx;
2334 $line->localtax1_type = $objp->localtax1_type;
2335 $line->localtax2_type = $objp->localtax2_type;
2336 $line->remise_percent = $objp->remise_percent;
2337 $line->fk_remise_except = $objp->fk_remise_except;
2338 $line->fk_product = $objp->fk_product;
2339 $line->date_start = $this->db->jdate($objp->date_start);
2340 $line->date_end = $this->db->jdate($objp->date_end);
2341 $line->info_bits = $objp->info_bits;
2342 $line->total_ht = $objp->total_ht;
2343 $line->total_tva = $objp->total_tva;
2344 $line->total_localtax1 = $objp->total_localtax1;
2345 $line->total_localtax2 = $objp->total_localtax2;
2346 $line->total_ttc = $objp->total_ttc;
2348 $line->fk_fournprice = $objp->fk_fournprice;
2349 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2350 $line->pa_ht = $marginInfos[0];
2351 $line->marge_tx = $marginInfos[1];
2352 $line->marque_tx = $marginInfos[2];
2353 $line->rang = $objp->rang;
2354 $line->special_code = $objp->special_code;
2355 $line->fk_parent_line = $objp->fk_parent_line;
2356 $line->situation_percent = $objp->situation_percent;
2357 $line->fk_prev_id = $objp->fk_prev_id;
2358 $line->fk_unit = $objp->fk_unit;
2360 $line->batch = $objp->batch;
2361 $line->fk_warehouse = $objp->fk_warehouse;
2364 $line->fk_accounting_account = $objp->fk_code_ventilation;
2367 $line->fk_multicurrency = $objp->fk_multicurrency;
2368 $line->multicurrency_code = $objp->multicurrency_code;
2369 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2370 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2371 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2372 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2374 $line->fetch_optionals();
2377 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2378 $tmpproduct =
new Product($this->db);
2379 $tmpproduct->fetch($objp->fk_product);
2380 $tmpproduct->getMultiLangs();
2382 $line->multilangs = $tmpproduct->multilangs;
2385 $this->lines[$i] = $line;
2389 $this->db->free($result);
2392 $this->error = $this->db->error();
2407 $this->tab_previous_situation_invoice = array();
2408 $this->tab_next_situation_invoice = array();
2410 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2411 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2412 $sql .=
' AND entity = '.((int) $this->entity);
2413 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2414 $sql .=
' ORDER BY situation_counter ASC';
2416 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2417 $result = $this->db->query($sql);
2418 if ($result && $this->db->num_rows($result) > 0) {
2419 while ($objp = $this->db->fetch_object($result)) {
2420 $invoice =
new Facture($this->db);
2421 if ($invoice->fetch($objp->rowid) > 0) {
2422 if ($objp->situation_counter < $this->situation_counter
2423 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2425 $this->tab_previous_situation_invoice[] = $invoice;
2427 $this->tab_next_situation_invoice[] = $invoice;
2446 if (empty($this->
type)) {
2449 if (isset($this->subtype)) {
2450 $this->subtype = (int) trim((
string) $this->subtype);
2452 if (isset($this->
ref)) {
2453 $this->
ref = trim($this->
ref);
2455 if (isset($this->ref_ext)) {
2456 $this->ref_ext = trim($this->ref_ext);
2458 if (isset($this->ref_client)) {
2459 $this->ref_client = trim($this->ref_client);
2461 if (isset($this->increment)) {
2462 $this->increment = trim($this->increment);
2464 if (isset($this->close_code)) {
2465 $this->close_code = trim($this->close_code);
2467 if (isset($this->close_note)) {
2468 $this->close_note = trim($this->close_note);
2470 if (isset($this->note) || isset($this->note_private)) {
2471 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2473 if (isset($this->note) || isset($this->note_private)) {
2474 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2476 if (isset($this->note_public)) {
2477 $this->note_public = trim($this->note_public);
2479 if (isset($this->model_pdf)) {
2480 $this->model_pdf = trim($this->model_pdf);
2482 if (isset($this->import_key)) {
2483 $this->import_key = trim($this->import_key);
2485 if (isset($this->retained_warranty)) {
2486 $this->retained_warranty = (float) $this->retained_warranty;
2494 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2495 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2496 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2497 $sql .=
" type=".(isset($this->
type) ? $this->db->escape($this->
type) :
"null").
",";
2498 $sql .=
" subtype=".(isset($this->subtype) ? $this->db->escape($this->subtype) :
"null").
",";
2499 $sql .=
" ref_client=".(isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null").
",";
2500 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2501 $sql .=
" fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) :
"null").
",";
2502 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2503 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2504 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2505 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2506 $sql .=
" paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).
",";
2507 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2508 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2509 $sql .=
" total_tva=".(isset($this->total_tva) ? (float) $this->total_tva :
"null").
",";
2510 $sql .=
" localtax1=".(isset($this->total_localtax1) ? (float) $this->total_localtax1 :
"null").
",";
2511 $sql .=
" localtax2=".(isset($this->total_localtax2) ? (float) $this->total_localtax2 :
"null").
",";
2512 $sql .=
" total_ht=".(isset($this->total_ht) ? (float) $this->total_ht :
"null").
",";
2513 $sql .=
" total_ttc=".(isset($this->total_ttc) ? (float) $this->total_ttc :
"null").
",";
2514 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2515 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2516 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? (int) $this->fk_user_valid :
"null").
",";
2517 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2518 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2519 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2520 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2521 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2522 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2523 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2524 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2525 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2526 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2527 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2528 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2529 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2530 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2531 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2532 $sql .=
" WHERE rowid=".((int) $this->
id);
2536 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2537 $resql = $this->db->query($sql);
2540 $this->errors[] =
"Error ".$this->db->lasterror();
2550 if (!$error && !$notrigger) {
2561 foreach ($this->errors as $errmsg) {
2562 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2563 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2565 $this->db->rollback();
2568 $this->db->commit();
2584 global $conf, $langs;
2586 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2587 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2592 $result = $remise->fetch($idremise);
2595 if ($remise->fk_facture) {
2596 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2597 $this->db->rollback();
2602 $facligne->fk_facture = $this->id;
2603 $facligne->fk_remise_except = $remise->id;
2604 $facligne->desc = $remise->description;
2605 $facligne->vat_src_code = $remise->vat_src_code;
2606 $facligne->tva_tx = $remise->tva_tx;
2607 $facligne->subprice = -$remise->amount_ht;
2608 $facligne->fk_product = 0;
2610 $facligne->remise_percent = 0;
2611 $facligne->rang = -1;
2612 $facligne->info_bits = 2;
2615 $facligne->rang = 1;
2616 $linecount = count($this->lines);
2617 for ($ii = 1; $ii <= $linecount; $ii++) {
2623 if ($remise->fk_facture_source > 0) {
2624 $srcinvoice =
new Facture($this->db);
2625 $srcinvoice->fetch($remise->fk_facture_source);
2626 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2628 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2629 $facligne->pa_ht = $arraytmp[
'pa_total'];
2632 $facligne->total_ht = -$remise->amount_ht;
2633 $facligne->total_tva = -$remise->amount_tva;
2634 $facligne->total_ttc = -$remise->amount_ttc;
2636 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2637 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2638 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2639 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2641 $lineid = $facligne->insert();
2646 $result = $remise->link_to_invoice($lineid, 0);
2648 $this->error = $remise->error;
2649 $this->db->rollback();
2653 $this->db->commit();
2656 $this->error = $facligne->error;
2657 $this->db->rollback();
2661 $this->error = $facligne->error;
2662 $this->db->rollback();
2666 $this->db->rollback();
2688 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2689 if (empty($ref_client)) {
2690 $sql .=
' SET ref_client = NULL';
2692 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2694 $sql .=
" WHERE rowid = ".((int) $this->
id);
2696 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2697 $resql = $this->db->query($sql);
2699 $this->errors[] = $this->db->error();
2704 $this->ref_client = $ref_client;
2707 if (!$notrigger && empty($error)) {
2717 $this->ref_client = $ref_client;
2719 $this->db->commit();
2722 foreach ($this->errors as $errmsg) {
2723 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2724 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2726 $this->db->rollback();
2739 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2741 global $langs, $conf;
2742 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2746 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2759 if (!$error && !$notrigger) {
2773 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2787 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2788 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2789 $sql .=
' AND fk_facture_line IS NULL';
2790 $resql = $this->db->query($sql);
2794 $list_rowid_det = array();
2795 foreach ($this->lines as $key => $invoiceline) {
2796 $list_rowid_det[] = $invoiceline->id;
2800 if (count($list_rowid_det)) {
2801 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2802 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2803 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
2805 if (!$this->db->query($sql)) {
2806 $this->error = $this->db->error().
" sql=".$sql;
2807 $this->errors[] = $this->error;
2808 $this->db->rollback();
2815 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2816 $sql .=
' SET fk_invoice = NULL';
2817 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2819 if (!$this->db->query($sql)) {
2820 $this->error = $this->db->error().
" sql=".$sql;
2821 $this->errors[] = $this->error;
2822 $this->db->rollback();
2826 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
2827 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2828 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2830 if (!$this->db->query($sql)) {
2831 $this->error = $this->db->error().
" sql=".$sql;
2832 $this->errors[] = $this->error;
2833 $this->db->rollback();
2838 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
2839 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2840 $langs->load(
"agenda");
2842 $num = count($this->lines);
2843 for ($i = 0; $i < $num; $i++) {
2844 if ($this->lines[$i]->fk_product > 0) {
2846 $mouvP->origin = &$this;
2847 $mouvP->setOrigin($this->element, $this->
id);
2849 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2850 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2852 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2859 $main = MAIN_DB_PREFIX.
'facturedet';
2860 $ef = $main.
"_extrafields";
2861 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2863 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2866 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2868 $resql = $this->db->query($sql);
2876 if ($conf->facture->dir_output && !empty($this->
ref)) {
2877 $dir = $conf->facture->dir_output.
"/".$ref;
2878 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2879 if (file_exists($file)) {
2883 $langs->load(
"errors");
2884 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2885 $this->errors[] = $this->error;
2886 $this->db->rollback();
2890 if (file_exists($dir)) {
2892 $langs->load(
"errors");
2893 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2894 $this->errors[] = $this->error;
2895 $this->db->rollback();
2901 $this->db->commit();
2904 $this->error = $this->db->lasterror().
" sql=".$sql;
2905 $this->errors[] = $this->error;
2906 $this->db->rollback();
2910 $this->error = $this->db->lasterror().
" sql=".$sql;
2911 $this->errors[] = $this->error;
2912 $this->db->rollback();
2916 $this->db->rollback();
2933 public function set_paid($user, $close_code =
'', $close_note =
'')
2936 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2937 return $this->
setPaid($user, $close_code, $close_note);
2950 public function setPaid($user, $close_code =
'', $close_note =
'')
2954 if ($this->paye != 1) {
2959 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
2961 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2962 $sql .=
' fk_statut='.self::STATUS_CLOSED;
2967 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2970 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2972 $sql .=
', fk_user_closing = '.((int) $user->id);
2973 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
2974 $sql .=
" WHERE rowid = ".((int) $this->
id);
2976 $resql = $this->db->query($sql);
2986 $this->error = $this->db->lasterror();
2990 $this->db->commit();
2993 $this->db->rollback();
3016 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3034 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3035 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3036 $sql .=
' date_closing=null,';
3037 $sql .=
' fk_user_closing=null';
3038 $sql .=
" WHERE rowid = ".((int) $this->
id);
3040 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3041 $resql = $this->db->query($sql);
3051 $this->error = $this->db->error();
3056 $this->db->commit();
3059 $this->db->rollback();
3081 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3082 return $this->
setCanceled($user, $close_code, $close_note);
3095 public function setCanceled($user, $close_code =
'', $close_note =
'')
3097 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3102 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3103 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3105 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3108 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3110 $sql .=
', fk_user_closing = '.((int) $user->id);
3111 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3112 $sql .=
" WHERE rowid = ".((int) $this->
id);
3114 $resql = $this->db->query($sql);
3118 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3119 $sql .=
' SET fk_facture = NULL';
3120 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3122 $resql = $this->db->query($sql);
3127 $this->db->rollback();
3132 $this->db->commit();
3135 $this->error = $this->db->error().
" sql=".$sql;
3136 $this->db->rollback();
3140 $this->error = $this->db->error().
" sql=".$sql;
3141 $this->db->rollback();
3157 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3159 global $conf, $langs, $mysoc;
3160 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3162 $productStatic =
null;
3163 $warehouseStatic =
null;
3164 if ($batch_rule > 0) {
3165 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3166 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3167 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3168 $productStatic =
new Product($this->db);
3169 $warehouseStatic =
new Entrepot($this->db);
3176 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3183 if ($this->
status != self::STATUS_DRAFT) {
3184 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3187 if (count($this->lines) <= 0) {
3188 $langs->load(
"errors");
3189 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3193 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3194 $this->error =
'Permission denied';
3195 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3198 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3206 if (!$last_of_type[0]) {
3207 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3213 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3214 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3215 foreach ($array_to_check as $key) {
3216 $keymin = strtolower($key);
3217 if (!property_exists($this->thirdparty, $keymin)) {
3220 $vallabel = $this->thirdparty->$keymin;
3222 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3224 if ($this->thirdparty->isACompany()) {
3226 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3227 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3228 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3229 $langs->load(
"errors");
3230 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3231 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3237 if ($key ==
'EMAIL') {
3240 $langs->load(
"errors");
3241 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3242 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3246 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3248 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta)) {
3249 $langs->load(
"errors");
3250 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3251 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3260 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3261 foreach ($array_to_check as $key => $val) {
3262 $keymin = strtolower($key);
3263 $vallabel = $this->$keymin;
3266 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3268 $langs->load(
"errors");
3270 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3277 if ($this->
type == self::TYPE_REPLACEMENT) {
3279 if ($this->fk_facture_source <= 0) {
3280 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3281 $this->db->rollback();
3286 $facreplaced =
new Facture($this->db);
3287 $result = $facreplaced->fetch($this->fk_facture_source);
3289 $this->error = $langs->trans(
"ErrorBadInvoice");
3290 $this->db->rollback();
3295 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3296 if ($idreplacement && $idreplacement != $this->
id) {
3297 $facreplacement =
new Facture($this->db);
3298 $facreplacement->fetch($idreplacement);
3299 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3300 $this->db->rollback();
3304 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3306 $this->error = $facreplaced->error;
3307 $this->db->rollback();
3313 if ($force_number) {
3314 $num = $force_number;
3315 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3331 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3332 $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).
"'";
3334 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3335 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3337 $sql .=
" WHERE rowid = ".((int) $this->
id);
3339 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3340 $resql = $this->db->query($sql);
3342 $this->error = $this->db->lasterror();
3347 if (!$error && (preg_match(
'/^[\(]?PROV/i', $this->
ref))) {
3353 $result = $this->thirdparty->setAsCustomer();
3356 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3357 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3358 $langs->load(
"agenda");
3361 $cpt = count($this->lines);
3362 for ($i = 0; $i < $cpt; $i++) {
3363 if ($this->lines[$i]->fk_product > 0) {
3365 $mouvP->origin = &$this;
3366 $mouvP->setOrigin($this->element, $this->
id);
3369 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3372 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3375 $this->error = $mouvP->error;
3376 $this->errors = array_merge($this->errors, $mouvP->errors);
3382 $is_batch_line =
false;
3383 if ($batch_rule > 0) {
3384 $productStatic->fetch($this->lines[$i]->fk_product);
3385 if ($productStatic->hasbatch()) {
3386 $is_batch_line =
true;
3387 $product_qty_remain = $this->lines[$i]->qty;
3393 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3394 $sortorder =
'ASC,ASC,ASC,ASC';
3397 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_ALLOW_NEGATIVE_TRANSFER') ?
null : 0), $sortfield, $sortorder);
3398 if (!is_array($resBatchList)) {
3400 $this->error = $this->db->lasterror();
3404 $batchList = $resBatchList;
3405 if (empty($batchList)) {
3407 $langs->load(
'errors');
3408 $warehouseStatic->fetch($idwarehouse);
3409 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3410 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3413 foreach ($batchList as $batch) {
3414 if ($batch->qty <= 0) {
3419 if ($batch->qty >= $product_qty_remain) {
3420 $product_batch_qty = $product_qty_remain;
3423 $product_batch_qty = $batch->qty;
3425 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3428 $this->error = $mouvP->error;
3429 $this->errors = array_merge($this->errors, $mouvP->errors);
3433 $product_qty_remain -= $product_batch_qty;
3435 if ($product_qty_remain <= 0) {
3440 if (!$error && $product_qty_remain > 0) {
3443 $batch = $batchList[0];
3444 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3447 $this->error = $mouvP->error;
3448 $this->errors = array_merge($this->errors, $mouvP->errors);
3452 $langs->load(
'errors');
3453 $warehouseStatic->fetch($idwarehouse);
3454 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3455 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3462 if (!$is_batch_line) {
3463 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3466 $this->error = $mouvP->error;
3467 $this->errors = array_merge($this->errors, $mouvP->errors);
3480 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3481 $invoice_situation =
new Facture($this->db);
3482 $result = $invoice_situation->fetch($this->fk_facture_source);
3483 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3484 $invoice_situation->situation_final = 0;
3486 $result = $invoice_situation->setFinal($user, 1);
3489 $this->error = $invoice_situation->error;
3490 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3496 if (!$error && !$notrigger) {
3506 $this->oldref = $this->ref;
3509 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3511 $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).
"'";
3512 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
3513 $resql = $this->db->query($sql);
3516 $this->error = $this->db->lasterror();
3518 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3519 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
3520 $resql = $this->db->query($sql);
3523 $this->error = $this->db->lasterror();
3529 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3530 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3531 if (!$error && file_exists($dirsource)) {
3532 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3534 if (@rename($dirsource, $dirdest)) {
3537 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3538 foreach ($listoffiles as $fileentry) {
3539 $dirsource = $fileentry[
'name'];
3540 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3541 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3542 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3543 @rename($dirsource, $dirdest);
3561 $this->date_validation = $now;
3566 $nboflines = count($this->lines);
3567 while (($i < $nboflines) && $final) {
3569 $previousprogress = $this->lines[$i]->get_allprev_progress($this->lines[$i]->fk_facture);
3570 $current_progress = floatval($this->lines[$i]->situation_percent);
3571 $full_progress = $previousprogress + $current_progress;
3572 $final = ($full_progress == 100);
3574 $final = ($this->lines[$i]->situation_percent == 100);
3579 if (empty($final)) {
3580 $this->situation_final = 0;
3582 $this->situation_final = 1;
3593 $this->db->commit();
3596 $this->db->rollback();
3609 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3610 $is_last = $next_invoice->is_last_in_cycle();
3612 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
3613 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3617 foreach ($next_invoice->lines as $line) {
3618 $result = $next_invoice->updateline(
3623 $line->remise_percent,
3627 $line->localtax1_tx,
3628 $line->localtax2_tx,
3631 $line->product_type,
3632 $line->fk_parent_line,
3634 $line->fk_fournprice,
3637 $line->special_code,
3638 $line->array_options,
3639 $line->situation_percent,
3644 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3665 global $conf, $langs;
3669 if ($this->
status == self::STATUS_DRAFT) {
3670 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3678 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3679 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3680 $sql .=
" WHERE rowid = ".((int) $this->
id);
3682 $result = $this->db->query($sql);
3685 $this->oldcopy = clone $this;
3689 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL')) {
3690 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3691 $langs->load(
"agenda");
3693 $num = count($this->lines);
3694 for ($i = 0; $i < $num; $i++) {
3695 if ($this->lines[$i]->fk_product > 0) {
3697 $mouvP->origin = &$this;
3698 $mouvP->setOrigin($this->element, $this->
id);
3700 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3701 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3703 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3710 $old_statut = $this->status;
3715 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3718 $this->
statut = $old_statut;
3719 $this->
status = $old_statut;
3723 $this->db->rollback();
3728 $this->db->commit();
3731 $this->db->rollback();
3735 $this->error = $this->db->error();
3736 $this->db->rollback();
3791 $remise_percent = 0,
3794 $fk_code_ventilation = 0,
3796 $fk_remise_except = 0,
3797 $price_base_type =
'HT',
3804 $fk_parent_line = 0,
3805 $fk_fournprice =
null,
3808 $array_options = array(),
3809 $situation_percent = 100,
3814 $noupdateafterinsertline = 0
3818 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3822 global $mysoc, $conf, $langs;
3824 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, fk_code_ventilation=$fk_code_ventilation, 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);
3826 if ($this->
status == self::STATUS_DRAFT) {
3827 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3830 if (empty($remise_percent)) {
3831 $remise_percent = 0;
3836 if (empty($info_bits)) {
3842 if (empty($fk_code_ventilation)) {
3843 $fk_code_ventilation = 0;
3845 if (empty($txtva)) {
3848 if (empty($txlocaltax1)) {
3851 if (empty($txlocaltax2)) {
3854 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3855 $fk_parent_line = 0;
3857 if (empty($fk_prev_id)) {
3858 $fk_prev_id =
'null';
3860 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3861 $situation_percent = 100;
3863 if (empty($ref_ext)) {
3867 $remise_percent = (float)
price2num($remise_percent);
3870 $pu_ht_devise =
price2num($pu_ht_devise);
3873 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
3879 if ($price_base_type ==
'HT') {
3890 if ($date_start && $date_end && $date_start > $date_end) {
3891 $langs->load(
"errors");
3892 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3898 $product_type = $type;
3899 if (!empty($fk_product) && $fk_product > 0) {
3900 $product =
new Product($this->db);
3901 $result = $product->fetch($fk_product);
3902 $product_type = $product->type;
3904 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
3905 $langs->load(
"errors");
3906 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3907 $this->db->rollback();
3917 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3918 $vat_src_code = $reg[1];
3919 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3927 $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);
3929 $total_ht = $tabprice[0];
3930 $total_tva = $tabprice[1];
3931 $total_ttc = $tabprice[2];
3932 $total_localtax1 = $tabprice[9];
3933 $total_localtax2 = $tabprice[10];
3934 $pu_ht = $tabprice[3];
3937 $multicurrency_total_ht = $tabprice[16];
3938 $multicurrency_total_tva = $tabprice[17];
3939 $multicurrency_total_ttc = $tabprice[18];
3940 $pu_ht_devise = $tabprice[19];
3944 if ($ranktouse == -1) {
3945 $rangmax = $this->
line_max($fk_parent_line);
3946 $ranktouse = $rangmax + 1;
3952 $this->line->context = $this->context;
3954 $this->line->fk_facture = $this->id;
3955 $this->line->label = $label;
3956 $this->line->desc = $desc;
3957 $this->line->ref_ext = $ref_ext;
3959 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
3960 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
3962 $this->line->vat_src_code = $vat_src_code;
3963 $this->line->tva_tx = $txtva;
3964 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3965 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3966 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
3967 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
3969 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
3970 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
3971 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
3972 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
3973 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
3975 $this->line->fk_product = $fk_product;
3976 $this->line->product_type = $product_type;
3977 $this->line->remise_percent = $remise_percent;
3978 $this->line->date_start = $date_start;
3979 $this->line->date_end = $date_end;
3980 $this->line->fk_code_ventilation = $fk_code_ventilation;
3981 $this->line->rang = $ranktouse;
3982 $this->line->info_bits = $info_bits;
3983 $this->line->fk_remise_except = $fk_remise_except;
3985 $this->line->special_code = $special_code;
3986 $this->line->fk_parent_line = $fk_parent_line;
3987 $this->line->origin = $origin;
3988 $this->line->origin_id = $origin_id;
3989 $this->line->situation_percent = $situation_percent;
3990 $this->line->fk_prev_id = $fk_prev_id;
3991 $this->line->fk_unit = $fk_unit;
3994 $this->line->fk_fournprice = $fk_fournprice;
3995 $this->line->pa_ht = $pa_ht;
3998 $this->line->fk_multicurrency = $this->fk_multicurrency;
3999 $this->line->multicurrency_code = $this->multicurrency_code;
4000 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
4002 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
4003 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
4004 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4006 if (is_array($array_options) && count($array_options) > 0) {
4007 $this->line->array_options = $array_options;
4010 $result = $this->line->insert();
4013 if (!empty($fk_parent_line)) {
4015 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4016 $linecount = count($this->lines);
4017 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4023 if (empty($noupdateafterinsertline)) {
4028 $this->db->commit();
4029 return $this->line->id;
4031 $this->error = $this->db->lasterror();
4032 $this->db->rollback();
4036 $this->error = $this->line->error;
4037 $this->errors = $this->line->errors;
4038 $this->db->rollback();
4042 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4043 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4079 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 = array(), $situation_percent = 100, $fk_unit =
null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext =
'', $rang = 0)
4081 global $conf, $user;
4084 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4087 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4089 global $mysoc, $langs;
4091 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);
4093 if ($this->
status == self::STATUS_DRAFT) {
4096 if (!$this->error) {
4097 $this->error = $langs->trans(
'invoiceLineProgressError');
4103 if ($date_start && $date_end && $date_start > $date_end) {
4104 $langs->load(
"errors");
4105 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4115 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4116 $fk_parent_line = 0;
4118 if (empty($special_code) || $special_code == 3) {
4121 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4122 $situation_percent = 100;
4124 if (empty($ref_ext)) {
4128 $remise_percent = (float)
price2num($remise_percent);
4131 $pu_ht_devise =
price2num($pu_ht_devise);
4133 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4136 $txlocaltax1 = (float)
price2num($txlocaltax1);
4137 $txlocaltax2 = (float)
price2num($txlocaltax2);
4153 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4154 $vat_src_code = $reg[1];
4155 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4158 $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);
4160 $total_ht = $tabprice[0];
4161 $total_tva = $tabprice[1];
4162 $total_ttc = $tabprice[2];
4163 $total_localtax1 = $tabprice[9];
4164 $total_localtax2 = $tabprice[10];
4165 $pu_ht = $tabprice[3];
4166 $pu_tva = $tabprice[4];
4167 $pu_ttc = $tabprice[5];
4170 $multicurrency_total_ht = $tabprice[16];
4171 $multicurrency_total_tva = $tabprice[17];
4172 $multicurrency_total_ttc = $tabprice[18];
4173 $pu_ht_devise = $tabprice[19];
4178 if ($remise_percent > 0) {
4179 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4180 $price = ((float) $pu - $remise);
4186 $line->fetch($rowid);
4187 $line->fetch_optionals();
4189 if (!empty($line->fk_product)) {
4190 $product =
new Product($this->db);
4191 $result = $product->fetch($line->fk_product);
4192 $product_type = $product->type;
4194 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4195 $langs->load(
"errors");
4196 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4197 $this->db->rollback();
4202 $staticline = clone $line;
4204 $line->oldline = $staticline;
4205 $this->line = $line;
4206 $this->line->context = $this->context;
4207 $this->line->rang = $rang;
4210 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4211 $rangmax = $this->
line_max($fk_parent_line);
4212 $this->line->rang = $rangmax + 1;
4215 $this->line->id = $rowid;
4216 $this->line->rowid = $rowid;
4217 $this->line->label = $label;
4218 $this->line->desc = $desc;
4219 $this->line->ref_ext = $ref_ext;
4220 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4222 $this->line->vat_src_code = $vat_src_code;
4223 $this->line->tva_tx = $txtva;
4224 $this->line->localtax1_tx = $txlocaltax1;
4225 $this->line->localtax2_tx = $txlocaltax2;
4226 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4227 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4229 $this->line->remise_percent = $remise_percent;
4230 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
4231 $this->line->date_start = $date_start;
4232 $this->line->date_end = $date_end;
4233 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
4234 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
4235 $this->line->total_localtax1 = $total_localtax1;
4236 $this->line->total_localtax2 = $total_localtax2;
4237 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
4238 $this->line->info_bits = $info_bits;
4239 $this->line->special_code = $special_code;
4240 $this->line->product_type = $type;
4241 $this->line->fk_parent_line = $fk_parent_line;
4242 $this->line->skip_update_total = $skip_update_total;
4243 $this->line->situation_percent = $situation_percent;
4244 $this->line->fk_unit = $fk_unit;
4246 $this->line->fk_fournprice = $fk_fournprice;
4247 $this->line->pa_ht = $pa_ht;
4250 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
4251 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
4252 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
4253 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4255 if (is_array($array_options) && count($array_options) > 0) {
4257 foreach ($array_options as $key => $value) {
4258 $this->line->array_options[$key] = $array_options[$key];
4262 $result = $this->line->update($user, $notrigger);
4265 if (!empty($fk_parent_line)) {
4271 $this->db->commit();
4274 $this->error = $this->line->error;
4275 $this->db->rollback();
4279 $this->error =
"Invoice statut makes operation forbidden";
4293 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4294 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4295 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4297 $result = $this->db->query($sql);
4299 $this->error = $this->db->error();
4303 $obj = $this->db->fetch_object($result);
4305 if ($obj ===
null) {
4308 return ($situation_percent < $obj->situation_percent);
4324 global $mysoc, $user;
4327 if (($line->info_bits & 2) == 2) {
4331 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4334 if ($percent > 100) {
4338 $previous_progress = $line->get_allprev_progress($line->fk_facture);
4339 $current_progress = $percent - $previous_progress;
4340 $line->situation_percent = $current_progress;
4341 $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,
'', $current_progress);
4343 $line->situation_percent = $percent;
4344 $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);
4346 $line->total_ht = $tabprice[0];
4347 $line->total_tva = $tabprice[1];
4348 $line->total_ttc = $tabprice[2];
4349 $line->total_localtax1 = $tabprice[9];
4350 $line->total_localtax2 = $tabprice[10];
4351 $line->multicurrency_total_ht = $tabprice[16];
4352 $line->multicurrency_total_tva = $tabprice[17];
4353 $line->multicurrency_total_ttc = $tabprice[18];
4354 $line->update($user);
4357 if ($update_price) {
4373 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4375 if ($this->
status != self::STATUS_DRAFT) {
4376 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4382 $line->context = $this->context;
4385 $result = $line->fetch($rowid);
4386 if (!($result > 0)) {
4391 if ($id > 0 && $line->fk_facture != $id) {
4392 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4399 $staticline = clone $line;
4400 $line->oldline = $staticline;
4402 if ($line->delete($user) > 0) {
4406 $this->db->commit();
4409 $this->db->rollback();
4410 $this->error = $this->db->lasterror();
4414 $this->db->rollback();
4415 $this->error = $line->error;
4434 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4436 return $this->
setDiscount($user, $remise, $notrigger);
4450 if (empty($remise)) {
4454 if ($user->hasRight(
'facture',
'creer')) {
4455 $remise = (float)
price2num($remise, 2);
4461 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4462 $sql .=
" SET remise_percent = ".((float) $remise);
4463 $sql .=
" WHERE rowid = ".((int) $this->
id);
4464 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
4467 $resql = $this->db->query($sql);
4469 $this->errors[] = $this->db->error();
4473 if (!$notrigger && empty($error)) {
4483 $this->remise_percent = $remise;
4486 $this->db->commit();
4489 foreach ($this->errors as $errmsg) {
4490 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4491 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4493 $this->db->rollback();
4580 global $conf, $langs;
4582 if ($this->module_source ==
'takepos') {
4583 $langs->load(
'cashdesk');
4585 $moduleName =
'takepos';
4586 $moduleSourceName =
'Takepos';
4587 $addonConstName =
'TAKEPOS_REF_ADDON';
4591 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4596 $langs->load(
'bills');
4598 $moduleName =
'facture';
4599 $moduleSourceName =
'Invoice';
4600 $addonConstName =
'FACTURE_ADDON';
4604 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4606 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4608 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4614 if (!empty($addon)) {
4615 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4619 $file = $addon.
'.php';
4620 $classname = $addon;
4624 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4625 foreach ($dirmodels as $reldir) {
4626 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4629 if (is_file($dir.$file) && is_readable($dir.$file)) {
4630 $mybool = ((bool) include_once $dir.$file) || $mybool;
4636 $file = $addon.
'/'.$addon.
'.modules.php';
4637 $classname =
'mod_'.$moduleName.
'_'.$addon;
4638 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4640 foreach ($conf->file->dol_document_root as $dirroot) {
4641 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4644 if (is_file($dir.$file) && is_readable($dir.$file)) {
4645 $mybool = (include_once $dir.$file) || $mybool;
4655 $obj =
new $classname();
4656 '@phan-var-force CommonNumRefGenerator $obj';
4658 $numref = $obj->getNextValue($soc, $this, $mode);
4665 if ($mode !=
'last' && !$numref) {
4666 $this->error = $obj->error;
4672 $langs->load(
'errors');
4673 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4686 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4687 $sql .=
' date_closing as dateclosing,';
4688 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4689 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4690 $sql .=
' WHERE c.rowid = '.((int) $id);
4692 $result = $this->db->query($sql);
4694 if ($this->db->num_rows($result)) {
4695 $obj = $this->db->fetch_object($result);
4697 $this->
id = $obj->rowid;
4698 $this->user_creation_id = $obj->fk_user_author;
4699 $this->user_validation_id = $obj->fk_user_valid;
4700 $this->user_closing_id = $obj->fk_user_closing;
4702 $this->date_creation = $this->db->jdate($obj->datec);
4703 $this->date_modification = $this->db->jdate($obj->datem);
4704 $this->date_validation = $this->db->jdate($obj->datev);
4705 $this->date_closing = $this->db->jdate($obj->dateclosing);
4707 $this->db->free($result);
4728 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4735 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4736 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4737 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4738 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4739 $sql .=
" AND f.fk_soc = s.rowid";
4741 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4743 if (is_object($excluser)) {
4744 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4748 if (!$user->hasRight(
'societe',
'client',
'voir')) {
4749 $search_sale = $user->id;
4752 if ($search_sale && $search_sale !=
'-1') {
4753 if ($search_sale == -2) {
4754 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
4755 } elseif ($search_sale > 0) {
4756 $sql .=
" AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = ".((int) $search_sale).
")";
4761 $sql .=
" AND f.fk_soc = ".((int) $socid);
4763 $sql .= $this->db->order($sortfield, $sortorder);
4764 $sql .= $this->db->plimit($limit, $offset);
4766 $result = $this->db->query($sql);
4768 $numc = $this->db->num_rows($result);
4771 while ($i < $numc) {
4772 $obj = $this->db->fetch_object($result);
4774 if ($shortlist == 1) {
4775 $ga[$obj->fid] = $obj->ref;
4776 } elseif ($shortlist == 2) {
4777 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4779 $ga[$i][
'id'] = $obj->fid;
4780 $ga[$i][
'ref'] = $obj->ref;
4781 $ga[$i][
'name'] = $obj->name;
4810 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4811 $sql .=
" ff.rowid as rowidnext";
4813 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4814 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4815 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4816 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4817 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4818 $sql .=
" AND f.paye = 0";
4819 $sql .=
" AND pf.fk_paiement IS NULL";
4820 $sql .=
" AND ff.fk_statut IS NULL";
4822 $sql .=
" AND f.fk_soc = ".((int) $socid);
4825 $sql .=
" ORDER BY f.ref";
4827 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4828 $resql = $this->db->query($sql);
4830 while ($obj = $this->db->fetch_object($resql)) {
4831 $return[$obj->rowid] = array(
4832 'id' => $obj->rowid,
4834 'status' => $obj->status,
4835 'paid' => $obj->paid,
4842 $this->error = $this->db->error();
4865 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
4866 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4867 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4868 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4869 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4870 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4874 $sql .=
" AND ff.type IS NULL";
4875 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4879 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4880 $sql .=
'(SELECT MAX(fs.rowid)';
4881 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4882 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4883 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4884 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4886 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4888 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4891 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4895 $sql .=
" AND f.fk_soc = ".((int) $socid);
4897 $sql .=
" ORDER BY f.ref";
4899 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4900 $resql = $this->db->query($sql);
4902 while ($obj = $this->db->fetch_object($resql)) {
4904 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4907 if ($obj->fk_statut == self::STATUS_CLOSED) {
4912 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4913 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
4919 $this->error = $this->db->error();
4935 global $conf, $langs;
4939 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
4940 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4941 if (!$user->hasRight(
'societe',
'client',
'voir')) {
4942 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4943 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4946 $sql .= $clause.
" f.paye=0";
4947 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4948 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
4950 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
4953 $resql = $this->db->query($sql);
4955 $langs->load(
"bills");
4959 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4960 $response->label = $langs->trans(
"CustomerBillsUnpaid");
4961 $response->labelShort = $langs->trans(
"Unpaid");
4962 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4965 $generic_facture =
new Facture($this->db);
4967 while ($obj = $this->db->fetch_object($resql)) {
4968 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
4969 $generic_facture->statut = $obj->status;
4970 $generic_facture->status = $obj->status;
4972 $response->nbtodo++;
4973 $response->total += $obj->total_ht;
4975 if ($generic_facture->hasDelay()) {
4976 $response->nbtodolate++;
4977 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4981 $this->db->free($resql);
4985 $this->error = $this->db->error();
5024 global $conf, $langs, $user;
5028 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5033 $sql =
"SELECT rowid";
5034 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5035 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5036 $sql .= $this->db->plimit(100);
5038 $resql = $this->db->query($sql);
5040 $num_prods = $this->db->num_rows($resql);
5042 while ($i < $num_prods) {
5044 $row = $this->db->fetch_row($resql);
5045 $prodids[$i] = $row[0];
5049 if (empty($num_prods)) {
5056 $this->
ref =
'SPECIMEN';
5057 $this->specimen = 1;
5059 $this->date = $nownotime;
5060 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5061 $this->cond_reglement_id = 1;
5062 $this->cond_reglement_code =
'RECEP';
5064 $this->mode_reglement_id = 0;
5065 $this->mode_reglement_code =
'';
5067 $this->note_public =
'This is a comment (public)';
5068 $this->note_private =
'This is a comment (private)';
5069 $this->note =
'This is a comment (private)';
5071 $this->fk_user_author = $user->id;
5073 $this->multicurrency_tx = 1;
5074 $this->multicurrency_code = $conf->currency;
5076 $this->fk_incoterms = 0;
5077 $this->location_incoterms =
'';
5079 if (empty($option) || $option !=
'nolines') {
5083 while ($xnbp < $nbp) {
5085 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5087 $line->subprice = 100;
5088 $line->tva_tx = 19.6;
5089 $line->localtax1_tx = 0;
5090 $line->localtax2_tx = 0;
5091 $line->remise_percent = 0;
5093 $prodid = mt_rand(1, $num_prods);
5094 $line->fk_product = $prodids[$prodid];
5096 $line->total_ht = -100;
5097 $line->total_ttc = -119.6;
5098 $line->total_tva = -19.6;
5099 $line->multicurrency_total_ht = -200;
5100 $line->multicurrency_total_ttc = -239.2;
5101 $line->multicurrency_total_tva = -39.2;
5102 } elseif ($xnbp == 2) {
5103 $line->subprice = -100;
5104 $line->total_ht = -100;
5105 $line->total_ttc = -119.6;
5106 $line->total_tva = -19.6;
5107 $line->remise_percent = 0;
5108 $line->multicurrency_total_ht = -200;
5109 $line->multicurrency_total_ttc = -239.2;
5110 $line->multicurrency_total_tva = -39.2;
5111 } elseif ($xnbp == 3) {
5112 $prodid = mt_rand(1, $num_prods);
5113 $line->fk_product = $prodids[$prodid];
5114 $line->total_ht = 50;
5115 $line->total_ttc = 59.8;
5116 $line->total_tva = 9.8;
5117 $line->multicurrency_total_ht = 100;
5118 $line->multicurrency_total_ttc = 119.6;
5119 $line->multicurrency_total_tva = 19.6;
5120 $line->remise_percent = 50;
5122 $prodid = mt_rand(1, $num_prods);
5123 $line->fk_product = $prodids[$prodid];
5124 $line->total_ht = 100;
5125 $line->total_ttc = 119.6;
5126 $line->total_tva = 19.6;
5127 $line->multicurrency_total_ht = 200;
5128 $line->multicurrency_total_ttc = 239.2;
5129 $line->multicurrency_total_tva = 39.2;
5130 $line->remise_percent = 0;
5133 $this->lines[$xnbp] = $line;
5136 $this->total_ht += $line->total_ht;
5137 $this->total_tva += $line->total_tva;
5138 $this->total_ttc += $line->total_ttc;
5140 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5141 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5142 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5146 $this->revenuestamp = 0;
5150 $line->desc = $langs->trans(
"Description").
" (offered line)";
5152 $line->subprice = 100;
5153 $line->tva_tx = 19.6;
5154 $line->localtax1_tx = 0;
5155 $line->localtax2_tx = 0;
5156 $line->remise_percent = 100;
5157 $line->total_ht = 0;
5158 $line->total_ttc = 0;
5159 $line->total_tva = 0;
5160 $line->multicurrency_total_ht = 0;
5161 $line->multicurrency_total_ttc = 0;
5162 $line->multicurrency_total_tva = 0;
5163 $prodid = mt_rand(1, $num_prods);
5164 $line->fk_product = $prodids[$prodid];
5166 $this->lines[$xnbp] = $line;
5180 global $conf, $user;
5182 $this->nb = array();
5186 $sql =
"SELECT count(f.rowid) as nb";
5187 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5188 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5189 if (!$user->hasRight(
'societe',
'client',
'voir')) {
5190 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5191 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5194 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
5196 $resql = $this->db->query($sql);
5198 while ($obj = $this->db->fetch_object($resql)) {
5199 $this->nb[
"invoices"] = $obj->nb;
5201 $this->db->free($resql);
5205 $this->error = $this->db->error();
5231 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5233 global $conf, $langs;
5235 $outputlangs->loadLangs(array(
"bills",
"products"));
5239 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5241 if (!empty($this->model_pdf)) {
5242 $modele = $this->model_pdf;
5250 $modelpath =
"core/modules/facture/doc/";
5252 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5262 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5263 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5264 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5266 $resql = $this->db->query($sql);
5268 if ($this->db->num_rows($resql) > 0) {
5270 $obj = $this->db->fetch_object($resql);
5272 $ref = $obj->maxsituationref;
5278 $this->db->free($resql);
5281 $this->error = $this->db->lasterror();
5282 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5296 return ($this->situation_counter == 1);
5310 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5311 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5312 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5313 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5314 $resql = $this->db->query($sql);
5316 if ($resql && $this->db->num_rows($resql) > 0) {
5317 while ($row = $this->db->fetch_object($resql)) {
5319 $situation =
new Facture($this->db);
5320 $situation->fetch($id);
5321 $res[] = $situation;
5324 $this->error = $this->db->error();
5325 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5345 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5348 $resql = $this->db->query($sql);
5350 $this->errors[] = $this->db->error();
5354 if (!$notrigger && empty($error)) {
5364 $this->db->commit();
5367 foreach ($this->errors as $errmsg) {
5368 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5369 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5371 $this->db->rollback();
5387 if (!empty($this->situation_cycle_ref)) {
5389 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5390 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5391 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5392 $resql = $this->db->query($sql);
5394 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5395 $last = $res[
'max(situation_counter)'];
5396 return ($last == $this->situation_counter);
5398 $this->error = $this->db->lasterror();
5399 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5457 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5458 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5460 $totalpaid = (float) $totalpaid;
5462 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5463 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5465 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5488 $displayWarranty =
false;
5489 if (!empty($this->retained_warranty)) {
5490 $displayWarranty =
true;
5494 $displayWarranty =
false;
5495 if (!empty($this->situation_final)) {
5496 $displayWarranty =
true;
5499 $displayWarranty =
true;
5501 foreach ($this->lines as $i => $line) {
5502 if ($line->product_type < 2 && $line->situation_percent < 100) {
5503 $displayWarranty =
false;
5511 return $displayWarranty;
5521 if (empty($this->retained_warranty)) {
5525 $retainedWarrantyAmount = 0;
5529 $displayWarranty =
true;
5531 if (!empty($this->lines)) {
5532 foreach ($this->lines as $i => $line) {
5533 if ($line->product_type < 2 && $line->situation_percent < 100) {
5534 $displayWarranty =
false;
5540 if ($displayWarranty && !empty($this->situation_final)) {
5542 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5545 foreach ($TPreviousIncoice as &$fac) {
5546 $total2BillWT += $fac->total_ttc;
5548 $total2BillWT += $this->total_ttc;
5550 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5556 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5559 if ($rounding < 0) {
5563 if ($rounding > 0) {
5564 return round($retainedWarrantyAmount, $rounding);
5567 return $retainedWarrantyAmount;
5578 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5580 if ($this->
status >= 0) {
5581 $fieldname =
'retained_warranty';
5582 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5583 $sql .=
" SET ".$fieldname.
" = ".((float) $value);
5584 $sql .=
' WHERE rowid='.((int) $this->
id);
5586 if ($this->db->query($sql)) {
5587 $this->retained_warranty = (float) $value;
5590 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5591 $this->error = $this->db->error();
5595 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5596 $this->error =
'Status of the object is incompatible '.$this->status;
5611 if (!$timestamp && $dateYmd) {
5612 $timestamp = $this->db->jdate($dateYmd);
5616 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5617 if ($this->
status >= 0) {
5618 $fieldname =
'retained_warranty_date_limit';
5619 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5620 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5621 $sql .=
' WHERE rowid = '.((int) $this->
id);
5623 if ($this->db->query($sql)) {
5624 $this->retained_warranty_date_limit = $timestamp;
5627 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5628 $this->error = $this->db->error();
5632 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5633 $this->error =
'Status of the object is incompatible '.$this->status;
5652 global $conf, $langs, $user;
5658 $errorsMsg = array();
5660 $langs->load(
"bills");
5662 if (!isModEnabled(
'invoice')) {
5663 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5666 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
5667 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
5677 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5678 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5679 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5680 $formmail =
new FormMail($this->db);
5685 $tmpinvoice =
new Facture($this->db);
5690 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5691 if (!empty($paymentmode) && $paymentmode !=
'all') {
5692 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5694 $sql .=
" WHERE f.paye = 0";
5695 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5696 if ($datetouse ==
'invoicedate') {
5697 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
5699 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5701 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
5702 if (!empty($paymentmode) && $paymentmode !=
'all') {
5703 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5706 if ($datetouse ==
'invoicedate') {
5707 $sql .= $this->db->order(
"datef",
"ASC");
5709 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
5712 $resql = $this->db->query($sql);
5715 if ($datetouse ==
'invoicedate') {
5716 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
5718 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5720 if (!empty($paymentmode) && $paymentmode !=
'all') {
5721 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5723 $this->output .=
'<br>';
5726 while ($obj = $this->db->fetch_object($resql)) {
5729 $res = $tmpinvoice->fetch($obj->id);
5731 $tmpinvoice->fetch_thirdparty();
5733 $outputlangs =
new Translate(
'', $conf);
5734 if ($tmpinvoice->thirdparty->default_lang) {
5735 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5736 $outputlangs->loadLangs(array(
"main",
"bills"));
5738 $outputlangs = $langs;
5742 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5743 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5744 $langs->load(
"errors");
5745 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5758 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5761 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5767 if ($forcerecipient) {
5768 $to = array($forcerecipient);
5770 $res = $tmpinvoice->fetch_thirdparty();
5771 $recipient = $tmpinvoice->thirdparty;
5773 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
5774 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5775 foreach ($tmparraycontact as $data_email) {
5776 if (!empty($data_email[
'email'])) {
5777 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
5781 if (empty($to) && !empty($recipient->email)) {
5782 $to[] = $recipient->email;
5785 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
5789 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5796 if (!empty($arraymessage->email_from)) {
5797 $from = $arraymessage->email_from;
5800 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5804 if (!$error && !empty($to)) {
5807 $to = implode(
',', $to);
5808 if (!empty($arraymessage->email_to)) {
5809 $to = $to.
','.$arraymessage->email_to;
5815 $trackid =
'inv'.$tmpinvoice->id;
5816 $sendcontext =
'standard';
5819 if (!empty($arraymessage->email_tocc)) {
5820 $email_tocc = $arraymessage->email_tocc;
5824 if (!empty($arraymessage->email_tobcc)) {
5825 $email_tobcc = $arraymessage->email_tobcc;
5832 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5833 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
5834 $joinFileName[] = basename($tmpinvoice->last_main_doc);
5835 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
5839 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5842 if ($cMailFile->sendfile()) {
5846 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5851 $actioncomm->type_code =
'AC_OTH_AUTO';
5852 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5853 $actioncomm->contact_id = 0;
5855 $actioncomm->code =
'AC_EMAIL';
5856 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
5857 $actioncomm->note_private = $sendContent;
5858 $actioncomm->fk_project = $tmpinvoice->fk_project;
5859 $actioncomm->datep =
dol_now();
5860 $actioncomm->datef = $actioncomm->datep;
5861 $actioncomm->percentage = -1;
5862 $actioncomm->authorid = $user->id;
5863 $actioncomm->userownerid = $user->id;
5865 $actioncomm->email_msgid = $cMailFile->msgid;
5866 $actioncomm->email_subject = $sendTopic;
5867 $actioncomm->email_from = $from;
5868 $actioncomm->email_sender =
'';
5869 $actioncomm->email_to = $to;
5873 $actioncomm->errors_to = $errors_to;
5875 $actioncomm->elementtype =
'invoice';
5876 $actioncomm->fk_element = $tmpinvoice->id;
5880 $actioncomm->create($user);
5882 $errormesg = $cMailFile->error.
' : '.$to;
5886 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5891 $actioncomm->type_code =
'AC_OTH_AUTO';
5892 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5893 $actioncomm->contact_id = 0;
5895 $actioncomm->code =
'AC_EMAIL';
5896 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5897 $actioncomm->note_private = $errormesg;
5898 $actioncomm->fk_project = $tmpinvoice->fk_project;
5899 $actioncomm->datep =
dol_now();
5900 $actioncomm->datef = $actioncomm->datep;
5901 $actioncomm->percentage = -1;
5902 $actioncomm->authorid = $user->id;
5903 $actioncomm->userownerid = $user->id;
5905 $actioncomm->email_msgid = $cMailFile->msgid;
5906 $actioncomm->email_from = $from;
5907 $actioncomm->email_sender =
'';
5908 $actioncomm->email_to = $to;
5912 $actioncomm->errors_to = $errors_to;
5916 $actioncomm->create($user);
5919 $this->db->commit();
5923 $errorsMsg[] = $errormesg;
5926 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
5936 $this->output .=
'Nb of emails sent : '.$nbMailSend;
5938 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
5942 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
5944 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
5959 $sql =
"SELECT datef";
5960 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
5961 $sql .=
" WHERE type = " . (int) $this->
type ;
5962 $sql .=
" AND date_valid IS NOT NULL";
5963 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
5964 $sql .=
" ORDER BY datef DESC LIMIT 1";
5966 $result = $this->db->query($sql);
5969 if ($this->db->num_rows($result)) {
5970 $obj = $this->db->fetch_object($result);
5971 $last_date = $this->db->jdate($obj->datef);
5972 $invoice_date = $this->date;
5974 $is_last_of_same_type = $invoice_date >= $last_date;
5975 if ($allow_validated_drafts) {
5979 return array($is_last_of_same_type, $last_date);
6002 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6004 $picto = $this->picto;
6005 if ($this->
type == self::TYPE_REPLACEMENT) {
6008 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6011 if ($this->
type == self::TYPE_DEPOSIT) {
6015 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6016 $return .=
'<div class="info-box info-box-sm">';
6017 $return .=
'<span class="info-box-icon bg-infobox-action">';
6019 $return .=
'</span>';
6020 $return .=
'<div class="info-box-content">';
6021 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6022 if ($selected >= 0) {
6023 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6025 if (!empty($arraydata[
'thirdparty'])) {
6026 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6028 if (property_exists($this,
'date')) {
6029 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->date,
'day').
'</span>';
6031 if (property_exists($this,
'total_ht')) {
6032 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6033 $return .=
' '.$langs->trans(
"HT");
6034 $return .=
'</span>';
6036 if (method_exists($this,
'getLibStatut')) {
6037 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6038 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6040 $return .=
'</div>';
6041 $return .=
'</div>';
6042 $return .=
'</div>';
6056 public $element =
'facturedet';
6061 public $table_element =
'facturedet';
6078 public $localtax1_type;
6079 public $localtax2_type;
6080 public $fk_remise_except;
6083 public $fk_fournprice;
6093 public $remise_percent;
6102 public $fk_warehouse;
6111 public $fk_code_ventilation = 0;
6117 public $skip_update_total;
6122 public $situation_percent;
6148 $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,';
6149 $sql .=
' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
6150 $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,';
6151 $sql .=
' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
6152 $sql .=
' fd.fk_code_ventilation,';
6153 $sql .=
' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
6154 $sql .=
' fd.situation_percent, fd.fk_prev_id,';
6155 $sql .=
' fd.multicurrency_subprice,';
6156 $sql .=
' fd.multicurrency_total_ht,';
6157 $sql .=
' fd.multicurrency_total_tva,';
6158 $sql .=
' fd.multicurrency_total_ttc,';
6159 $sql .=
' p.ref as product_ref, p.label as product_label, p.description as product_desc';
6160 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as fd';
6161 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON fd.fk_product = p.rowid';
6162 $sql .=
' WHERE fd.rowid = '.((int) $rowid);
6164 $result = $this->db->query($sql);
6166 $objp = $this->db->fetch_object($result);
6169 $this->error =
'InvoiceLine with id '. $rowid .
' not found sql='.$sql;
6173 $this->
rowid = $objp->rowid;
6174 $this->
id = $objp->rowid;
6175 $this->fk_facture = $objp->fk_facture;
6176 $this->fk_parent_line = $objp->fk_parent_line;
6177 $this->label = $objp->custom_label;
6178 $this->desc = $objp->description;
6179 $this->qty = $objp->qty;
6180 $this->subprice = $objp->subprice;
6181 $this->ref_ext = $objp->ref_ext;
6182 $this->vat_src_code = $objp->vat_src_code;
6183 $this->tva_tx = $objp->tva_tx;
6184 $this->localtax1_tx = $objp->localtax1_tx;
6185 $this->localtax2_tx = $objp->localtax2_tx;
6186 $this->remise_percent = $objp->remise_percent;
6187 $this->fk_remise_except = $objp->fk_remise_except;
6188 $this->fk_product = $objp->fk_product;
6189 $this->product_type = $objp->product_type;
6190 $this->date_start = $this->db->jdate($objp->date_start);
6191 $this->date_end = $this->db->jdate($objp->date_end);
6192 $this->info_bits = $objp->info_bits;
6193 $this->tva_npr = (($objp->info_bits & 1) == 1) ? 1 : 0;
6194 $this->special_code = $objp->special_code;
6195 $this->total_ht = $objp->total_ht;
6196 $this->total_tva = $objp->total_tva;
6197 $this->total_localtax1 = $objp->total_localtax1;
6198 $this->total_localtax2 = $objp->total_localtax2;
6199 $this->total_ttc = $objp->total_ttc;
6200 $this->fk_code_ventilation = $objp->fk_code_ventilation;
6201 $this->rang = $objp->rang;
6202 $this->fk_fournprice = $objp->fk_fournprice;
6203 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
6204 $this->pa_ht = $marginInfos[0];
6205 $this->marge_tx = $marginInfos[1];
6206 $this->marque_tx = $marginInfos[2];
6208 $this->
ref = $objp->product_ref;
6210 $this->product_ref = $objp->product_ref;
6211 $this->product_label = $objp->product_label;
6212 $this->product_desc = $objp->product_desc;
6214 $this->fk_unit = $objp->fk_unit;
6215 $this->fk_user_modif = $objp->fk_user_modif;
6216 $this->fk_user_author = $objp->fk_user_author;
6218 $this->situation_percent = $objp->situation_percent;
6219 $this->fk_prev_id = $objp->fk_prev_id;
6221 $this->multicurrency_subprice = $objp->multicurrency_subprice;
6222 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
6223 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
6224 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
6228 $this->db->free($result);
6232 $this->error = $this->db->lasterror();
6244 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
6246 global $langs, $user;
6250 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6252 dol_syslog(get_class($this).
"::insert rang=".$this->rang, LOG_DEBUG);
6255 $this->desc = trim($this->desc);
6256 if (empty($this->tva_tx)) {
6259 if (empty($this->localtax1_tx)) {
6260 $this->localtax1_tx = 0;
6262 if (empty($this->localtax2_tx)) {
6263 $this->localtax2_tx = 0;
6265 if (empty($this->localtax1_type)) {
6266 $this->localtax1_type = 0;
6268 if (empty($this->localtax2_type)) {
6269 $this->localtax2_type = 0;
6271 if (empty($this->total_localtax1)) {
6272 $this->total_localtax1 = 0;
6274 if (empty($this->total_localtax2)) {
6275 $this->total_localtax2 = 0;
6277 if (empty($this->rang)) {
6280 if (empty($this->remise_percent)) {
6281 $this->remise_percent = 0;
6283 if (empty($this->info_bits)) {
6284 $this->info_bits = 0;
6286 if (empty($this->subprice)) {
6287 $this->subprice = 0;
6289 if (empty($this->ref_ext)) {
6290 $this->ref_ext =
'';
6292 if (empty($this->special_code)) {
6293 $this->special_code = 0;
6295 if (empty($this->fk_parent_line)) {
6296 $this->fk_parent_line = 0;
6298 if (empty($this->fk_prev_id)) {
6299 $this->fk_prev_id = 0;
6301 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6302 $this->situation_percent = 100;
6305 if (empty($this->pa_ht)) {
6308 if (empty($this->multicurrency_subprice)) {
6309 $this->multicurrency_subprice = 0;
6311 if (empty($this->multicurrency_total_ht)) {
6312 $this->multicurrency_total_ht = 0;
6314 if (empty($this->multicurrency_total_tva)) {
6315 $this->multicurrency_total_tva = 0;
6317 if (empty($this->multicurrency_total_ttc)) {
6318 $this->multicurrency_total_ttc = 0;
6322 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6323 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6327 $this->pa_ht = $result;
6332 if ($this->product_type < 0) {
6333 $this->error =
'ErrorProductTypeMustBe0orMore';
6336 if (!empty($this->fk_product) && $this->fk_product > 0) {
6340 $this->error =
'ErrorProductIdDoesNotExists';
6341 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6349 $sql =
'INSERT INTO '.MAIN_DB_PREFIX.
'facturedet';
6350 $sql .=
' (fk_facture, fk_parent_line, label, description, qty,';
6351 $sql .=
' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6352 $sql .=
' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6353 $sql .=
' date_start, date_end, fk_code_ventilation,';
6354 $sql .=
' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6355 $sql .=
' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6356 $sql .=
' situation_percent, fk_prev_id,';
6357 $sql .=
' fk_unit, fk_user_author, fk_user_modif,';
6358 $sql .=
' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc,';
6359 $sql .=
' batch, fk_warehouse';
6361 $sql .=
" VALUES (".$this->fk_facture.
",";
6362 $sql .=
" ".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null").
",";
6363 $sql .=
" ".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null").
",";
6364 $sql .=
" '".$this->db->escape($this->desc).
"',";
6365 $sql .=
" ".price2num($this->qty).
",";
6366 $sql .=
" ".(empty($this->vat_src_code) ?
"''" :
"'".$this->db->escape($this->vat_src_code).
"'").
",";
6367 $sql .=
" ".price2num($this->tva_tx).
",";
6368 $sql .=
" ".price2num($this->localtax1_tx).
",";
6369 $sql .=
" ".price2num($this->localtax2_tx).
",";
6370 $sql .=
" '".$this->db->escape($this->localtax1_type).
"',";
6371 $sql .=
" '".$this->db->escape($this->localtax2_type).
"',";
6372 $sql .=
' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product :
"null").
',';
6373 $sql .=
" ".((int) $this->product_type).
",";
6374 $sql .=
" ".price2num($this->remise_percent).
",";
6375 $sql .=
" ".price2num($this->subprice).
",";
6376 $sql .=
" '".$this->db->escape($this->ref_ext).
"',";
6377 $sql .=
' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except :
"null").
',';
6378 $sql .=
" ".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null").
",";
6379 $sql .=
" ".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null").
",";
6380 $sql .=
' '.((int) $this->fk_code_ventilation).
',';
6381 $sql .=
' '.((int) $this->rang).
',';
6382 $sql .=
' '.((int) $this->special_code).
',';
6383 $sql .=
' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice :
"null").
',';
6384 $sql .=
' '.price2num($this->pa_ht).
',';
6385 $sql .=
" '".$this->db->escape($this->info_bits).
"',";
6386 $sql .=
" ".price2num($this->total_ht).
",";
6387 $sql .=
" ".price2num($this->total_tva).
",";
6388 $sql .=
" ".price2num($this->total_ttc).
",";
6389 $sql .=
" ".price2num($this->total_localtax1).
",";
6390 $sql .=
" ".price2num($this->total_localtax2);
6391 $sql .=
", ".((float) $this->situation_percent);
6392 $sql .=
", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id :
"null");
6393 $sql .=
", ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6394 $sql .=
", ".((int) $user->id);
6395 $sql .=
", ".((int) $user->id);
6396 $sql .=
", ".(int) $this->fk_multicurrency;
6397 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
6398 $sql .=
", ".price2num($this->multicurrency_subprice);
6399 $sql .=
", ".price2num($this->multicurrency_total_ht);
6400 $sql .=
", ".price2num($this->multicurrency_total_tva);
6401 $sql .=
", ".price2num($this->multicurrency_total_ttc);
6402 $sql .=
", '".$this->db->escape($this->batch).
"'";
6403 $sql .=
", ".((int) $this->fk_warehouse);
6406 dol_syslog(get_class($this).
"::insert", LOG_DEBUG);
6407 $resql = $this->db->query($sql);
6409 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facturedet');
6410 $this->
rowid = $this->id;
6421 if ($this->fk_remise_except) {
6423 $result = $discount->fetch($this->fk_remise_except);
6428 if ($discount->fk_facture_line > 0) {
6429 if (empty($noerrorifdiscountalreadylinked)) {
6430 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed", $discount->id);
6431 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6432 $this->db->rollback();
6436 $result = $discount->link_to_invoice($this->
rowid, 0);
6438 $this->error = $discount->error;
6439 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6440 $this->db->rollback();
6445 $this->error = $langs->trans(
"ErrorADiscountThatHasBeenRemovedIsIncluded");
6446 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6447 $this->db->rollback();
6451 $this->error = $discount->error;
6452 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6453 $this->db->rollback();
6460 $result = $this->
call_trigger(
'LINEBILL_INSERT', $user);
6462 $this->db->rollback();
6468 $this->db->commit();
6471 $this->error = $this->db->lasterror();
6472 $this->db->rollback();
6484 public function update($user =
null, $notrigger = 0)
6486 global $user, $conf;
6490 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6493 $this->desc = trim($this->desc);
6494 if (empty($this->ref_ext)) {
6495 $this->ref_ext =
'';
6497 if (empty($this->tva_tx)) {
6500 if (empty($this->localtax1_tx)) {
6501 $this->localtax1_tx = 0;
6503 if (empty($this->localtax2_tx)) {
6504 $this->localtax2_tx = 0;
6506 if (empty($this->localtax1_type)) {
6507 $this->localtax1_type = 0;
6509 if (empty($this->localtax2_type)) {
6510 $this->localtax2_type = 0;
6512 if (empty($this->total_localtax1)) {
6513 $this->total_localtax1 = 0;
6515 if (empty($this->total_localtax2)) {
6516 $this->total_localtax2 = 0;
6518 if (empty($this->remise_percent)) {
6519 $this->remise_percent = 0;
6521 if (empty($this->info_bits)) {
6522 $this->info_bits = 0;
6524 if (empty($this->special_code)) {
6525 $this->special_code = 0;
6527 if (empty($this->product_type)) {
6528 $this->product_type = 0;
6530 if (empty($this->fk_parent_line)) {
6531 $this->fk_parent_line = 0;
6533 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6534 $this->situation_percent = 100;
6536 if (empty($this->pa_ht)) {
6540 if (empty($this->multicurrency_subprice)) {
6541 $this->multicurrency_subprice = 0;
6543 if (empty($this->multicurrency_total_ht)) {
6544 $this->multicurrency_total_ht = 0;
6546 if (empty($this->multicurrency_total_tva)) {
6547 $this->multicurrency_total_tva = 0;
6549 if (empty($this->multicurrency_total_ttc)) {
6550 $this->multicurrency_total_ttc = 0;
6554 if ($this->product_type < 0) {
6559 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6561 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6565 $this->pa_ht = $result;
6572 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6573 $sql .=
" description='".$this->db->escape($this->desc).
"'";
6574 $sql .=
", ref_ext='".$this->db->escape($this->ref_ext).
"'";
6575 $sql .=
", label=".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null");
6576 $sql .=
", subprice=".price2num($this->subprice);
6577 $sql .=
", remise_percent=".price2num($this->remise_percent);
6578 if ($this->fk_remise_except) {
6579 $sql .=
", fk_remise_except=".$this->fk_remise_except;
6581 $sql .=
", fk_remise_except=null";
6583 $sql .=
", vat_src_code = '".(empty($this->vat_src_code) ?
'' : $this->db->escape($this->vat_src_code)).
"'";
6584 $sql .=
", tva_tx=".price2num($this->tva_tx);
6585 $sql .=
", localtax1_tx=".price2num($this->localtax1_tx);
6586 $sql .=
", localtax2_tx=".price2num($this->localtax2_tx);
6587 $sql .=
", localtax1_type='".$this->db->escape($this->localtax1_type).
"'";
6588 $sql .=
", localtax2_type='".$this->db->escape($this->localtax2_type).
"'";
6589 $sql .=
", qty=".price2num($this->qty);
6590 $sql .=
", date_start=".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null");
6591 $sql .=
", date_end=".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null");
6592 $sql .=
", product_type=".$this->product_type;
6593 $sql .=
", info_bits='".$this->db->escape($this->info_bits).
"'";
6594 $sql .=
", special_code=" . (int) $this->special_code;
6595 if (empty($this->skip_update_total)) {
6596 $sql .=
", total_ht=".price2num($this->total_ht);
6597 $sql .=
", total_tva=".price2num($this->total_tva);
6598 $sql .=
", total_ttc=".price2num($this->total_ttc);
6599 $sql .=
", total_localtax1=".price2num($this->total_localtax1);
6600 $sql .=
", total_localtax2=".price2num($this->total_localtax2);
6602 $sql .=
", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ?
"'".$this->db->escape($this->fk_fournprice).
"'" :
"null");
6603 $sql .=
", buy_price_ht=".(($this->pa_ht || (string) $this->pa_ht ===
'0') ?
price2num($this->pa_ht) :
"null");
6604 $sql .=
", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null");
6605 if (!empty($this->rang)) {
6606 $sql .=
", rang=".((int) $this->rang);
6608 $sql .=
", situation_percent = ".((float) $this->situation_percent);
6609 $sql .=
", fk_unit = ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6610 $sql .=
", fk_user_modif = ".((int) $user->id);
6613 $sql .=
", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6614 $sql .=
", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6615 $sql .=
", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6616 $sql .=
", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6618 $sql .=
", batch = '".$this->db->escape($this->batch).
"'";
6619 $sql .=
", fk_warehouse = ".((int) $this->fk_warehouse);
6621 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6623 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
6624 $resql = $this->db->query($sql);
6627 $this->
id = $this->rowid;
6634 if (!$error && !$notrigger) {
6636 $result = $this->
call_trigger(
'LINEBILL_MODIFY', $user);
6638 $this->db->rollback();
6643 $this->db->commit();
6646 $this->error = $this->db->error();
6647 $this->db->rollback();
6659 public function delete($tmpuser =
null, $notrigger = 0)
6666 if (empty($notrigger)) {
6667 $result = $this->
call_trigger(
'LINEBILL_DELETE', $user);
6669 $this->db->rollback();
6678 $this->db->rollback();
6683 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
6684 $sql .=
' SET fk_facture_line = NULL';
6685 $sql .=
' WHERE fk_facture_line = '.((int) $this->
id);
6687 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
6688 $result = $this->db->query($sql);
6690 $this->error = $this->db->error();
6691 $this->errors[] = $this->error;
6692 $this->db->rollback();
6696 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
6697 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
6698 $sql .=
' WHERE invoice_line_id = '.((int) $this->
id);
6699 if (!$this->db->query($sql)) {
6700 $this->error = $this->db->error().
" sql=".$sql;
6701 $this->errors[] = $this->error;
6702 $this->db->rollback();
6706 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->
id);
6708 if ($this->db->query($sql)) {
6709 $this->db->commit();
6712 $this->error = $this->db->error().
" sql=".$sql;
6713 $this->errors[] = $this->error;
6714 $this->db->rollback();
6730 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6733 if (empty($this->total_localtax1)) {
6734 $this->total_localtax1 = 0;
6736 if (empty($this->total_localtax2)) {
6737 $this->total_localtax2 = 0;
6741 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6742 $sql .=
" total_ht=".price2num($this->total_ht);
6743 $sql .=
",total_tva=".price2num($this->total_tva);
6744 $sql .=
",total_localtax1=".price2num($this->total_localtax1);
6745 $sql .=
",total_localtax2=".price2num($this->total_localtax2);
6746 $sql .=
",total_ttc=".price2num($this->total_ttc);
6747 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6749 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6751 $resql = $this->db->query($sql);
6753 $this->db->commit();
6756 $this->error = $this->db->error();
6757 $this->db->rollback();
6775 global $invoicecache;
6777 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6781 if (!isset($invoicecache[$invoiceid])) {
6782 $invoicecache[$invoiceid] =
new Facture($this->db);
6783 $invoicecache[$invoiceid]->fetch($invoiceid);
6789 $sql =
"SELECT situation_percent FROM ".MAIN_DB_PREFIX.
"facturedet";
6790 $sql .=
" WHERE rowid = ".((int) $this->fk_prev_id);
6792 $resql = $this->db->query($sql);
6794 if ($resql && $this->db->num_rows($resql) > 0) {
6797 $obj = $this->db->fetch_object($resql);
6799 $returnPercent = (float) $obj->situation_percent;
6802 if ($include_credit_note) {
6803 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6804 $sql .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6805 $sql .=
" WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6806 $sql .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6807 $sql .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6809 $res = $this->db->query($sql);
6811 while ($obj = $this->db->fetch_object($res)) {
6812 $returnPercent = $returnPercent + (float) $obj->situation_percent;
6819 return $returnPercent;
6821 $this->error = $this->db->error();
6822 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6823 $this->db->rollback();
6842 global $invoicecache;
6844 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6848 if (!isset($invoicecache[$invoiceid])) {
6849 $invoicecache[$invoiceid] =
new Facture($this->db);
6850 $invoicecache[$invoiceid]->fetch($invoiceid);
6857 $lastprevid = $this->fk_prev_id;
6858 $cumulated_percent = 0.0;
6860 while (!$all_found) {
6861 $sql =
"SELECT situation_percent, fk_prev_id FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $lastprevid);
6862 $resql = $this->db->query($sql);
6864 if ($resql && $this->db->num_rows($resql) > 0) {
6865 $obj = $this->db->fetch_object($resql);
6866 $cumulated_percent += floatval($obj->situation_percent);
6868 if ($include_credit_note) {
6869 $sql_credit_note =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6870 $sql_credit_note .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6871 $sql_credit_note .=
" WHERE fd.fk_prev_id = ".((int) $lastprevid);
6872 $sql_credit_note .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6873 $sql_credit_note .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6875 $res_credit_note = $this->db->query($sql_credit_note);
6876 if ($res_credit_note) {
6877 while ($cn = $this->db->fetch_object($res_credit_note)) {
6878 $cumulated_percent = $cumulated_percent + floatval($cn->situation_percent);
6886 if ($obj->fk_prev_id) {
6887 $lastprevid = $obj->fk_prev_id;
6892 $this->error = $this->db->error();
6893 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6894 $this->db->rollback();
6898 return $cumulated_percent;
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Superclass for invoices classes.
getSommePaiement($multicurrency=0)
Return amount of payments already done.
calculate_date_lim_reglement($cond_reglement=0)
Returns an invoice payment deadline based on the invoice settlement conditions and billing date.
is_erasable()
Return if an invoice can be deleted Rule is: If invoice is draft and has a temporary ref -> yes (1) I...
Parent class of all other business classes for details of elements (invoices, contracts,...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteExtraFields()
Delete all extra fields values for the current object.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Class to manage absolute discounts.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class to manage shipments.
Class to manage invoices.
createFromClone(User $user, $fromid=0)
Load an object from its id and create a new one in database.
setDraft($user, $idwarehouse=-1)
Set draft status.
loadStateBoard()
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
$fk_facture_source
id of source invoice if replacement invoice or credit note
getIdShippingContact()
Retourne id des contacts clients de livraison.
setFinal(User $user, $notrigger=0)
Sets the invoice as a final situation.
setCanceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Replace a thirdparty id with another one.
list_replacable_invoices($socid=0)
Return list of invoices qualified to be replaced by another invoice.
insert_discount($idremise)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume...
createFromOrder($object, User $user)
Load an object from an order and create a new invoice into database.
willBeLastOfSameType($allow_validated_drafts=false)
See if current invoice date is posterior to the last invoice date among validated invoices of same ty...
update_percent($line, $percent, $update_price=true)
Update invoice line with percentage.
const TYPE_REPLACEMENT
Replacement invoice.
validate($user, $force_number='', $idwarehouse=0, $notrigger=0, $batch_rule=0)
Tag invoice as validated + call trigger BILL_VALIDATE Object must have lines loaded with fetch_lines.
update(User $user, $notrigger=0)
Update database.
fetch_lines($only_product=0, $loadalsotranslation=0)
Load all detailed lines into this->lines.
$fk_fac_rec_source
id of template invoice when generated from a template invoice
liste_array($shortlist=0, $draft=0, $excluser=null, $socid=0, $limit=0, $offset=0, $sortfield='f.datef, f.rowid', $sortorder='DESC')
Return list of invoices (eventually filtered on a user) into an array.
getIdBillingContact()
Retourne id des contacts clients de facturation.
__construct(DoliDB $db)
Constructor.
const STATUS_DRAFT
Draft status.
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=array(), $situation_percent=100, $fk_unit=null, $pu_ht_devise=0, $notrigger=0, $ref_ext='', $rang=0)
Update a detail line.
getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1, $target='')
Return clicable link of object (with eventually picto)
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
fetchPreviousNextSituationInvoice()
Fetch previous and next situations invoices.
fetch($rowid, $ref='', $ref_ext='', $notused=0, $fetch_situation=false)
Get object from database.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
$paye
1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code)
updatePriceNextInvoice(&$langs)
Update price of next invoice.
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Replace a product id with another one.
setRetainedWarrantyDateLimit($timestamp, $dateYmd='')
Change the retained_warranty_date_limit.
$pos_source
key of pos source ('0', '1', ...)
sendEmailsRemindersOnInvoiceDueDate($nbdays=0, $paymentmode='all', $template='', $datetouse='duedate', $forcerecipient='')
Send reminders by emails for invoices validated that are due.
info($id)
Load miscellaneous information for tab "Info".
const TYPE_PROFORMA
Proforma invoice (should not be used.
getKanbanView($option='', $arraydata=null)
Return clicable link of object (with eventually picto)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
setRetainedWarranty($value)
Change the retained warranty.
get_prev_sits()
Returns an array containing the previous situations as Facture objects.
list_qualified_avoir_invoices($socid=0)
Return list of invoices qualified to be corrected by a credit note.
set_canceled($user, $close_code='', $close_note='')
Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never rece...
newCycle()
Gets the smallest reference available for a new cycle.
setDiscount($user, $remise, $notrigger=0)
Set percent discount.
set_ref_client($ref_client, $notrigger=0)
Set customer ref.
is_first()
Checks if the invoice is the first of a cycle.
set_remise($user, $remise, $notrigger=0)
Set percent discount.
getTooltipContentArray($params)
getTooltipContentArray
getNextNumRef($soc, $mode='next')
Set absolute discount.
checkProgressLine($idline, $situation_percent)
Check if the percent edited is lower of next invoice line.
const STATUS_VALIDATED
Validated (need to be paid)
hasDelay()
Is the customer invoice delayed?
getLinesArray()
Create an array of invoice lines.
set_unpaid($user)
Tags the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a di...
const TYPE_DEPOSIT
Deposit invoice.
set_paid($user, $close_code='', $close_note='')
Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2,...
const STATUS_ABANDONED
Classified abandoned and no payment done.
createFromCurrent(User $user, $invertdetail=0)
Create a new invoice in database from current invoice.
setPaid($user, $close_code='', $close_note='')
Tag the invoice as :
displayRetainedWarranty()
Currently used for documents generation : to know if retained warranty need to be displayed.
const TYPE_CREDIT_NOTE
Credit note invoice.
is_last_in_cycle()
Checks if the invoice is the last in its cycle.
initAsSpecimen($option='')
Initialise an instance with random values.
deleteLine($rowid, $id=0)
Delete line in database.
getRetainedWarrantyAmount($rounding=-1)
create(User $user, $notrigger=0, $forceduedate=0)
Create invoice in database.
$module_source
key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos',...
addline( $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $fk_code_ventilation=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=array(), $situation_percent=100, $fk_prev_id=0, $fk_unit=null, $pu_ht_devise=0, $ref_ext='', $noupdateafterinsertline=0)
Add an invoice line into database (linked to product/service or not).
setUnpaid($user)
Tag the invoice as incompletely paid and call the trigger BILL_UNPAYED This method is used when a dir...
const STATUS_CLOSED
Classified paid.
createFromContract($object, User $user, $lines=array())
Load an object from an order and create a new invoice into database.
Class to manage invoice lines.
$fk_parent_line
Id parent line.
insert($notrigger=0, $noerrorifdiscountalreadylinked=0)
Insert line into database.
get_prev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of the previous line.
fetch($rowid)
Load invoice line from database.
update($user=null, $notrigger=0)
Update line into database.
$fk_facture
From llx_facturedet Id facture.
__construct($db)
Constructor.
update_total()
Update DB line fields total_xxx Used by migration.
get_allprev_progress($invoiceid, $include_credit_note=true)
Returns situation_percent of all the previous line.
Class to manage invoice templates.
Class to manage stock movements.
static getIdFromCode($dbs, $code)
Get id of currency from code.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
Manage record for batch number management.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
hasRight($module, $permlevel1, $permlevel2='')
Return if a user has a permission.
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
dol_get_next_month($month, $year)
Return next month.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e e e e e statut
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e rowid