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);
453 $this->ref_customer = trim($this->ref_customer);
455 $this->note_private = (isset($this->note_private) ? trim($this->note_private) :
'');
456 $this->note = (isset($this->note) ? trim($this->note) : $this->note_private);
457 $this->note_public = (isset($this->note_public) ? trim($this->note_public) :
'');
459 if (!$this->cond_reglement_id) {
460 $this->cond_reglement_id = 0;
462 if (!$this->mode_reglement_id) {
463 $this->mode_reglement_id = 0;
468 if (!empty($this->multicurrency_code)) {
470 if (empty($this->multicurrency_tx)) {
478 $this->fk_multicurrency = 0;
480 if (empty($this->fk_multicurrency)) {
481 $this->multicurrency_code = $conf->currency;
482 $this->fk_multicurrency = 0;
483 $this->multicurrency_tx = 1;
486 dol_syslog(get_class($this).
"::create user=".$user->id.
" date=".$this->date);
489 if (empty($this->date)) {
490 $this->error =
"Try to create an invoice with an empty parameter (date)";
491 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
495 $result = $soc->fetch($this->socid);
497 $this->error =
"Failed to fetch company: ".$soc->error;
498 dol_syslog(get_class($this).
"::create ".$this->error, LOG_ERR);
503 $this->date_creation = $now;
507 $originaldatewhen =
null;
508 $nextdatewhen =
null;
509 $previousdaynextdatewhen =
null;
512 if ($this->fac_rec > 0) {
513 $this->fk_fac_rec_source = $this->fac_rec;
516 $origin_user_author_id = ($this->fk_user_author > 0 ? $this->fk_user_author : $origin_user_author_id);
518 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
520 $result = $_facrec->fetch($this->fac_rec);
521 $result = $_facrec->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
524 $originaldatewhen = $_facrec->date_when;
525 $nextdatewhen =
null;
526 $previousdaynextdatewhen =
null;
527 if ($originaldatewhen) {
528 $nextdatewhen =
dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
532 if (!empty($_facrec->frequency)) {
533 $this->socid = $_facrec->socid;
535 $this->entity = $_facrec->entity;
540 $this->fk_project =
GETPOSTINT(
'projectid') > 0 ?
GETPOSTINT(
'projectid') : $_facrec->fk_project;
541 $this->note_public = GETPOSTISSET(
'note_public') ?
GETPOST(
'note_public',
'restricthtml') : $_facrec->note_public;
542 $this->note_private = GETPOSTISSET(
'note_private') ?
GETPOST(
'note_private',
'restricthtml') : $_facrec->note_private;
543 $this->model_pdf = GETPOSTISSET(
'model') ?
GETPOST(
'model',
'alpha') : $_facrec->model_pdf;
544 $this->cond_reglement_id =
GETPOSTINT(
'cond_reglement_id') > 0 ?
GETPOSTINT(
'cond_reglement_id') : $_facrec->cond_reglement_id;
545 $this->mode_reglement_id =
GETPOSTINT(
'mode_reglement_id') > 0 ?
GETPOSTINT(
'mode_reglement_id') : $_facrec->mode_reglement_id;
546 $this->fk_account =
GETPOST(
'fk_account') > 0 ?
GETPOSTINT(
'fk_account') : $_facrec->fk_account;
549 $this->total_ht = $_facrec->total_ht;
550 $this->total_ttc = $_facrec->total_ttc;
555 $this->fk_incoterms = $_facrec->fk_incoterms;
556 $this->location_incoterms = $_facrec->location_incoterms;
562 $this->ref_client = trim($this->ref_client);
563 $this->ref_customer = trim($this->ref_customer);
564 $this->note_public = trim($this->note_public);
565 $this->note_private = trim($this->note_private);
566 $this->note_private =
dol_concatdesc($this->note_private, $langs->trans(
"GeneratedFromRecurringInvoice", $_facrec->ref));
568 $this->array_options = $_facrec->array_options;
570 if (!$this->mode_reglement_id) {
571 $this->mode_reglement_id = 0;
576 $this->linked_objects = $_facrec->linkedObjectsIds;
581 if ($_facrec->frequency > 0) {
582 dol_syslog(
"This is a recurring invoice so we set date_last_gen and next date_when");
583 if (empty($_facrec->date_when)) {
584 $_facrec->date_when = $now;
586 $next_date = $_facrec->getNextDate();
587 $result = $_facrec->setValueFrom(
'date_last_gen', $now,
'',
null,
'date',
'', $user,
'');
589 $result = $_facrec->setNextDate($next_date, 1);
593 $outputlangs = $langs;
596 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->thirdparty->default_lang)) {
597 $newlang = $this->thirdparty->default_lang;
599 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && empty($newlang) && isset($this->default_lang)) {
600 $newlang = $this->default_lang;
602 if (!empty($newlang)) {
604 $outputlangs->setDefaultLang($newlang);
610 $substitutionarray[
'__INVOICE_MONTH__'] =
dol_print_date($this->date,
'%m');
613 $substitutionarray[
'__INVOICE_MONTH_TEXT__'] =
dol_print_date($this->date,
'%B');
616 $substitutionarray[
'__INVOICE_YEAR__'] =
dol_print_date($this->date,
'%Y');
619 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = (isset($originaldatewhen) ?
dol_print_date($originaldatewhen,
'dayhour') :
'');
620 $substitutionarray[
'__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($nextdatewhen) ?
dol_print_date($nextdatewhen,
'dayhour') :
'');
621 $substitutionarray[
'__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = (isset($previousdaynextdatewhen) ?
dol_print_date($previousdaynextdatewhen,
'dayhour') :
'');
622 $substitutionarray[
'__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
623 $substitutionarray[
'__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
634 if (empty($forceduedate)) {
640 $this->date_lim_reglement = $duedate;
642 $this->date_lim_reglement = $forceduedate;
646 $socid = $this->socid;
648 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.
"facture (";
657 $sql .=
", date_pointoftax";
658 $sql .=
", note_private";
659 $sql .=
", note_public";
660 $sql .=
", ref_client";
661 $sql .=
", fk_account";
662 $sql .=
", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
663 $sql .=
", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
664 $sql .=
", situation_cycle_ref, situation_counter, situation_final";
665 $sql .=
", fk_incoterms, location_incoterms";
666 $sql .=
", fk_multicurrency";
667 $sql .=
", multicurrency_code";
668 $sql .=
", multicurrency_tx";
669 $sql .=
", retained_warranty";
670 $sql .=
", retained_warranty_date_limit";
671 $sql .=
", retained_warranty_fk_cond_reglement";
675 $sql .=
", ".setEntity($this);
676 $sql .=
", ".($this->ref_ext ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null");
677 $sql .=
", '".$this->db->escape($this->
type).
"'";
678 $sql .=
", ".($this->subtype ?
"'".$this->db->escape($this->subtype).
"'" :
"null");
679 $sql .=
", ".((int) $socid);
680 $sql .=
", '".$this->db->idate($this->date_creation).
"'";
681 $sql .=
", '".$this->db->idate($this->date).
"'";
682 $sql .=
", ".(empty($this->date_pointoftax) ?
"null" :
"'".$this->db->idate($this->date_pointoftax).
"'");
683 $sql .=
", ".($this->note_private ?
"'".$this->db->escape($this->note_private).
"'" :
"null");
684 $sql .=
", ".($this->note_public ?
"'".$this->db->escape($this->note_public).
"'" :
"null");
685 $sql .=
", ".($this->ref_customer ?
"'".$this->db->escape($this->ref_customer).
"'" : ($this->ref_client ?
"'".$this->db->escape($this->ref_client).
"'" :
"null"));
686 $sql .=
", ".($this->fk_account > 0 ? $this->fk_account :
'NULL');
687 $sql .=
", ".($this->module_source ?
"'".$this->db->escape($this->module_source).
"'" :
"null");
688 $sql .=
", ".($this->pos_source !=
'' ?
"'".$this->db->escape($this->pos_source).
"'" :
"null");
689 $sql .=
", ".($this->fk_fac_rec_source ?
"'".$this->db->escape($this->fk_fac_rec_source).
"'" :
"null");
690 $sql .=
", ".($this->fk_facture_source ?
"'".$this->db->escape($this->fk_facture_source).
"'" :
"null");
691 $sql .=
", ".($origin_user_author_id > 0 ? (int) $origin_user_author_id :
"null");
692 $sql .=
", ".($this->fk_project ? (int) $this->fk_project :
"null");
693 $sql .=
", ".((int) $this->cond_reglement_id);
694 $sql .=
", ".((int) $this->mode_reglement_id);
695 $sql .=
", '".$this->db->idate($this->date_lim_reglement).
"'";
696 $sql .=
", ".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null");
697 $sql .=
", ".($this->situation_cycle_ref ?
"'".$this->db->escape($this->situation_cycle_ref).
"'" :
"null");
698 $sql .=
", ".($this->situation_counter ?
"'".$this->db->escape($this->situation_counter).
"'" :
"null");
699 $sql .=
", ".($this->situation_final ? (int) $this->situation_final : 0);
700 $sql .=
", ".(int) $this->fk_incoterms;
701 $sql .=
", '".$this->db->escape($this->location_incoterms).
"'";
702 $sql .=
", ".(int) $this->fk_multicurrency;
703 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
704 $sql .=
", ".(float) $this->multicurrency_tx;
705 $sql .=
", ".(empty($this->retained_warranty) ?
"0" : $this->db->escape($this->retained_warranty));
706 $sql .=
", ".(!empty($this->retained_warranty_date_limit) ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'NULL');
707 $sql .=
", ".(int) $this->retained_warranty_fk_cond_reglement;
710 $resql = $this->db->query($sql);
712 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facture');
715 $this->
ref =
'(PROV'.$this->id.
')';
716 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"facture SET ref='".$this->db->escape($this->
ref).
"' WHERE rowid=".((int) $this->
id);
718 $resql = $this->db->query($sql);
723 if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
724 $this->linked_objects = $this->linkedObjectsIds;
728 if (!$error && $this->
id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
729 foreach ($this->linked_objects as $origin => $tmp_origin_id) {
730 if (is_array($tmp_origin_id)) {
731 foreach ($tmp_origin_id as $origin_id) {
734 $this->error = $this->db->lasterror();
739 $origin_id = $tmp_origin_id;
742 $this->error = $this->db->lasterror();
750 if (!$error && $this->
id &&
getDolGlobalString(
'MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) {
751 $originforcontact = $this->origin;
752 $originidforcontact = $this->origin_id;
753 if ($originforcontact ==
'shipping') {
754 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
756 $exp->fetch($this->origin_id);
757 $exp->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
758 if (count($exp->linkedObjectsIds[
'commande']) > 0) {
759 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
760 $originforcontact =
'commande';
761 if (is_object($value)) {
762 $originidforcontact = $value->id;
764 $originidforcontact = $value;
771 $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";
772 $sqlcontact .=
" WHERE element_id = ".((int) $originidforcontact).
" AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact).
"'";
774 $resqlcontact = $this->db->query($sqlcontact);
776 while ($objcontact = $this->db->fetch_object($resqlcontact)) {
778 $this->
add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source);
788 if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) {
791 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines that are InvoiceLines");
792 foreach ($this->lines as $i => $val) {
793 $newinvoiceline = $this->lines[$i];
795 $newinvoiceline->context = $this->context;
797 $newinvoiceline->fk_facture = $this->id;
799 $newinvoiceline->origin = $this->lines[$i]->element;
800 $newinvoiceline->origin_id = $this->lines[$i]->id;
803 if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) {
804 $newinvoiceline->date_start = $originaldatewhen;
806 if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) {
807 $newinvoiceline->date_end = $previousdaynextdatewhen;
812 if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
817 $vatrate = $newinvoiceline->tva_tx;
818 if ($newinvoiceline->vat_src_code && ! preg_match(
'/\(.*\)/', (
string) $vatrate)) {
819 $vatrate .=
' ('.$newinvoiceline->vat_src_code.
')';
822 $newinvoiceline->fk_parent_line = $fk_parent_line;
826 $discount->fetch($newinvoiceline->fk_remise_except);
828 $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
829 $newinvoiceline->fk_remise_except = $discountId;
833 $newinvoiceline->desc,
834 $newinvoiceline->subprice,
835 $newinvoiceline->qty,
837 $newinvoiceline->localtax1_tx,
838 $newinvoiceline->localtax2_tx,
839 $newinvoiceline->fk_product,
840 $newinvoiceline->remise_percent,
841 $newinvoiceline->date_start,
842 $newinvoiceline->date_end,
843 $newinvoiceline->fk_code_ventilation,
844 $newinvoiceline->info_bits,
845 $newinvoiceline->fk_remise_except,
848 $newinvoiceline->product_type,
849 $newinvoiceline->rang,
850 $newinvoiceline->special_code,
851 $newinvoiceline->element,
854 $newinvoiceline->fk_fournprice,
855 $newinvoiceline->pa_ht,
856 $newinvoiceline->label,
857 $newinvoiceline->array_options,
858 $newinvoiceline->situation_percent,
859 $newinvoiceline->fk_prev_id,
860 $newinvoiceline->fk_unit,
861 $newinvoiceline->multicurrency_subprice,
862 $newinvoiceline->ref_ext,
867 $this->error = $newinvoiceline->error;
868 $this->errors = array_merge($this->errors, $newinvoiceline->errors);
874 if ($result > 0 && $newinvoiceline->product_type == 9) {
875 $fk_parent_line = $result;
879 } elseif (!$error && empty($this->fac_rec)) {
882 dol_syslog(
"There is ".count($this->lines).
" lines into ->lines as a simple array");
884 foreach ($this->lines as $i => $val) {
885 $line = $this->lines[$i];
889 if (!is_object($line)) {
890 $line = (object) $line;
895 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
900 $vatrate = $line->tva_tx;
901 if ($line->vat_src_code && !preg_match(
'/\(.*\)/', (
string) $vatrate)) {
902 $vatrate .=
' ('.$line->vat_src_code.
')';
906 $originid = $line->origin_id;
907 $origintype = $line->origin;
909 $originid = $line->id;
910 $origintype = $this->element;
914 if (empty($line->ref_ext)) {
926 $line->remise_percent,
929 $line->fk_code_ventilation,
931 $line->fk_remise_except,
940 $line->fk_fournprice,
943 $line->array_options,
944 $line->situation_percent,
947 $line->multicurrency_subprice,
952 $this->error = $this->db->lasterror();
954 $this->db->rollback();
959 if ($result > 0 && $line->product_type == 9) {
960 $fk_parent_line = $result;
969 if (!$error && $this->fac_rec > 0) {
970 dol_syslog(
"There is ".count($_facrec->lines).
" lines from recurring invoice");
973 foreach ($_facrec->lines as $i => $val) {
974 if ($_facrec->lines[$i]->fk_product) {
975 $prod =
new Product($this->db);
976 $res = $prod->fetch($_facrec->lines[$i]->fk_product);
980 if (($_facrec->lines[$i]->product_type != 9 && empty($_facrec->lines[$i]->fk_parent_line)) || $_facrec->lines[$i]->product_type == 9) {
992 $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ?
'('.$_facrec->lines[$i]->vat_src_code.
')' :
'');
993 $tva_npr = $_facrec->lines[$i]->info_bits;
994 if (empty($tva_tx)) {
997 $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
998 $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
1000 $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
1001 $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
1004 if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
1005 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1007 $producttmp->fetch($_facrec->lines[$i]->fk_product);
1012 if (
getDolGlobalString(
'MARGIN_TYPE') ==
'costprice' && !empty($producttmp->cost_price)) {
1013 $buyprice = $producttmp->cost_price;
1015 $buyprice = $producttmp->pmp;
1017 if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
1018 if ($producttmp->product_fourn_price_id > 0) {
1019 $buyprice =
price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise,
'MU');
1025 $result_insert = $this->
addline(
1026 $_facrec->lines[$i]->desc,
1027 $_facrec->lines[$i]->subprice,
1028 $_facrec->lines[$i]->qty,
1032 $_facrec->lines[$i]->fk_product,
1033 $_facrec->lines[$i]->remise_percent,
1034 ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen :
'',
1035 ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen :
'',
1041 $_facrec->lines[$i]->product_type,
1042 $_facrec->lines[$i]->rang,
1043 $_facrec->lines[$i]->special_code,
1047 $fk_product_fournisseur_price,
1049 $_facrec->lines[$i]->label,
1050 empty($_facrec->lines[$i]->array_options) ? null : $_facrec->lines[$i]->array_options,
1053 $_facrec->lines[$i]->fk_unit,
1054 $_facrec->lines[$i]->multicurrency_subprice,
1055 $_facrec->lines[$i]->ref_ext,
1060 if ($result_insert > 0 && $_facrec->lines[$i]->product_type == 9) {
1061 $fk_parent_line = $result_insert;
1064 if ($result_insert < 0) {
1066 $this->error = $this->db->error();
1085 if (!$error && !$notrigger) {
1094 $this->db->commit();
1097 $this->db->rollback();
1101 $this->error = $langs->trans(
'FailedToUpdatePrice');
1102 $this->db->rollback();
1106 dol_syslog(get_class($this).
"::create error ".$this->error, LOG_ERR);
1107 $this->db->rollback();
1111 $this->error = $this->db->error();
1112 $this->db->rollback();
1128 $facture =
new Facture($this->db);
1134 if (!empty($this->array_options)) {
1135 $facture->array_options = $this->array_options;
1138 foreach ($this->lines as &$line) {
1139 $line->fetch_optionals();
1143 $facture->type = $this->type;
1144 $facture->subtype = $this->subtype;
1145 $facture->socid = $this->socid;
1146 $facture->date = $this->date;
1147 $facture->date_pointoftax = $this->date_pointoftax;
1148 $facture->note_public = $this->note_public;
1149 $facture->note_private = $this->note_private;
1150 $facture->ref_client = $this->ref_client;
1151 $facture->ref_customer = $this->ref_customer;
1152 $facture->model_pdf = $this->model_pdf;
1153 $facture->fk_project = $this->fk_project;
1154 $facture->cond_reglement_id = $this->cond_reglement_id;
1155 $facture->mode_reglement_id = $this->mode_reglement_id;
1159 $facture->origin = $this->origin;
1160 $facture->origin_id = $this->origin_id;
1161 $facture->fk_account = $this->fk_account;
1163 $facture->lines = $this->lines;
1164 $facture->situation_counter = $this->situation_counter;
1165 $facture->situation_cycle_ref = $this->situation_cycle_ref;
1166 $facture->situation_final = $this->situation_final;
1168 $facture->retained_warranty = $this->retained_warranty;
1169 $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
1170 $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
1172 $facture->fk_user_author = $user->id;
1173 $facture->user_creation_id = $user->id;
1177 foreach ($facture->lines as $i => $tmpline) {
1178 $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
1179 if ($invertdetail) {
1180 $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
1181 $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
1182 $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
1183 $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
1184 $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
1185 $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
1186 $facture->lines[$i]->ref_ext =
'';
1190 dol_syslog(get_class($this).
"::createFromCurrent invertdetail=".$invertdetail.
" socid=".$this->socid.
" nboflines=".count($facture->lines));
1192 $facid = $facture->create($user);
1194 $this->error = $facture->error;
1195 $this->errors = $facture->errors;
1199 foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
1200 foreach ($Tfk_object as $fk_object) {
1201 $facture->add_object_linked($typeObject, $fk_object);
1205 $facture->add_object_linked(
'facture', $this->fk_facture_source);
1221 global $conf, $hookmanager;
1235 if (!empty($this->socid) && $this->socid !=
$object->socid) {
1236 $objsoc =
new Societe($this->db);
1238 if ($objsoc->fetch($this->socid) > 0) {
1240 $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
1241 $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
1243 $object->fk_delivery_address = 0;
1255 $object->user_creation_id = $user->id;
1256 $object->user_validation_id =
null;
1257 $object->fk_user_author = $user->id;
1258 $object->fk_user_valid =
null;
1259 $object->fk_facture_source = 0;
1261 $object->date_modification =
'';
1262 $object->date_validation =
'';
1272 foreach (
$object->lines as $i => $line) {
1273 if ((
$object->lines[$i]->info_bits & 0x02) == 0x02) {
1280 if (
getDolGlobalString(
'INVOICE_AUTO_NEXT_MONTH_ON_LINES') && !empty($line->date_start) && !empty($line->date_end)) {
1292 if (
dol_mktime(0, 0, 0, $start[
'mon'], $start[
'mday'], $start[
'year'],
'gmt') == $first
1293 &&
dol_mktime(23, 59, 59, $end[
'mon'], $end[
'mday'], $end[
'year'],
'gmt') == $last) {
1297 $object->lines[$i]->date_start = $newFirst;
1298 $object->lines[$i]->date_end = $newLast;
1302 $object->lines[$i]->ref_ext =
'';
1306 $object->context[
'createfromclone'] =
'createfromclone';
1307 $result =
$object->create($user);
1310 $this->error =
$object->error;
1311 $this->errors =
$object->errors;
1314 if (
$object->copy_linked_contact($objFrom,
'internal') < 0) {
1316 $this->error =
$object->error;
1317 $this->errors =
$object->errors;
1318 } elseif (
$object->socid == $objFrom->socid) {
1320 if (
$object->copy_linked_contact($objFrom,
'external') < 0) {
1322 $this->error =
$object->error;
1323 $this->errors =
$object->errors;
1330 if (is_object($hookmanager)) {
1331 $parameters = array(
'objFrom' => $objFrom);
1333 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters,
$object, $action);
1341 unset(
$object->context[
'createfromclone']);
1345 $this->db->commit();
1348 $this->db->rollback();
1362 global $conf, $hookmanager;
1371 for ($i = 0; $i < $num; $i++) {
1374 $line->libelle =
$object->lines[$i]->libelle;
1375 $line->label =
$object->lines[$i]->label;
1376 $line->desc =
$object->lines[$i]->desc;
1377 $line->subprice =
$object->lines[$i]->subprice;
1378 $line->total_ht =
$object->lines[$i]->total_ht;
1379 $line->total_tva =
$object->lines[$i]->total_tva;
1380 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1381 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1382 $line->total_ttc =
$object->lines[$i]->total_ttc;
1383 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1384 $line->tva_tx =
$object->lines[$i]->tva_tx;
1385 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1386 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1387 $line->qty =
$object->lines[$i]->qty;
1388 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1389 $line->remise_percent =
$object->lines[$i]->remise_percent;
1390 $line->fk_product =
$object->lines[$i]->fk_product;
1391 $line->info_bits =
$object->lines[$i]->info_bits;
1392 $line->product_type =
$object->lines[$i]->product_type;
1393 $line->rang =
$object->lines[$i]->rang;
1394 $line->special_code =
$object->lines[$i]->special_code;
1395 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1396 $line->fk_unit =
$object->lines[$i]->fk_unit;
1397 $line->date_start =
$object->lines[$i]->date_start;
1398 $line->date_end =
$object->lines[$i]->date_end;
1401 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1402 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1403 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1404 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1405 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1406 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1408 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1410 $line->pa_ht = $marginInfos[0];
1413 $object->lines[$i]->fetch_optionals();
1414 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1415 $line->array_options[$options_key] = $value;
1418 $this->lines[$i] = $line;
1421 $this->socid =
$object->socid;
1422 $this->fk_project =
$object->fk_project;
1423 $this->fk_account =
$object->fk_account;
1424 $this->cond_reglement_id =
$object->cond_reglement_id;
1425 $this->mode_reglement_id =
$object->mode_reglement_id;
1426 $this->availability_id =
$object->availability_id;
1427 $this->demand_reason_id =
$object->demand_reason_id;
1428 $this->delivery_date =
$object->delivery_date;
1429 $this->fk_delivery_address =
$object->fk_delivery_address;
1430 $this->contact_id =
$object->contact_id;
1431 $this->ref_client =
$object->ref_client;
1434 $this->note_private =
$object->note_private;
1435 $this->note_public =
$object->note_public;
1438 $this->module_source =
$object->module_source;
1439 $this->pos_source =
$object->pos_source;
1441 $this->origin =
$object->element;
1442 $this->origin_id =
$object->id;
1444 $this->fk_user_author = $user->id;
1448 foreach (
$object->array_options as $options_key => $value) {
1449 $this->array_options[$options_key] = $value;
1453 $this->linked_objects[$this->origin] = $this->origin_id;
1454 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1455 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1458 $ret = $this->
create($user);
1462 $hookmanager->initHooks(array(
'invoicedao'));
1464 $parameters = array(
'objFrom' =>
$object);
1466 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1492 global $conf, $hookmanager;
1500 $use_all_lines = empty($lines);
1502 for ($i = 0; $i < $num; $i++) {
1503 if (!$use_all_lines && !in_array(
$object->lines[$i]->id, $lines)) {
1509 $line->libelle =
$object->lines[$i]->libelle;
1510 $line->label =
$object->lines[$i]->label;
1511 $line->desc =
$object->lines[$i]->desc;
1512 $line->subprice =
$object->lines[$i]->subprice;
1513 $line->total_ht =
$object->lines[$i]->total_ht;
1514 $line->total_tva =
$object->lines[$i]->total_tva;
1515 $line->total_localtax1 =
$object->lines[$i]->total_localtax1;
1516 $line->total_localtax2 =
$object->lines[$i]->total_localtax2;
1517 $line->total_ttc =
$object->lines[$i]->total_ttc;
1518 $line->vat_src_code =
$object->lines[$i]->vat_src_code;
1519 $line->tva_tx =
$object->lines[$i]->tva_tx;
1520 $line->localtax1_tx =
$object->lines[$i]->localtax1_tx;
1521 $line->localtax2_tx =
$object->lines[$i]->localtax2_tx;
1522 $line->qty =
$object->lines[$i]->qty;
1523 $line->fk_remise_except =
$object->lines[$i]->fk_remise_except;
1524 $line->remise_percent =
$object->lines[$i]->remise_percent;
1525 $line->fk_product =
$object->lines[$i]->fk_product;
1526 $line->info_bits =
$object->lines[$i]->info_bits;
1527 $line->product_type =
$object->lines[$i]->product_type;
1528 $line->rang =
$object->lines[$i]->rang;
1529 $line->special_code =
$object->lines[$i]->special_code;
1530 $line->fk_parent_line =
$object->lines[$i]->fk_parent_line;
1531 $line->fk_unit =
$object->lines[$i]->fk_unit;
1532 $line->date_start =
$object->lines[$i]->date_start;
1533 $line->date_end =
$object->lines[$i]->date_end;
1536 $line->fk_multicurrency =
$object->lines[$i]->fk_multicurrency;
1537 $line->multicurrency_code =
$object->lines[$i]->multicurrency_code;
1538 $line->multicurrency_subprice =
$object->lines[$i]->multicurrency_subprice;
1539 $line->multicurrency_total_ht =
$object->lines[$i]->multicurrency_total_ht;
1540 $line->multicurrency_total_tva =
$object->lines[$i]->multicurrency_total_tva;
1541 $line->multicurrency_total_ttc =
$object->lines[$i]->multicurrency_total_ttc;
1543 $line->fk_fournprice =
$object->lines[$i]->fk_fournprice;
1545 $line->pa_ht = $marginInfos[0];
1548 $object->lines[$i]->fetch_optionals();
1549 foreach (
$object->lines[$i]->array_options as $options_key => $value) {
1550 $line->array_options[$options_key] = $value;
1553 $this->lines[$i] = $line;
1556 $this->socid =
$object->socid;
1557 $this->fk_project =
$object->fk_project;
1558 $this->fk_account =
$object->fk_account;
1559 $this->cond_reglement_id =
$object->cond_reglement_id;
1560 $this->mode_reglement_id =
$object->mode_reglement_id;
1561 $this->availability_id =
$object->availability_id;
1562 $this->demand_reason_id =
$object->demand_reason_id;
1563 $this->delivery_date =
$object->delivery_date;
1564 $this->fk_delivery_address =
$object->fk_delivery_address;
1565 $this->contact_id =
$object->contact_id;
1566 $this->ref_client =
$object->ref_client;
1569 $this->note_private =
$object->note_private;
1570 $this->note_public =
$object->note_public;
1573 $this->module_source =
$object->module_source;
1574 $this->pos_source =
$object->pos_source;
1576 $this->origin =
$object->element;
1577 $this->origin_id =
$object->id;
1579 $this->fk_user_author = $user->id;
1583 foreach (
$object->array_options as $options_key => $value) {
1584 $this->array_options[$options_key] = $value;
1588 $this->linked_objects[$this->origin] = $this->origin_id;
1589 if (!empty(
$object->other_linked_objects) && is_array(
$object->other_linked_objects)) {
1590 $this->linked_objects = array_merge($this->linked_objects,
$object->other_linked_objects);
1593 $ret = $this->
create($user);
1597 $hookmanager->initHooks(array(
'invoicedao'));
1599 $parameters = array(
'objFrom' =>
$object);
1601 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $this, $action);
1631 global $conf, $langs, $hookmanager, $action;
1633 if (! in_array($origin->element, array(
'propal',
'commande'))) {
1634 $origin->error =
'ErrorCanOnlyAutomaticallyGenerateADepositFromProposalOrOrder';
1639 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DateInvoice'));
1643 require_once DOL_DOCUMENT_ROOT .
'/core/lib/date.lib.php';
1646 $origin->error =
'ErrorDateIsInFuture';
1650 if ($payment_terms_id <= 0) {
1651 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'PaymentConditionsShort'));
1655 $payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $origin->cond_reglement_id);
1657 if (empty($payment_conditions_deposit_percent)) {
1658 $origin->error =
'ErrorPaymentConditionsNotEligibleToDepositCreation';
1662 if (empty($origin->deposit_percent)) {
1663 $origin->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentities(
'DepositPercent'));
1667 $deposit =
new self($origin->db);
1668 $deposit->socid = $origin->socid;
1670 $deposit->fk_project = $origin->fk_project;
1671 $deposit->ref_client = $origin->ref_client;
1672 $deposit->date = $date;
1673 $deposit->mode_reglement_id = $origin->mode_reglement_id;
1674 $deposit->cond_reglement_id = $payment_terms_id;
1675 $deposit->availability_id = $origin->availability_id;
1676 $deposit->demand_reason_id = $origin->demand_reason_id;
1677 $deposit->fk_account = $origin->fk_account;
1678 $deposit->fk_incoterms = $origin->fk_incoterms;
1679 $deposit->location_incoterms = $origin->location_incoterms;
1680 $deposit->fk_multicurrency = $origin->fk_multicurrency;
1681 $deposit->multicurrency_code = $origin->multicurrency_code;
1682 $deposit->multicurrency_tx = $origin->multicurrency_tx;
1683 $deposit->module_source = $origin->module_source;
1684 $deposit->pos_source = $origin->pos_source;
1685 $deposit->model_pdf =
'crabe';
1687 $modelByTypeConfName =
'FACTURE_ADDON_PDF_' . $deposit->type;
1696 $deposit->note_private = $origin->note_private;
1697 $deposit->note_public = $origin->note_public;
1700 $deposit->origin = $origin->element;
1701 $deposit->origin_id = $origin->id;
1703 $origin->fetch_optionals();
1705 foreach ($origin->array_options as $extrakey => $value) {
1706 $deposit->array_options[$extrakey] = $value;
1709 $deposit->linked_objects[$deposit->origin] = $deposit->origin_id;
1711 foreach ($overrideFields as $key => $value) {
1712 $deposit->$key = $value;
1715 $deposit->context[
'createdepositfromorigin'] =
'createdepositfromorigin';
1717 $origin->db->begin();
1720 $createReturn = $deposit->create($user, $notrigger);
1722 if ($createReturn <= 0) {
1723 $origin->db->rollback();
1724 $origin->error = $deposit->error;
1725 $origin->errors = $deposit->errors;
1729 $amount_ttc_diff = 0;
1730 $amountdeposit = array();
1731 $descriptions = array();
1734 $amount = $origin->total_ttc * ($origin->deposit_percent / 100);
1736 $TTotalByTva = array();
1737 foreach ($origin->lines as &$line) {
1738 if (!empty($line->special_code)) {
1741 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1742 $descriptions[$line->tva_tx] .=
'<li>' . (!empty($line->product_ref) ? $line->product_ref .
' - ' :
'');
1743 $descriptions[$line->tva_tx] .= (!empty($line->product_label) ? $line->product_label .
' - ' :
'');
1744 $descriptions[$line->tva_tx] .= $langs->trans(
'Qty') .
' : ' . $line->qty;
1745 $descriptions[$line->tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($line->total_ht) .
'</li>';
1748 foreach ($TTotalByTva as $tva => &$total) {
1749 $coef = $total / $origin->total_ttc;
1750 $am = $amount * $coef;
1751 $amount_ttc_diff += $am;
1752 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1756 $lines = $origin->lines;
1757 $numlines = count($lines);
1758 for ($i = 0; $i < $numlines; $i++) {
1759 if (empty($lines[$i]->qty)) {
1762 if (!empty($lines[$i]->special_code)) {
1766 $totalamount += $lines[$i]->total_ht;
1767 $tva_tx = $lines[$i]->tva_tx;
1768 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $origin->deposit_percent) / 100;
1769 $descriptions[$tva_tx] .=
'<li>' . (!empty($lines[$i]->product_ref) ? $lines[$i]->product_ref .
' - ' :
'');
1770 $descriptions[$tva_tx] .= (!empty($lines[$i]->product_label) ? $lines[$i]->product_label .
' - ' :
'');
1771 $descriptions[$tva_tx] .= $langs->trans(
'Qty') .
' : ' . $lines[$i]->qty;
1772 $descriptions[$tva_tx] .=
' - ' . $langs->trans(
'TotalHT') .
' : ' .
price($lines[$i]->total_ht) .
'</li>';
1775 if ($totalamount == 0) {
1776 $amountdeposit[0] = 0;
1779 $amount_ttc_diff = $amountdeposit[0];
1782 foreach ($amountdeposit as $tva => $amount) {
1783 if (empty($amount)) {
1787 $descline =
'(DEPOSIT) ('. $origin->deposit_percent .
'%) - '.$origin->ref;
1790 if (
getDolGlobalString(
'INVOICE_DEPOSIT_VARIABLE_MODE_DETAIL_LINES_IN_DESCRIPTION') && !empty($descriptions[$tva])) {
1791 $descline .=
'<ul>' . $descriptions[$tva] .
'</ul>';
1794 $addlineResult = $deposit->addline(
1801 (!
getDolGlobalString(
'INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1821 if ($addlineResult < 0) {
1822 $origin->db->rollback();
1823 $origin->error = $deposit->error;
1824 $origin->errors = $deposit->errors;
1829 $diff = $deposit->total_ttc - $amount_ttc_diff;
1832 $deposit->fetch_lines();
1833 $subprice_diff = $deposit->lines[0]->subprice - $diff / (1 + $deposit->lines[0]->tva_tx / 100);
1835 $updatelineResult = $deposit->updateline(
1836 $deposit->lines[0]->id,
1837 $deposit->lines[0]->desc,
1839 $deposit->lines[0]->qty,
1840 $deposit->lines[0]->remise_percent,
1841 $deposit->lines[0]->date_start,
1842 $deposit->lines[0]->date_end,
1843 $deposit->lines[0]->tva_tx,
1847 $deposit->lines[0]->info_bits,
1848 $deposit->lines[0]->product_type,
1852 $deposit->lines[0]->pa_ht,
1853 $deposit->lines[0]->label,
1859 if ($updatelineResult < 0) {
1860 $origin->db->rollback();
1861 $origin->error = $deposit->error;
1862 $origin->errors = $deposit->errors;
1867 $hookmanager->initHooks(array(
'invoicedao'));
1869 $parameters = array(
'objFrom' => $origin);
1870 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $deposit, $action);
1873 $origin->db->rollback();
1874 $origin->error = $hookmanager->error;
1875 $origin->errors = $hookmanager->errors;
1879 if (!empty($autoValidateDeposit)) {
1880 $validateReturn = $deposit->validate($user,
'', 0, $notrigger);
1882 if ($validateReturn < 0) {
1883 $origin->db->rollback();
1884 $origin->error = $deposit->error;
1885 $origin->errors = $deposit->errors;
1890 unset($deposit->context[
'createdepositfromorigin']);
1892 $origin->db->commit();
1906 global $conf, $langs, $mysoc, $user;
1908 $langs->load(
'bills');
1911 $moretitle = $params[
'moretitle'] ??
'';
1913 $picto = $this->picto;
1914 if ($this->
type == self::TYPE_REPLACEMENT) {
1917 if ($this->
type == self::TYPE_CREDIT_NOTE) {
1920 if ($this->
type == self::TYPE_DEPOSIT) {
1924 if ($user->hasRight(
"facture",
"read")) {
1925 $datas[
'picto'] =
img_picto(
'', $picto).
' <u class="paddingrightonly">'.$langs->trans(
"Invoice").
'</u>';
1927 $datas[
'picto'] .=
' '.$this->getLibType(1);
1930 if (!empty($params[
'fromajaxtooltip']) && !isset($this->totalpaid)) {
1934 if (isset($this->
status) && isset($this->totalpaid)) {
1935 $datas[
'picto'] .=
' '.$this->getLibStatut(5, $this->totalpaid);
1938 $datas[
'picto'] .=
' - '.$moretitle;
1940 if (!empty($this->
ref)) {
1941 $datas[
'ref'] =
'<br><b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
1943 if (!empty($this->ref_customer)) {
1944 $datas[
'refcustomer'] =
'<br><b>'.$langs->trans(
'RefCustomer').
':</b> '.$this->ref_customer;
1946 if (!empty($this->date)) {
1947 $datas[
'date'] =
'<br><b>'.$langs->trans(
'Date').
':</b> '.
dol_print_date($this->date,
'day');
1949 if (!empty($this->total_ht)) {
1950 $datas[
'amountht'] =
'<br><b>'.$langs->trans(
'AmountHT').
':</b> '.
price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1952 if (!empty($this->total_tva)) {
1953 $datas[
'amountvat'] =
'<br><b>'.$langs->trans(
'AmountVAT').
':</b> '.
price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1955 if (!empty($this->revenuestamp) && $this->revenuestamp != 0) {
1956 $datas[
'amountrevenustamp'] =
'<br><b>'.$langs->trans(
'RevenueStamp').
':</b> '.
price($this->revenuestamp, 0, $langs, 0, -1, -1, $conf->currency);
1958 if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) {
1960 $datas[
'amountlt1'] =
'<br><b>'.$langs->transcountry(
'AmountLT1', $mysoc->country_code).
':</b> '.
price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
1962 if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
1963 $datas[
'amountlt2'] =
'<br><b>'.$langs->transcountry(
'AmountLT2', $mysoc->country_code).
':</b> '.
price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
1965 if (!empty($this->total_ttc)) {
1966 $datas[
'amountttc'] =
'<br><b>'.$langs->trans(
'AmountTTC').
':</b> '.
price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1987 public function getNomUrl($withpicto = 0, $option =
'', $max = 0, $short = 0, $moretitle =
'', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target =
'')
1989 global $langs, $conf, $user;
1991 if (!empty($conf->dol_no_mouse_hover)) {
1997 if ($option ==
'withdraw') {
1998 $url = DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.$this->id;
2000 $url = DOL_URL_ROOT.
'/compta/facture/card.php?id='.$this->id;
2003 if (!$user->hasRight(
"facture",
"read")) {
2007 if ($option !==
'nolink') {
2009 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2010 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
2011 $add_save_lastsearch_values = 1;
2013 if ($add_save_lastsearch_values) {
2014 $url .=
'&save_lastsearch_values=1';
2022 $picto = $this->picto;
2023 if ($this->
type == self::TYPE_REPLACEMENT) {
2026 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2029 if ($this->
type == self::TYPE_DEPOSIT) {
2035 'objecttype' => $this->element,
2036 'moretitle' => $moretitle,
2037 'option' => $option,
2039 $classfortooltip =
'classfortooltip';
2042 $classfortooltip =
'classforajaxtooltip';
2043 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
2049 $linkclose = ($target ?
' target="'.$target.
'"' :
'');
2050 if (empty($notooltip) && $user->hasRight(
"facture",
"read")) {
2052 $label = $langs->trans(
"Invoice");
2053 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
2055 $linkclose .= ($label ?
' title="'.dol_escape_htmltag($label, 1).
'"' :
' title="tocomplete"');
2056 $linkclose .= $dataparams.
' class="'.$classfortooltip.
'"';
2059 $linkstart =
'<a href="'.$url.
'"';
2060 $linkstart .= $linkclose.
'>';
2063 if ($option ==
'nolink') {
2068 $result .= $linkstart;
2070 $result .=
img_object(($notooltip ?
'' : $label), ($picto ? $picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'"'), 0, 0, $notooltip ? 0 : 1);
2072 if ($withpicto != 2) {
2073 $result .= ($max ?
dol_trunc($this->
ref, $max) : $this->ref);
2075 $result .= $linkend;
2077 if ($addlinktonotes) {
2078 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
2081 $notetoshow = $langs->trans(
"ViewPrivateNote").
':<br>'.$txttoshow;
2082 $result .=
' <span class="note inline-block">';
2083 $result .=
'<a href="'.DOL_URL_ROOT.
'/compta/facture/note.php?id='.$this->
id.
'" class="classfortooltip" title="'.
dol_escape_htmltag($notetoshow, 1, 1).
'">';
2088 $result .=
'</span>';
2092 global $action, $hookmanager;
2093 $hookmanager->initHooks(array(
'invoicedao'));
2094 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result,
'notooltip' => $notooltip,
'addlinktonotes' => $addlinktonotes,
'save_lastsearch_value' => $save_lastsearch_value,
'target' => $target);
2095 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
2097 $result = $hookmanager->resPrint;
2099 $result .= $hookmanager->resPrint;
2115 public function fetch($rowid, $ref =
'', $ref_ext =
'', $notused = 0, $fetch_situation =
false)
2117 if (empty($rowid) && empty($ref) && empty($ref_ext)) {
2121 $sql =
'SELECT f.rowid, f.entity, f.ref, f.ref_client, f.ref_ext, f.type, f.subtype, f.fk_soc';
2122 $sql .=
', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
2123 $sql .=
', f.datef as df, f.date_pointoftax';
2124 $sql .=
', f.date_lim_reglement as dlr';
2125 $sql .=
', f.datec as datec';
2126 $sql .=
', f.date_valid as datev';
2127 $sql .=
', f.tms as datem';
2128 $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';
2129 $sql .=
', f.fk_facture_source, f.fk_fac_rec_source';
2130 $sql .=
', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
2131 $sql .=
', f.situation_cycle_ref, f.situation_counter, f.situation_final';
2132 $sql .=
', f.fk_account';
2133 $sql .=
", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
2134 $sql .=
', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
2135 $sql .=
', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
2136 $sql .=
', f.fk_incoterms, f.location_incoterms';
2137 $sql .=
', f.module_source, f.pos_source';
2138 $sql .=
", i.libelle as label_incoterms";
2139 $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";
2140 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as f';
2141 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
2142 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as p ON f.fk_mode_reglement = p.id';
2143 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_incoterms as i ON f.fk_incoterms = i.rowid';
2146 $sql .=
" WHERE f.rowid = ".((int) $rowid);
2148 $sql .=
' WHERE f.entity IN ('.getEntity(
'invoice').
')';
2150 $sql .=
" AND f.ref = '".$this->db->escape($ref).
"'";
2153 $sql .=
" AND f.ref_ext = '".$this->db->escape($ref_ext).
"'";
2157 dol_syslog(get_class($this).
"::fetch", LOG_DEBUG);
2158 $resql = $this->db->query($sql);
2160 if ($this->db->num_rows($resql)) {
2161 $obj = $this->db->fetch_object($resql);
2163 $this->
id = $obj->rowid;
2164 $this->entity = $obj->entity;
2166 $this->
ref = $obj->ref;
2167 $this->ref_client = $obj->ref_client;
2168 $this->ref_customer = $obj->ref_client;
2169 $this->ref_ext = $obj->ref_ext;
2170 $this->
type = $obj->type;
2171 $this->subtype = $obj->subtype;
2172 $this->date = $this->db->jdate($obj->df);
2173 $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
2174 $this->date_creation = $this->db->jdate($obj->datec);
2175 $this->date_validation = $this->db->jdate($obj->datev);
2176 $this->date_modification = $this->db->jdate($obj->datem);
2177 $this->datem = $this->db->jdate($obj->datem);
2178 $this->total_ht = $obj->total_ht;
2179 $this->total_tva = $obj->total_tva;
2180 $this->total_localtax1 = $obj->localtax1;
2181 $this->total_localtax2 = $obj->localtax2;
2182 $this->total_ttc = $obj->total_ttc;
2183 $this->revenuestamp = $obj->revenuestamp;
2184 $this->paye = $obj->paye;
2185 $this->close_code = $obj->close_code;
2186 $this->close_note = $obj->close_note;
2188 $this->socid = $obj->fk_soc;
2189 $this->thirdparty =
null;
2191 $this->fk_project = $obj->fk_project;
2192 $this->project =
null;
2194 $this->
statut = $obj->status;
2195 $this->
status = $obj->status;
2197 $this->date_lim_reglement = $this->db->jdate($obj->dlr);
2198 $this->mode_reglement_id = $obj->fk_mode_reglement;
2199 $this->mode_reglement_code = $obj->mode_reglement_code;
2200 $this->mode_reglement = $obj->mode_reglement_libelle;
2201 $this->cond_reglement_id = $obj->fk_cond_reglement;
2202 $this->cond_reglement_code = $obj->cond_reglement_code;
2203 $this->cond_reglement = $obj->cond_reglement_libelle;
2204 $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
2205 $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account :
null;
2206 $this->fk_facture_source = $obj->fk_facture_source;
2207 $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
2208 $this->note = $obj->note_private;
2209 $this->note_private = $obj->note_private;
2210 $this->note_public = $obj->note_public;
2211 $this->user_creation_id = $obj->fk_user_author;
2212 $this->user_validation_id = $obj->fk_user_valid;
2213 $this->user_modification_id = $obj->fk_user_modif;
2214 $this->fk_user_author = $obj->fk_user_author;
2215 $this->fk_user_valid = $obj->fk_user_valid;
2216 $this->fk_user_modif = $obj->fk_user_modif;
2217 $this->model_pdf = $obj->model_pdf;
2218 $this->last_main_doc = $obj->last_main_doc;
2219 $this->situation_cycle_ref = $obj->situation_cycle_ref;
2220 $this->situation_counter = $obj->situation_counter;
2221 $this->situation_final = $obj->situation_final;
2222 $this->retained_warranty = $obj->retained_warranty;
2223 $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
2224 $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
2226 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams,
true) : array();
2229 $this->fk_incoterms = $obj->fk_incoterms;
2230 $this->location_incoterms = $obj->location_incoterms;
2231 $this->label_incoterms = $obj->label_incoterms;
2233 $this->module_source = $obj->module_source;
2234 $this->pos_source = $obj->pos_source;
2237 $this->fk_multicurrency = $obj->fk_multicurrency;
2238 $this->multicurrency_code = $obj->multicurrency_code;
2239 $this->multicurrency_tx = $obj->multicurrency_tx;
2240 $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
2241 $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
2242 $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
2244 if (($this->
type == self::TYPE_SITUATION || ($this->
type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
2253 $this->lines = array();
2257 $this->error = $this->db->error();
2261 $this->db->free($resql);
2265 $this->error =
'Invoice with id='.$rowid.
' or ref='.$ref.
' or ref_ext='.$ref_ext.
' not found';
2267 dol_syslog(__METHOD__.$this->error, LOG_WARNING);
2271 $this->error = $this->db->lasterror();
2286 public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
2289 $this->lines = array();
2291 $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,';
2292 $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,';
2293 $sql .=
' l.situation_percent, l.fk_prev_id,';
2294 $sql .=
' l.rang, l.special_code, l.batch, l.fk_warehouse,';
2295 $sql .=
' l.date_start as date_start, l.date_end as date_end,';
2296 $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,';
2297 $sql .=
' l.fk_unit,';
2298 $sql .=
' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
2299 $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';
2300 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as l';
2301 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON l.fk_product = p.rowid';
2302 $sql .=
' WHERE l.fk_facture = '.((int) $this->
id);
2303 $sql .=
' ORDER BY l.rang, l.rowid';
2305 dol_syslog(get_class($this).
'::fetch_lines', LOG_DEBUG);
2306 $result = $this->db->query($sql);
2308 $num = $this->db->num_rows($result);
2311 $objp = $this->db->fetch_object($result);
2314 $line->id = $objp->rowid;
2315 $line->rowid = $objp->rowid;
2316 $line->fk_facture = $objp->fk_facture;
2317 $line->label = $objp->custom_label;
2318 $line->desc = $objp->description;
2319 $line->description = $objp->description;
2320 $line->product_type = $objp->product_type;
2321 $line->ref = $objp->product_ref;
2322 $line->product_ref = $objp->product_ref;
2323 $line->libelle = $objp->product_label;
2324 $line->product_label = $objp->product_label;
2325 $line->product_barcode = $objp->product_barcode;
2326 $line->product_desc = $objp->product_desc;
2327 $line->fk_product_type = $objp->fk_product_type;
2328 $line->qty = $objp->qty;
2329 $line->subprice = $objp->subprice;
2330 $line->ref_ext = $objp->ref_ext;
2332 $line->vat_src_code = $objp->vat_src_code;
2333 $line->tva_tx = $objp->tva_tx;
2334 $line->localtax1_tx = $objp->localtax1_tx;
2335 $line->localtax2_tx = $objp->localtax2_tx;
2336 $line->localtax1_type = $objp->localtax1_type;
2337 $line->localtax2_type = $objp->localtax2_type;
2338 $line->remise_percent = $objp->remise_percent;
2339 $line->fk_remise_except = $objp->fk_remise_except;
2340 $line->fk_product = $objp->fk_product;
2341 $line->date_start = $this->db->jdate($objp->date_start);
2342 $line->date_end = $this->db->jdate($objp->date_end);
2343 $line->info_bits = $objp->info_bits;
2344 $line->total_ht = $objp->total_ht;
2345 $line->total_tva = $objp->total_tva;
2346 $line->total_localtax1 = $objp->total_localtax1;
2347 $line->total_localtax2 = $objp->total_localtax2;
2348 $line->total_ttc = $objp->total_ttc;
2350 $line->fk_fournprice = $objp->fk_fournprice;
2351 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
2352 $line->pa_ht = $marginInfos[0];
2353 $line->marge_tx = $marginInfos[1];
2354 $line->marque_tx = $marginInfos[2];
2355 $line->rang = $objp->rang;
2356 $line->special_code = $objp->special_code;
2357 $line->fk_parent_line = $objp->fk_parent_line;
2358 $line->situation_percent = $objp->situation_percent;
2359 $line->fk_prev_id = $objp->fk_prev_id;
2360 $line->fk_unit = $objp->fk_unit;
2362 $line->batch = $objp->batch;
2363 $line->fk_warehouse = $objp->fk_warehouse;
2366 $line->fk_accounting_account = $objp->fk_code_ventilation;
2369 $line->fk_multicurrency = $objp->fk_multicurrency;
2370 $line->multicurrency_code = $objp->multicurrency_code;
2371 $line->multicurrency_subprice = $objp->multicurrency_subprice;
2372 $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
2373 $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
2374 $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
2376 $line->fetch_optionals();
2379 if (
getDolGlobalInt(
'MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
2380 $tmpproduct =
new Product($this->db);
2381 $tmpproduct->fetch($objp->fk_product);
2382 $tmpproduct->getMultiLangs();
2384 $line->multilangs = $tmpproduct->multilangs;
2387 $this->lines[$i] = $line;
2391 $this->db->free($result);
2394 $this->error = $this->db->error();
2409 $this->tab_previous_situation_invoice = array();
2410 $this->tab_next_situation_invoice = array();
2412 $sql =
'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.
'facture';
2413 $sql .=
" WHERE rowid <> ".((int) $this->
id);
2414 $sql .=
' AND entity = '.((int) $this->entity);
2415 $sql .=
' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
2416 $sql .=
' ORDER BY situation_counter ASC';
2418 dol_syslog(get_class($this).
'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
2419 $result = $this->db->query($sql);
2420 if ($result && $this->db->num_rows($result) > 0) {
2421 while ($objp = $this->db->fetch_object($result)) {
2422 $invoice =
new Facture($this->db);
2423 if ($invoice->fetch($objp->rowid) > 0) {
2424 if ($objp->situation_counter < $this->situation_counter
2425 || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id)
2427 $this->tab_previous_situation_invoice[] = $invoice;
2429 $this->tab_next_situation_invoice[] = $invoice;
2448 if (empty($this->
type)) {
2451 if (isset($this->subtype)) {
2452 $this->subtype = (int) trim((
string) $this->subtype);
2454 if (isset($this->
ref)) {
2455 $this->
ref = trim($this->
ref);
2457 if (isset($this->ref_ext)) {
2458 $this->ref_ext = trim($this->ref_ext);
2461 if (isset($this->ref_client)) {
2462 $this->ref_client = trim($this->ref_client);
2464 if (isset($this->ref_customer)) {
2465 $this->ref_customer = trim($this->ref_customer);
2467 if (isset($this->increment)) {
2468 $this->increment = trim($this->increment);
2470 if (isset($this->close_code)) {
2471 $this->close_code = trim($this->close_code);
2473 if (isset($this->close_note)) {
2474 $this->close_note = trim($this->close_note);
2476 if (isset($this->note) || isset($this->note_private)) {
2477 $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private));
2479 if (isset($this->note) || isset($this->note_private)) {
2480 $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
2482 if (isset($this->note_public)) {
2483 $this->note_public = trim($this->note_public);
2485 if (isset($this->model_pdf)) {
2486 $this->model_pdf = trim($this->model_pdf);
2488 if (isset($this->import_key)) {
2489 $this->import_key = trim($this->import_key);
2491 if (isset($this->retained_warranty)) {
2492 $this->retained_warranty = (float) $this->retained_warranty;
2500 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture SET";
2501 $sql .=
" ref=".(isset($this->
ref) ?
"'".$this->db->escape($this->
ref).
"'" :
"null").
",";
2502 $sql .=
" ref_ext=".(isset($this->ref_ext) ?
"'".$this->db->escape($this->ref_ext).
"'" :
"null").
",";
2503 $sql .=
" type=".(isset($this->
type) ? $this->db->escape($this->
type) :
"null").
",";
2504 $sql .=
" subtype=".(isset($this->subtype) ? $this->db->escape($this->subtype) :
"null").
",";
2505 $sql .=
" ref_client=".(isset($this->ref_customer) ?
"'".$this->db->escape($this->ref_customer).
"'" : (isset($this->ref_client) ?
"'".$this->db->escape($this->ref_client).
"'" :
"null")).
",";
2506 $sql .=
" increment=".(isset($this->increment) ?
"'".$this->db->escape($this->increment).
"'" :
"null").
",";
2507 $sql .=
" fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) :
"null").
",";
2508 $sql .=
" datec=".(strval($this->date_creation) !=
'' ?
"'".$this->db->idate($this->date_creation).
"'" :
'null').
",";
2509 $sql .=
" datef=".(strval($this->date) !=
'' ?
"'".$this->db->idate($this->date).
"'" :
'null').
",";
2510 $sql .=
" date_pointoftax=".(strval($this->date_pointoftax) !=
'' ?
"'".$this->db->idate($this->date_pointoftax).
"'" :
'null').
",";
2511 $sql .=
" date_valid=".(strval($this->date_validation) !=
'' ?
"'".$this->db->idate($this->date_validation).
"'" :
'null').
",";
2512 $sql .=
" paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).
",";
2513 $sql .=
" close_code=".(isset($this->close_code) ?
"'".$this->db->escape($this->close_code).
"'" :
"null").
",";
2514 $sql .=
" close_note=".(isset($this->close_note) ?
"'".$this->db->escape($this->close_note).
"'" :
"null").
",";
2515 $sql .=
" total_tva=".(isset($this->total_tva) ? (float) $this->total_tva :
"null").
",";
2516 $sql .=
" localtax1=".(isset($this->total_localtax1) ? (float) $this->total_localtax1 :
"null").
",";
2517 $sql .=
" localtax2=".(isset($this->total_localtax2) ? (float) $this->total_localtax2 :
"null").
",";
2518 $sql .=
" total_ht=".(isset($this->total_ht) ? (float) $this->total_ht :
"null").
",";
2519 $sql .=
" total_ttc=".(isset($this->total_ttc) ? (float) $this->total_ttc :
"null").
",";
2520 $sql .=
" revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp !=
'') ? (
float) $this->revenuestamp :
"null").
",";
2521 $sql .=
" fk_statut=".(isset($this->
status) ? (int) $this->
status :
"null").
",";
2522 $sql .=
" fk_user_valid=".(isset($this->fk_user_valid) ? (int) $this->fk_user_valid :
"null").
",";
2523 $sql .=
" fk_facture_source=".(isset($this->fk_facture_source) ? (int) $this->fk_facture_source :
"null").
",";
2524 $sql .=
" fk_projet=".(isset($this->fk_project) ? (int) $this->fk_project :
"null").
",";
2525 $sql .=
" fk_cond_reglement=".(isset($this->cond_reglement_id) ? (int) $this->cond_reglement_id :
"null").
",";
2526 $sql .=
" fk_mode_reglement=".(isset($this->mode_reglement_id) ? (int) $this->mode_reglement_id :
"null").
",";
2527 $sql .=
" date_lim_reglement=".(strval($this->date_lim_reglement) !=
'' ?
"'".$this->db->idate($this->date_lim_reglement).
"'" :
'null').
",";
2528 $sql .=
" note_private=".(isset($this->note_private) ?
"'".$this->db->escape($this->note_private).
"'" :
"null").
",";
2529 $sql .=
" note_public=".(isset($this->note_public) ?
"'".$this->db->escape($this->note_public).
"'" :
"null").
",";
2530 $sql .=
" model_pdf=".(isset($this->model_pdf) ?
"'".$this->db->escape($this->model_pdf).
"'" :
"null").
",";
2531 $sql .=
" import_key=".(isset($this->import_key) ?
"'".$this->db->escape($this->import_key).
"'" :
"null").
",";
2532 $sql .=
" situation_cycle_ref=".(empty($this->situation_cycle_ref) ?
"null" : (int) $this->situation_cycle_ref).
",";
2533 $sql .=
" situation_counter=".(empty($this->situation_counter) ?
"null" : (int) $this->situation_counter).
",";
2534 $sql .=
" situation_final=".(empty($this->situation_final) ?
"0" : (int) $this->situation_final).
",";
2535 $sql .=
" retained_warranty=".(empty($this->retained_warranty) ?
"0" : (float) $this->retained_warranty).
",";
2536 $sql .=
" retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) !=
'' ?
"'".$this->db->idate($this->retained_warranty_date_limit).
"'" :
'null').
",";
2537 $sql .=
" retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ? (int) $this->retained_warranty_fk_cond_reglement :
"null");
2538 $sql .=
" WHERE rowid=".((int) $this->
id);
2542 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
2543 $resql = $this->db->query($sql);
2546 $this->errors[] =
"Error ".$this->db->lasterror();
2556 if (!$error && !$notrigger) {
2567 foreach ($this->errors as $errmsg) {
2568 dol_syslog(get_class($this).
"::update ".$errmsg, LOG_ERR);
2569 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2571 $this->db->rollback();
2574 $this->db->commit();
2590 global $conf, $langs;
2592 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2593 include_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
2598 $result = $remise->fetch($idremise);
2601 if ($remise->fk_facture) {
2602 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed");
2603 $this->db->rollback();
2608 $facligne->fk_facture = $this->id;
2609 $facligne->fk_remise_except = $remise->id;
2610 $facligne->desc = $remise->description;
2611 $facligne->vat_src_code = $remise->vat_src_code;
2612 $facligne->tva_tx = $remise->tva_tx;
2613 $facligne->subprice = -$remise->amount_ht;
2614 $facligne->fk_product = 0;
2616 $facligne->remise_percent = 0;
2617 $facligne->rang = -1;
2618 $facligne->info_bits = 2;
2621 $facligne->rang = 1;
2622 $linecount = count($this->lines);
2623 for ($ii = 1; $ii <= $linecount; $ii++) {
2629 if ($remise->fk_facture_source > 0) {
2630 $srcinvoice =
new Facture($this->db);
2631 $srcinvoice->fetch($remise->fk_facture_source);
2632 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
2634 $arraytmp = $formmargin->getMarginInfosArray($srcinvoice,
false);
2635 $facligne->pa_ht = $arraytmp[
'pa_total'];
2638 $facligne->total_ht = -$remise->amount_ht;
2639 $facligne->total_tva = -$remise->amount_tva;
2640 $facligne->total_ttc = -$remise->amount_ttc;
2642 $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
2643 $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
2644 $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
2645 $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
2647 $lineid = $facligne->insert();
2652 $result = $remise->link_to_invoice($lineid, 0);
2654 $this->error = $remise->error;
2655 $this->db->rollback();
2659 $this->db->commit();
2662 $this->error = $facligne->error;
2663 $this->db->rollback();
2667 $this->error = $facligne->error;
2668 $this->db->rollback();
2672 $this->db->rollback();
2694 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2695 if (empty($ref_client)) {
2696 $sql .=
' SET ref_client = NULL';
2698 $sql .=
' SET ref_client = \''.$this->db->escape($ref_client).
'\'';
2700 $sql .=
" WHERE rowid = ".((int) $this->
id);
2702 dol_syslog(__METHOD__.
' this->id='.$this->id.
', ref_client='.$ref_client, LOG_DEBUG);
2703 $resql = $this->db->query($sql);
2705 $this->errors[] = $this->db->error();
2710 $this->ref_client = $ref_client;
2711 $this->ref_customer = $ref_client;
2714 if (!$notrigger && empty($error)) {
2724 $this->ref_client = $ref_client;
2725 $this->ref_customer = $ref_client;
2727 $this->db->commit();
2730 foreach ($this->errors as $errmsg) {
2731 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
2732 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
2734 $this->db->rollback();
2747 public function delete($user, $notrigger = 0, $idwarehouse = -1)
2749 global $langs, $conf;
2750 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
2754 dol_syslog(get_class($this).
"::delete rowid=".$rowid.
", ref=".$this->ref.
", thirdparty=".(empty($this->thirdparty) ?
'' : $this->thirdparty->name), LOG_DEBUG);
2767 if (!$error && !$notrigger) {
2781 dol_syslog(get_class($this).
"::delete error deleteExtraFields ".$this->error, LOG_ERR);
2795 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'societe_remise_except';
2796 $sql .=
' WHERE fk_facture_source = '.((int) $rowid);
2797 $sql .=
' AND fk_facture_line IS NULL';
2798 $resql = $this->db->query($sql);
2802 $list_rowid_det = array();
2803 foreach ($this->lines as $key => $invoiceline) {
2804 $list_rowid_det[] = $invoiceline->id;
2808 if (count($list_rowid_det)) {
2809 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
2810 $sql .=
' SET fk_facture = NULL, fk_facture_line = NULL';
2811 $sql .=
' WHERE fk_facture_line IN ('.$this->db->sanitize(implode(
',', $list_rowid_det)).
')';
2813 if (!$this->db->query($sql)) {
2814 $this->error = $this->db->error().
" sql=".$sql;
2815 $this->errors[] = $this->error;
2816 $this->db->rollback();
2823 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'eventorganization_conferenceorboothattendee';
2824 $sql .=
' SET fk_invoice = NULL';
2825 $sql .=
' WHERE fk_invoice = '.((int) $rowid);
2827 if (!$this->db->query($sql)) {
2828 $this->error = $this->db->error().
" sql=".$sql;
2829 $this->errors[] = $this->error;
2830 $this->db->rollback();
2834 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
2835 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
2836 $sql .=
' WHERE invoice_id = '.((int) $rowid);
2838 if (!$this->db->query($sql)) {
2839 $this->error = $this->db->error().
" sql=".$sql;
2840 $this->errors[] = $this->error;
2841 $this->db->rollback();
2846 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse != -1) {
2847 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
2848 $langs->load(
"agenda");
2850 $num = count($this->lines);
2851 for ($i = 0; $i < $num; $i++) {
2852 if ($this->lines[$i]->fk_product > 0) {
2854 $mouvP->origin = &$this;
2855 $mouvP->setOrigin($this->element, $this->
id);
2857 if ($this->
type == self::TYPE_CREDIT_NOTE) {
2858 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2860 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceDeleteDolibarr", $this->ref));
2867 $main = MAIN_DB_PREFIX.
'facturedet';
2868 $ef = $main.
"_extrafields";
2869 $sqlef =
"DELETE FROM ".$ef.
" WHERE fk_object IN (SELECT rowid FROM ".$main.
" WHERE fk_facture = ".((int) $rowid).
")";
2871 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facturedet WHERE fk_facture = '.((int) $rowid);
2874 $sql =
'DELETE FROM '.MAIN_DB_PREFIX.
'facture WHERE rowid = '.((int) $rowid);
2876 $resql = $this->db->query($sql);
2884 if ($conf->facture->dir_output && !empty($this->
ref)) {
2885 $dir = $conf->facture->dir_output.
"/".$ref;
2886 $file = $conf->facture->dir_output.
"/".$ref.
"/".$ref.
".pdf";
2887 if (file_exists($file)) {
2891 $langs->load(
"errors");
2892 $this->error = $langs->trans(
"ErrorFailToDeleteFile", $file);
2893 $this->errors[] = $this->error;
2894 $this->db->rollback();
2898 if (file_exists($dir)) {
2900 $langs->load(
"errors");
2901 $this->error = $langs->trans(
"ErrorFailToDeleteDir", $dir);
2902 $this->errors[] = $this->error;
2903 $this->db->rollback();
2909 $this->db->commit();
2912 $this->error = $this->db->lasterror().
" sql=".$sql;
2913 $this->errors[] = $this->error;
2914 $this->db->rollback();
2918 $this->error = $this->db->lasterror().
" sql=".$sql;
2919 $this->errors[] = $this->error;
2920 $this->db->rollback();
2924 $this->db->rollback();
2941 public function set_paid($user, $close_code =
'', $close_note =
'')
2944 dol_syslog(get_class($this).
"::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
2945 return $this->
setPaid($user, $close_code, $close_note);
2958 public function setPaid($user, $close_code =
'', $close_note =
'')
2962 if ($this->paye != 1) {
2967 dol_syslog(get_class($this).
"::setPaid rowid=".((
int) $this->
id), LOG_DEBUG);
2969 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
2970 $sql .=
' fk_statut='.self::STATUS_CLOSED;
2975 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
2978 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
2980 $sql .=
', fk_user_closing = '.((int) $user->id);
2981 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
2982 $sql .=
" WHERE rowid = ".((int) $this->
id);
2984 $resql = $this->db->query($sql);
2994 $this->error = $this->db->lasterror();
2998 $this->db->commit();
3001 $this->db->rollback();
3024 dol_syslog(get_class($this).
"::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
3042 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3043 $sql .=
' SET paye=0, fk_statut='.self::STATUS_VALIDATED.
', close_code=null, close_note=null,';
3044 $sql .=
' date_closing=null,';
3045 $sql .=
' fk_user_closing=null';
3046 $sql .=
" WHERE rowid = ".((int) $this->
id);
3048 dol_syslog(get_class($this).
"::setUnpaid", LOG_DEBUG);
3049 $resql = $this->db->query($sql);
3059 $this->error = $this->db->error();
3064 $this->db->commit();
3067 $this->db->rollback();
3089 dol_syslog(get_class($this).
"::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
3090 return $this->
setCanceled($user, $close_code, $close_note);
3103 public function setCanceled($user, $close_code =
'', $close_note =
'')
3105 dol_syslog(get_class($this).
"::setCanceled rowid=".((
int) $this->
id), LOG_DEBUG);
3110 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET';
3111 $sql .=
' fk_statut='.self::STATUS_ABANDONED;
3113 $sql .=
", close_code='".$this->db->escape($close_code).
"'";
3116 $sql .=
", close_note='".$this->db->escape($close_note).
"'";
3118 $sql .=
', fk_user_closing = '.((int) $user->id);
3119 $sql .=
", date_closing = '".$this->db->idate($now).
"'";
3120 $sql .=
" WHERE rowid = ".((int) $this->
id);
3122 $resql = $this->db->query($sql);
3126 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
3127 $sql .=
' SET fk_facture = NULL';
3128 $sql .=
' WHERE fk_facture = '.((int) $this->
id);
3130 $resql = $this->db->query($sql);
3135 $this->db->rollback();
3140 $this->db->commit();
3143 $this->error = $this->db->error().
" sql=".$sql;
3144 $this->db->rollback();
3148 $this->error = $this->db->error().
" sql=".$sql;
3149 $this->db->rollback();
3165 public function validate($user, $force_number =
'', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
3167 global $conf, $langs, $mysoc;
3168 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
3170 $productStatic =
null;
3171 $warehouseStatic =
null;
3172 if ($batch_rule > 0) {
3173 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
3174 require_once DOL_DOCUMENT_ROOT.
'/product/class/productbatch.class.php';
3175 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
3176 $productStatic =
new Product($this->db);
3177 $warehouseStatic =
new Entrepot($this->db);
3184 dol_syslog(get_class($this).
'::validate user='.$user->id.
', force_number='.$force_number.
', idwarehouse='.$idwarehouse);
3191 if ($this->
status != self::STATUS_DRAFT) {
3192 dol_syslog(get_class($this).
"::validate Current status is not draft. operation canceled.", LOG_WARNING);
3195 if (count($this->lines) <= 0) {
3196 $langs->load(
"errors");
3197 $this->error = $langs->trans(
"ErrorObjectMustHaveLinesToBeValidated", $this->
ref);
3201 || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'facture',
'invoice_advance',
'validate'))) {
3202 $this->error =
'Permission denied';
3203 dol_syslog(get_class($this).
"::validate ".$this->error.
' MAIN_USE_ADVANCED_PERMS=' .
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'), LOG_ERR);
3206 if ((preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) &&
3214 if (!$last_of_type[0]) {
3215 $this->error = $langs->transnoentities(
"ErrorInvoiceIsNotLastOfSameType", $this->
ref,
dol_print_date($this->date,
'day'),
dol_print_date($last_of_type[1],
'day'));
3221 if (!empty($this->thirdparty) && is_object($this->thirdparty)) {
3222 $array_to_check = array(
'IDPROF1',
'IDPROF2',
'IDPROF3',
'IDPROF4',
'IDPROF5',
'IDPROF6',
'EMAIL',
'ACCOUNTANCY_CODE_CUSTOMER');
3223 foreach ($array_to_check as $key) {
3224 $keymin = strtolower($key);
3225 if (!property_exists($this->thirdparty, $keymin)) {
3228 $vallabel = $this->thirdparty->$keymin;
3230 $i = (int) preg_replace(
'/[^0-9]/',
'', $key);
3232 if ($this->thirdparty->isACompany()) {
3234 if ($mysoc->country_id > 0 && $this->thirdparty->country_id == $mysoc->country_id) {
3235 $idprof_mandatory =
'SOCIETE_'.$key.
'_INVOICE_MANDATORY';
3236 if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
3237 $langs->load(
"errors");
3238 $this->error = $langs->trans(
'ErrorProdIdIsMandatory', $langs->transcountry(
'ProfId'.$i, $this->thirdparty->country_code)).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3239 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3245 if ($key ==
'EMAIL') {
3248 $langs->load(
"errors");
3249 $this->error = $langs->trans(
"ErrorBadEMail", $this->thirdparty->email).
' ('.$langs->trans(
"ForbiddenBySetupRules").
') ['.$langs->trans(
'Company').
' : '.$this->thirdparty->name.
']';
3250 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3254 if ($key ==
'ACCOUNTANCY_CODE_CUSTOMER') {
3256 if (
getDolGlobalString(
'SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_INVOICE_MANDATORY') && empty($this->thirdparty->code_compta)) {
3257 $langs->load(
"errors");
3258 $this->error = $langs->trans(
"ErrorAccountancyCodeCustomerIsMandatory", $this->thirdparty->name).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')';
3259 dol_syslog(__METHOD__.
' '.$this->error, LOG_ERR);
3268 $array_to_check = array(
'REF_CLIENT' =>
'RefCustomer');
3269 foreach ($array_to_check as $key => $val) {
3270 $keymin = strtolower($key);
3271 $vallabel = $this->$keymin;
3274 $keymandatory =
'INVOICE_'.$key.
'_MANDATORY_FOR_VALIDATION';
3276 $langs->load(
"errors");
3278 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv($val));
3285 if ($this->
type == self::TYPE_REPLACEMENT) {
3287 if ($this->fk_facture_source <= 0) {
3288 $this->error = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceReplacement"));
3289 $this->db->rollback();
3294 $facreplaced =
new Facture($this->db);
3295 $result = $facreplaced->fetch($this->fk_facture_source);
3297 $this->error = $langs->trans(
"ErrorBadInvoice");
3298 $this->db->rollback();
3303 $idreplacement = $facreplaced->getIdReplacingInvoice(
'validated');
3304 if ($idreplacement && $idreplacement != $this->
id) {
3305 $facreplacement =
new Facture($this->db);
3306 $facreplacement->fetch($idreplacement);
3307 $this->error = $langs->trans(
"ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
3308 $this->db->rollback();
3312 $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED,
'');
3314 $this->error = $facreplaced->error;
3315 $this->db->rollback();
3321 if ($force_number) {
3322 $num = $force_number;
3323 } elseif (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
3339 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3340 $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).
"'";
3342 $sql .=
", datef='".$this->db->idate($this->date).
"'";
3343 $sql .=
", date_lim_reglement='".$this->db->idate($this->date_lim_reglement).
"'";
3345 $sql .=
" WHERE rowid = ".((int) $this->
id);
3347 dol_syslog(get_class($this).
"::validate", LOG_DEBUG);
3348 $resql = $this->db->query($sql);
3350 $this->error = $this->db->lasterror();
3355 if (!$error && (preg_match(
'/^[\(]?PROV/i', $this->
ref))) {
3361 $result = $this->thirdparty->setAsCustomer();
3364 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL') && $idwarehouse > 0) {
3365 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3366 $langs->load(
"agenda");
3369 $cpt = count($this->lines);
3370 for ($i = 0; $i < $cpt; $i++) {
3371 if ($this->lines[$i]->fk_product > 0) {
3373 $mouvP->origin = &$this;
3374 $mouvP->setOrigin($this->element, $this->
id);
3377 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3380 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceValidatedInDolibarr", $num),
'',
'', $this->lines[$i]->batch);
3383 $this->error = $mouvP->error;
3384 $this->errors = array_merge($this->errors, $mouvP->errors);
3390 $is_batch_line =
false;
3391 if ($batch_rule > 0) {
3392 $productStatic->fetch($this->lines[$i]->fk_product);
3393 if ($productStatic->hasbatch()) {
3394 $is_batch_line =
true;
3395 $product_qty_remain = $this->lines[$i]->qty;
3401 $sortfield =
'pl.sellby,pl.eatby,pb.qty,pl.rowid';
3402 $sortorder =
'ASC,ASC,ASC,ASC';
3405 $resBatchList = $productbatch->findAllForProduct($productStatic->id, $idwarehouse, (
getDolGlobalInt(
'STOCK_ALLOW_NEGATIVE_TRANSFER') ?
null : 0), $sortfield, $sortorder);
3406 if (!is_array($resBatchList)) {
3408 $this->error = $this->db->lasterror();
3412 $batchList = $resBatchList;
3413 if (empty($batchList)) {
3415 $langs->load(
'errors');
3416 $warehouseStatic->fetch($idwarehouse);
3417 $this->error = $langs->trans(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3418 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3421 foreach ($batchList as $batch) {
3422 if ($batch->qty <= 0) {
3427 if ($batch->qty >= $product_qty_remain) {
3428 $product_batch_qty = $product_qty_remain;
3431 $product_batch_qty = $batch->qty;
3433 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3436 $this->error = $mouvP->error;
3437 $this->errors = array_merge($this->errors, $mouvP->errors);
3441 $product_qty_remain -= $product_batch_qty;
3443 if ($product_qty_remain <= 0) {
3448 if (!$error && $product_qty_remain > 0) {
3451 $batch = $batchList[0];
3452 $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans(
'InvoiceValidatedInDolibarr', $num),
'',
'',
'', $batch->batch);
3455 $this->error = $mouvP->error;
3456 $this->errors = array_merge($this->errors, $mouvP->errors);
3460 $langs->load(
'errors');
3461 $warehouseStatic->fetch($idwarehouse);
3462 $this->error = $langs->trans(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
3463 dol_syslog(__METHOD__.
' Error: '.$langs->transnoentitiesnoconv(
'ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
3470 if (!$is_batch_line) {
3471 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceValidatedInDolibarr", $num));
3474 $this->error = $mouvP->error;
3475 $this->errors = array_merge($this->errors, $mouvP->errors);
3488 if (!$error && $this->
type == self::TYPE_CREDIT_NOTE && $this->fk_facture_source > 0) {
3489 $invoice_situation =
new Facture($this->db);
3490 $result = $invoice_situation->fetch($this->fk_facture_source);
3491 if ($result > 0 && $invoice_situation->type == self::TYPE_SITUATION && $invoice_situation->situation_final == 1) {
3492 $invoice_situation->situation_final = 0;
3494 $result = $invoice_situation->setFinal($user, 1);
3497 $this->error = $invoice_situation->error;
3498 $this->errors = array_merge($this->errors, $invoice_situation->errors);
3504 if (!$error && !$notrigger) {
3514 $this->oldref = $this->ref;
3517 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
3519 $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).
"'";
3520 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%' AND filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
3521 $resql = $this->db->query($sql);
3524 $this->error = $this->db->lasterror();
3526 $sql =
'UPDATE '.MAIN_DB_PREFIX.
"ecm_files set filepath = 'facture/".$this->db->escape($this->newref).
"'";
3527 $sql .=
" WHERE filepath = 'facture/".$this->db->escape($this->
ref).
"' and entity = ".$conf->entity;
3528 $resql = $this->db->query($sql);
3531 $this->error = $this->db->lasterror();
3537 $dirsource = $conf->facture->dir_output.
'/'.$oldref;
3538 $dirdest = $conf->facture->dir_output.
'/'.$newref;
3539 if (!$error && file_exists($dirsource)) {
3540 dol_syslog(get_class($this).
"::validate rename dir ".$dirsource.
" into ".$dirdest);
3542 if (@rename($dirsource, $dirdest)) {
3545 $listoffiles =
dol_dir_list($conf->facture->dir_output.
'/'.$newref,
'files', 1,
'^'.preg_quote($oldref,
'/'));
3546 foreach ($listoffiles as $fileentry) {
3547 $dirsource = $fileentry[
'name'];
3548 $dirdest = preg_replace(
'/^'.preg_quote($oldref,
'/').
'/', $newref, $dirsource);
3549 $dirsource = $fileentry[
'path'].
'/'.$dirsource;
3550 $dirdest = $fileentry[
'path'].
'/'.$dirdest;
3551 @rename($dirsource, $dirdest);
3569 $this->date_validation = $now;
3574 $nboflines = count($this->lines);
3575 while (($i < $nboflines) && $final) {
3577 $previousprogress = $this->lines[$i]->get_allprev_progress($this->lines[$i]->fk_facture);
3578 $current_progress = floatval($this->lines[$i]->situation_percent);
3579 $full_progress = $previousprogress + $current_progress;
3580 $final = ($full_progress == 100);
3582 $final = ($this->lines[$i]->situation_percent == 100);
3587 if (empty($final)) {
3588 $this->situation_final = 0;
3590 $this->situation_final = 1;
3601 $this->db->commit();
3604 $this->db->rollback();
3617 foreach ($this->tab_next_situation_invoice as $next_invoice) {
3618 $is_last = $next_invoice->is_last_in_cycle();
3620 if ($next_invoice->status == self::STATUS_DRAFT && $is_last != 1) {
3621 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3625 foreach ($next_invoice->lines as $line) {
3626 $result = $next_invoice->updateline(
3631 $line->remise_percent,
3635 $line->localtax1_tx,
3636 $line->localtax2_tx,
3639 $line->product_type,
3640 $line->fk_parent_line,
3642 $line->fk_fournprice,
3645 $line->special_code,
3646 $line->array_options,
3647 $line->situation_percent,
3652 $this->error = $langs->trans(
'updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
3673 global $conf, $langs;
3677 if ($this->
status == self::STATUS_DRAFT) {
3678 dol_syslog(__METHOD__.
" already draft status", LOG_WARNING);
3686 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
3687 $sql .=
" SET fk_statut = ".self::STATUS_DRAFT;
3688 $sql .=
" WHERE rowid = ".((int) $this->
id);
3690 $result = $this->db->query($sql);
3693 $this->oldcopy = clone $this;
3697 if ($this->
type != self::TYPE_DEPOSIT && $result >= 0 && isModEnabled(
'stock') &&
getDolGlobalString(
'STOCK_CALCULATE_ON_BILL')) {
3698 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/mouvementstock.class.php';
3699 $langs->load(
"agenda");
3701 $num = count($this->lines);
3702 for ($i = 0; $i < $num; $i++) {
3703 if ($this->lines[$i]->fk_product > 0) {
3705 $mouvP->origin = &$this;
3706 $mouvP->setOrigin($this->element, $this->
id);
3708 if ($this->
type == self::TYPE_CREDIT_NOTE) {
3709 $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3711 $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans(
"InvoiceBackToDraftInDolibarr", $this->ref));
3718 $old_statut = $this->status;
3723 $result = $this->
call_trigger(
'BILL_UNVALIDATE', $user);
3726 $this->
statut = $old_statut;
3727 $this->
status = $old_statut;
3731 $this->db->rollback();
3736 $this->db->commit();
3739 $this->db->rollback();
3743 $this->error = $this->db->error();
3744 $this->db->rollback();
3799 $remise_percent = 0,
3802 $fk_code_ventilation = 0,
3804 $fk_remise_except = 0,
3805 $price_base_type =
'HT',
3812 $fk_parent_line = 0,
3813 $fk_fournprice =
null,
3816 $array_options = array(),
3817 $situation_percent = 100,
3822 $noupdateafterinsertline = 0
3826 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
3830 global $mysoc, $conf, $langs;
3832 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);
3834 if ($this->
status == self::STATUS_DRAFT) {
3835 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3838 if (empty($remise_percent)) {
3839 $remise_percent = 0;
3844 if (empty($info_bits)) {
3850 if (empty($fk_code_ventilation)) {
3851 $fk_code_ventilation = 0;
3853 if (empty($txtva)) {
3856 if (empty($txlocaltax1)) {
3859 if (empty($txlocaltax2)) {
3862 if (empty($fk_parent_line) || $fk_parent_line < 0) {
3863 $fk_parent_line = 0;
3865 if (empty($fk_prev_id)) {
3866 $fk_prev_id =
'null';
3868 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
3869 $situation_percent = 100;
3871 if (empty($ref_ext)) {
3875 $remise_percent = (float)
price2num($remise_percent);
3878 $pu_ht_devise =
price2num($pu_ht_devise);
3881 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
3887 if ($price_base_type ==
'HT') {
3898 if ($date_start && $date_end && $date_start > $date_end) {
3899 $langs->load(
"errors");
3900 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
3906 $product_type = $type;
3907 if (!empty($fk_product) && $fk_product > 0) {
3908 $product =
new Product($this->db);
3909 $result = $product->fetch($fk_product);
3910 $product_type = $product->type;
3912 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
3913 $langs->load(
"errors");
3914 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
3915 $this->db->rollback();
3925 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
3926 $vat_src_code = $reg[1];
3927 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
3935 $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);
3937 $total_ht = $tabprice[0];
3938 $total_tva = $tabprice[1];
3939 $total_ttc = $tabprice[2];
3940 $total_localtax1 = $tabprice[9];
3941 $total_localtax2 = $tabprice[10];
3942 $pu_ht = $tabprice[3];
3945 $multicurrency_total_ht = $tabprice[16];
3946 $multicurrency_total_tva = $tabprice[17];
3947 $multicurrency_total_ttc = $tabprice[18];
3948 $pu_ht_devise = $tabprice[19];
3952 if ($ranktouse == -1) {
3953 $rangmax = $this->
line_max($fk_parent_line);
3954 $ranktouse = $rangmax + 1;
3960 $this->line->context = $this->context;
3962 $this->line->fk_facture = $this->id;
3963 $this->line->label = $label;
3964 $this->line->desc = $desc;
3965 $this->line->ref_ext = $ref_ext;
3967 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
3968 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
3970 $this->line->vat_src_code = $vat_src_code;
3971 $this->line->tva_tx = $txtva;
3972 $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
3973 $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
3974 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
3975 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
3977 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
3978 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
3979 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
3980 $this->line->total_localtax1 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax1) : $total_localtax1);
3981 $this->line->total_localtax2 = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_localtax2) : $total_localtax2);
3983 $this->line->fk_product = $fk_product;
3984 $this->line->product_type = $product_type;
3985 $this->line->remise_percent = $remise_percent;
3986 $this->line->date_start = $date_start;
3987 $this->line->date_end = $date_end;
3988 $this->line->fk_code_ventilation = $fk_code_ventilation;
3989 $this->line->rang = $ranktouse;
3990 $this->line->info_bits = $info_bits;
3991 $this->line->fk_remise_except = $fk_remise_except;
3993 $this->line->special_code = $special_code;
3994 $this->line->fk_parent_line = $fk_parent_line;
3995 $this->line->origin = $origin;
3996 $this->line->origin_id = $origin_id;
3997 $this->line->situation_percent = $situation_percent;
3998 $this->line->fk_prev_id = $fk_prev_id;
3999 $this->line->fk_unit = $fk_unit;
4002 $this->line->fk_fournprice = $fk_fournprice;
4003 $this->line->pa_ht = $pa_ht;
4006 $this->line->fk_multicurrency = $this->fk_multicurrency;
4007 $this->line->multicurrency_code = $this->multicurrency_code;
4008 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
4010 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
4011 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
4012 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4014 if (is_array($array_options) && count($array_options) > 0) {
4015 $this->line->array_options = $array_options;
4018 $result = $this->line->insert();
4021 if (!empty($fk_parent_line)) {
4023 } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) {
4024 $linecount = count($this->lines);
4025 for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
4031 if (empty($noupdateafterinsertline)) {
4036 $this->db->commit();
4037 return $this->line->id;
4039 $this->error = $this->db->lasterror();
4040 $this->db->rollback();
4044 $this->error = $this->line->error;
4045 $this->errors = $this->line->errors;
4046 $this->db->rollback();
4050 $this->errors[] =
'status of invoice must be Draft to allow use of ->addline()';
4051 dol_syslog(get_class($this).
"::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
4087 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)
4089 global $conf, $user;
4092 dol_syslog(__METHOD__.
": using line label is deprecated", LOG_WARNING);
4095 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4097 global $mysoc, $langs;
4099 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);
4101 if ($this->
status == self::STATUS_DRAFT) {
4104 if (!$this->error) {
4105 $this->error = $langs->trans(
'invoiceLineProgressError');
4111 if ($date_start && $date_end && $date_start > $date_end) {
4112 $langs->load(
"errors");
4113 $this->error = $langs->trans(
'ErrorStartDateGreaterEnd');
4123 if (empty($fk_parent_line) || $fk_parent_line < 0) {
4124 $fk_parent_line = 0;
4126 if (empty($special_code) || $special_code == 3) {
4129 if (!isset($situation_percent) || $situation_percent > 100 || (
string) $situation_percent ==
'') {
4130 $situation_percent = 100;
4132 if (empty($ref_ext)) {
4136 $remise_percent = (float)
price2num($remise_percent);
4139 $pu_ht_devise =
price2num($pu_ht_devise);
4141 if (!preg_match(
'/\((.*)\)/', (
string) $txtva)) {
4144 $txlocaltax1 = (float)
price2num($txlocaltax1);
4145 $txlocaltax2 = (float)
price2num($txlocaltax2);
4161 if (preg_match(
'/\((.*)\)/', $txtva, $reg)) {
4162 $vat_src_code = $reg[1];
4163 $txtva = preg_replace(
'/\s*\(.*\)/',
'', $txtva);
4166 $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);
4168 $total_ht = $tabprice[0];
4169 $total_tva = $tabprice[1];
4170 $total_ttc = $tabprice[2];
4171 $total_localtax1 = $tabprice[9];
4172 $total_localtax2 = $tabprice[10];
4173 $pu_ht = $tabprice[3];
4174 $pu_tva = $tabprice[4];
4175 $pu_ttc = $tabprice[5];
4178 $multicurrency_total_ht = $tabprice[16];
4179 $multicurrency_total_tva = $tabprice[17];
4180 $multicurrency_total_ttc = $tabprice[18];
4181 $pu_ht_devise = $tabprice[19];
4186 if ($remise_percent > 0) {
4187 $remise = round(((
float) $pu * (
float) $remise_percent / 100), 2);
4188 $price = ((float) $pu - $remise);
4194 $line->fetch($rowid);
4195 $line->fetch_optionals();
4197 if (!empty($line->fk_product)) {
4198 $product =
new Product($this->db);
4199 $result = $product->fetch($line->fk_product);
4200 $product_type = $product->type;
4202 if (
getDolGlobalString(
'STOCK_MUST_BE_ENOUGH_FOR_INVOICE') && $product_type == 0 && $product->stock_reel < $qty) {
4203 $langs->load(
"errors");
4204 $this->error = $langs->trans(
'ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
4205 $this->db->rollback();
4210 $staticline = clone $line;
4212 $line->oldline = $staticline;
4213 $this->line = $line;
4214 $this->line->context = $this->context;
4215 $this->line->rang = $rang;
4218 if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
4219 $rangmax = $this->
line_max($fk_parent_line);
4220 $this->line->rang = $rangmax + 1;
4223 $this->line->id = $rowid;
4224 $this->line->rowid = $rowid;
4225 $this->line->label = $label;
4226 $this->line->desc = $desc;
4227 $this->line->ref_ext = $ref_ext;
4228 $this->line->qty = ($this->
type == self::TYPE_CREDIT_NOTE ? abs((
float) $qty) : $qty);
4230 $this->line->vat_src_code = $vat_src_code;
4231 $this->line->tva_tx = $txtva;
4232 $this->line->localtax1_tx = $txlocaltax1;
4233 $this->line->localtax2_tx = $txlocaltax2;
4234 $this->line->localtax1_type = empty($localtaxes_type[0]) ? 0 : $localtaxes_type[0];
4235 $this->line->localtax2_type = empty($localtaxes_type[2]) ? 0 : $localtaxes_type[2];
4237 $this->line->remise_percent = $remise_percent;
4238 $this->line->subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht) : $pu_ht);
4239 $this->line->date_start = $date_start;
4240 $this->line->date_end = $date_end;
4241 $this->line->total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ht) : $total_ht);
4242 $this->line->total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_tva) : $total_tva);
4243 $this->line->total_localtax1 = $total_localtax1;
4244 $this->line->total_localtax2 = $total_localtax2;
4245 $this->line->total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($total_ttc) : $total_ttc);
4246 $this->line->info_bits = $info_bits;
4247 $this->line->special_code = $special_code;
4248 $this->line->product_type = $type;
4249 $this->line->fk_parent_line = $fk_parent_line;
4250 $this->line->skip_update_total = $skip_update_total;
4251 $this->line->situation_percent = $situation_percent;
4252 $this->line->fk_unit = $fk_unit;
4254 $this->line->fk_fournprice = $fk_fournprice;
4255 $this->line->pa_ht = $pa_ht;
4258 $this->line->multicurrency_subprice = ($this->
type == self::TYPE_CREDIT_NOTE ? -abs($pu_ht_devise) : $pu_ht_devise);
4259 $this->line->multicurrency_total_ht = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ht) : $multicurrency_total_ht);
4260 $this->line->multicurrency_total_tva = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_tva) : $multicurrency_total_tva);
4261 $this->line->multicurrency_total_ttc = (($this->
type == self::TYPE_CREDIT_NOTE || $qty < 0) ? -abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
4263 if (is_array($array_options) && count($array_options) > 0) {
4265 foreach ($array_options as $key => $value) {
4266 $this->line->array_options[$key] = $array_options[$key];
4270 $result = $this->line->update($user, $notrigger);
4273 if (!empty($fk_parent_line)) {
4279 $this->db->commit();
4282 $this->error = $this->line->error;
4283 $this->db->rollback();
4287 $this->error =
"Invoice statut makes operation forbidden";
4301 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd
4302 INNER JOIN '.MAIN_DB_PREFIX.
'facture f ON (fd.fk_facture = f.rowid)
4303 WHERE fd.fk_prev_id = '.((int) $idline).
' AND f.fk_statut <> 0';
4305 $result = $this->db->query($sql);
4307 $this->error = $this->db->error();
4311 $obj = $this->db->fetch_object($result);
4313 if ($obj ===
null) {
4316 return ($situation_percent < $obj->situation_percent);
4332 global $mysoc, $user;
4335 if (($line->info_bits & 2) == 2) {
4339 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4342 if ($percent > 100) {
4346 $previous_progress = $line->get_allprev_progress($line->fk_facture);
4347 $current_progress = $percent - $previous_progress;
4348 $line->situation_percent = $current_progress;
4349 $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);
4351 $line->situation_percent = $percent;
4352 $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);
4354 $line->total_ht = $tabprice[0];
4355 $line->total_tva = $tabprice[1];
4356 $line->total_ttc = $tabprice[2];
4357 $line->total_localtax1 = $tabprice[9];
4358 $line->total_localtax2 = $tabprice[10];
4359 $line->multicurrency_total_ht = $tabprice[16];
4360 $line->multicurrency_total_tva = $tabprice[17];
4361 $line->multicurrency_total_ttc = $tabprice[18];
4362 $line->update($user);
4365 if ($update_price) {
4381 dol_syslog(get_class($this).
"::deleteline rowid=".((
int) $rowid), LOG_DEBUG);
4383 if ($this->
status != self::STATUS_DRAFT) {
4384 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
4390 $line->context = $this->context;
4393 $result = $line->fetch($rowid);
4394 if (!($result > 0)) {
4399 if ($id > 0 && $line->fk_facture != $id) {
4400 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
4407 $staticline = clone $line;
4408 $line->oldline = $staticline;
4410 if ($line->delete($user) > 0) {
4414 $this->db->commit();
4417 $this->db->rollback();
4418 $this->error = $this->db->lasterror();
4422 $this->db->rollback();
4423 $this->error = $line->error;
4442 dol_syslog(get_class($this).
"::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
4444 return $this->
setDiscount($user, $remise, $notrigger);
4458 if (empty($remise)) {
4462 if ($user->hasRight(
'facture',
'creer')) {
4463 $remise = (float)
price2num($remise, 2);
4469 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facture";
4470 $sql .=
" SET remise_percent = ".((float) $remise);
4471 $sql .=
" WHERE rowid = ".((int) $this->
id);
4472 $sql .=
" AND fk_statut = ".((int) self::STATUS_DRAFT);
4475 $resql = $this->db->query($sql);
4477 $this->errors[] = $this->db->error();
4481 if (!$notrigger && empty($error)) {
4491 $this->remise_percent = $remise;
4494 $this->db->commit();
4497 foreach ($this->errors as $errmsg) {
4498 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
4499 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
4501 $this->db->rollback();
4588 global $conf, $langs;
4590 if ($this->module_source ==
'takepos') {
4591 $langs->load(
'cashdesk');
4593 $moduleName =
'takepos';
4594 $moduleSourceName =
'Takepos';
4595 $addonConstName =
'TAKEPOS_REF_ADDON';
4599 $conf->global->TAKEPOS_REF_ADDON =
'mod_takepos_ref_simple';
4604 $langs->load(
'bills');
4606 $moduleName =
'facture';
4607 $moduleSourceName =
'Invoice';
4608 $addonConstName =
'FACTURE_ADDON';
4612 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4614 $conf->global->FACTURE_ADDON =
'mod_facture_terre';
4616 $conf->global->FACTURE_ADDON =
'mod_facture_mercure';
4622 if (!empty($addon)) {
4623 dol_syslog(
"Call getNextNumRef with ".$addonConstName.
" = " .
getDolGlobalString(
'FACTURE_ADDON').
", thirdparty=".$soc->name.
", type=".$soc->typent_code.
", mode=".$mode, LOG_DEBUG);
4627 $file = $addon.
'.php';
4628 $classname = $addon;
4632 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
4633 foreach ($dirmodels as $reldir) {
4634 $dir =
dol_buildpath($reldir.
'core/modules/'.$moduleName.
'/');
4637 if (is_file($dir.$file) && is_readable($dir.$file)) {
4638 $mybool = ((bool) include_once $dir.$file) || $mybool;
4644 $file = $addon.
'/'.$addon.
'.modules.php';
4645 $classname =
'mod_'.$moduleName.
'_'.$addon;
4646 $classname = preg_replace(
'/\-.*$/',
'', $classname);
4648 foreach ($conf->file->dol_document_root as $dirroot) {
4649 $dir = $dirroot.
'/core/modules/'.$moduleName.
'/';
4652 if (is_file($dir.$file) && is_readable($dir.$file)) {
4653 $mybool = (include_once $dir.$file) || $mybool;
4663 $obj =
new $classname();
4664 '@phan-var-force CommonNumRefGenerator $obj';
4666 $numref = $obj->getNextValue($soc, $this, $mode);
4673 if ($mode !=
'last' && !$numref) {
4674 $this->error = $obj->error;
4680 $langs->load(
'errors');
4681 print $langs->trans(
'Error').
' '.$langs->trans(
'ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
4694 $sql =
'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
4695 $sql .=
' date_closing as dateclosing,';
4696 $sql .=
' fk_user_author, fk_user_valid, fk_user_closing';
4697 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture as c';
4698 $sql .=
' WHERE c.rowid = '.((int) $id);
4700 $result = $this->db->query($sql);
4702 if ($this->db->num_rows($result)) {
4703 $obj = $this->db->fetch_object($result);
4705 $this->
id = $obj->rowid;
4706 $this->user_creation_id = $obj->fk_user_author;
4707 $this->user_validation_id = $obj->fk_user_valid;
4708 $this->user_closing_id = $obj->fk_user_closing;
4710 $this->date_creation = $this->db->jdate($obj->datec);
4711 $this->date_modification = $this->db->jdate($obj->datem);
4712 $this->date_validation = $this->db->jdate($obj->datev);
4713 $this->date_closing = $this->db->jdate($obj->dateclosing);
4715 $this->db->free($result);
4736 public function liste_array($shortlist = 0, $draft = 0, $excluser =
null, $socid = 0, $limit = 0, $offset = 0, $sortfield =
'f.datef,f.rowid', $sortorder =
'DESC')
4743 $sql =
"SELECT s.rowid, s.nom as name, s.client,";
4744 $sql .=
" f.rowid as fid, f.ref as ref, f.datef as df";
4745 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe as s, ".MAIN_DB_PREFIX.
"facture as f";
4746 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4747 $sql .=
" AND f.fk_soc = s.rowid";
4749 $sql .=
" AND f.fk_statut = ".self::STATUS_DRAFT;
4751 if (is_object($excluser)) {
4752 $sql .=
" AND f.fk_user_author <> ".((int) $excluser->id);
4756 if (!$user->hasRight(
'societe',
'client',
'voir')) {
4757 $search_sale = $user->id;
4760 if ($search_sale && $search_sale !=
'-1') {
4761 if ($search_sale == -2) {
4762 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
4763 } elseif ($search_sale > 0) {
4764 $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).
")";
4769 $sql .=
" AND f.fk_soc = ".((int) $socid);
4771 $sql .= $this->db->order($sortfield, $sortorder);
4772 $sql .= $this->db->plimit($limit, $offset);
4774 $result = $this->db->query($sql);
4776 $numc = $this->db->num_rows($result);
4779 while ($i < $numc) {
4780 $obj = $this->db->fetch_object($result);
4782 if ($shortlist == 1) {
4783 $ga[$obj->fid] = $obj->ref;
4784 } elseif ($shortlist == 2) {
4785 $ga[$obj->fid] = $obj->ref.
' ('.$obj->name.
')';
4787 $ga[$i][
'id'] = $obj->fid;
4788 $ga[$i][
'ref'] = $obj->ref;
4789 $ga[$i][
'name'] = $obj->name;
4818 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
4819 $sql .=
" ff.rowid as rowidnext";
4821 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4822 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4823 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON f.rowid = ff.fk_facture_source";
4824 $sql .=
" WHERE (f.fk_statut = ".self::STATUS_VALIDATED.
" OR (f.fk_statut = ".self::STATUS_ABANDONED.
" AND f.close_code = '".self::CLOSECODE_ABANDONED.
"'))";
4825 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4826 $sql .=
" AND f.paye = 0";
4827 $sql .=
" AND pf.fk_paiement IS NULL";
4828 $sql .=
" AND ff.fk_statut IS NULL";
4830 $sql .=
" AND f.fk_soc = ".((int) $socid);
4833 $sql .=
" ORDER BY f.ref";
4835 dol_syslog(get_class($this).
"::list_replacable_invoices", LOG_DEBUG);
4836 $resql = $this->db->query($sql);
4838 while ($obj = $this->db->fetch_object($resql)) {
4839 $return[$obj->rowid] = array(
4840 'id' => $obj->rowid,
4842 'status' => $obj->status,
4843 'paid' => $obj->paid,
4850 $this->error = $this->db->error();
4873 $sql =
"SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.subtype, f.paye, pf.fk_paiement";
4874 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4875 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"paiement_facture as pf ON f.rowid = pf.fk_facture";
4876 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.
")";
4877 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice').
")";
4878 $sql .=
" AND f.fk_statut in (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4882 $sql .=
" AND ff.type IS NULL";
4883 $sql .=
" AND f.type <> ".self::TYPE_CREDIT_NOTE;
4887 $sql .=
" AND (f.type <> ".self::TYPE_SITUATION.
" OR f.rowid IN ";
4888 $sql .=
'(SELECT MAX(fs.rowid)';
4889 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as fs";
4890 $sql .=
" WHERE fs.entity IN (".getEntity(
'invoice').
")";
4891 $sql .=
" AND fs.type = ".self::TYPE_SITUATION;
4892 $sql .=
" AND fs.fk_statut IN (".self::STATUS_VALIDATED.
",".self::STATUS_CLOSED.
")";
4894 $sql .=
" AND fs.fk_soc = ".((int) $socid);
4896 $sql .=
" GROUP BY fs.situation_cycle_ref)";
4899 $sql .=
" AND f.type <> ".self::TYPE_SITUATION;
4903 $sql .=
" AND f.fk_soc = ".((int) $socid);
4905 $sql .=
" ORDER BY f.ref";
4907 dol_syslog(get_class($this).
"::list_qualified_avoir_invoices", LOG_DEBUG);
4908 $resql = $this->db->query($sql);
4910 while ($obj = $this->db->fetch_object($resql)) {
4912 if ($obj->fk_statut == self::STATUS_VALIDATED) {
4915 if ($obj->fk_statut == self::STATUS_CLOSED) {
4920 $paymentornot = ($obj->fk_paiement ? 1 : 0);
4921 $return[$obj->rowid] = array(
'ref' => $obj->ref,
'status' => $obj->fk_statut,
'type' => $obj->type,
'paye' => $obj->paye,
'paymentornot' => $paymentornot);
4927 $this->error = $this->db->error();
4943 global $conf, $langs;
4947 $sql =
"SELECT f.rowid, f.date_lim_reglement as datefin, f.fk_statut as status, f.total_ht";
4948 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
4949 if (!$user->hasRight(
'societe',
'client',
'voir')) {
4950 $sql .=
" JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
4951 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
4954 $sql .= $clause.
" f.paye=0";
4955 $sql .=
" AND f.entity IN (".getEntity(
'invoice').
")";
4956 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
4958 $sql .=
" AND f.fk_soc = ".((int) $user->socid);
4961 $resql = $this->db->query($sql);
4963 $langs->load(
"bills");
4967 $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
4968 $response->label = $langs->trans(
"CustomerBillsUnpaid");
4969 $response->labelShort = $langs->trans(
"Unpaid");
4970 $response->url = DOL_URL_ROOT.
'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
4973 $generic_facture =
new Facture($this->db);
4975 while ($obj = $this->db->fetch_object($resql)) {
4976 $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
4977 $generic_facture->statut = $obj->status;
4978 $generic_facture->status = $obj->status;
4980 $response->nbtodo++;
4981 $response->total += $obj->total_ht;
4983 if ($generic_facture->hasDelay()) {
4984 $response->nbtodolate++;
4985 $response->url_late = DOL_URL_ROOT.
'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
4989 $this->db->free($resql);
4993 $this->error = $this->db->error();
5032 global $conf, $langs, $user;
5036 $nownotime =
dol_mktime(0, 0, 0, $arraynow[
'mon'], $arraynow[
'mday'], $arraynow[
'year']);
5041 $sql =
"SELECT rowid";
5042 $sql .=
" FROM ".MAIN_DB_PREFIX.
"product";
5043 $sql .=
" WHERE entity IN (".getEntity(
'product').
")";
5044 $sql .= $this->db->plimit(100);
5046 $resql = $this->db->query($sql);
5048 $num_prods = $this->db->num_rows($resql);
5050 while ($i < $num_prods) {
5052 $row = $this->db->fetch_row($resql);
5053 $prodids[$i] = $row[0];
5057 if (empty($num_prods)) {
5064 $this->
ref =
'SPECIMEN';
5065 $this->specimen = 1;
5067 $this->date = $nownotime;
5068 $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
5069 $this->cond_reglement_id = 1;
5070 $this->cond_reglement_code =
'RECEP';
5072 $this->mode_reglement_id = 0;
5073 $this->mode_reglement_code =
'';
5075 $this->note_public =
'This is a comment (public)';
5076 $this->note_private =
'This is a comment (private)';
5077 $this->note =
'This is a comment (private)';
5079 $this->fk_user_author = $user->id;
5081 $this->multicurrency_tx = 1;
5082 $this->multicurrency_code = $conf->currency;
5084 $this->fk_incoterms = 0;
5085 $this->location_incoterms =
'';
5087 if (empty($option) || $option !=
'nolines') {
5091 while ($xnbp < $nbp) {
5093 $line->desc = $langs->trans(
"Description").
" ".$xnbp;
5095 $line->subprice = 100;
5096 $line->tva_tx = 19.6;
5097 $line->localtax1_tx = 0;
5098 $line->localtax2_tx = 0;
5099 $line->remise_percent = 0;
5101 $prodid = mt_rand(1, $num_prods);
5102 $line->fk_product = $prodids[$prodid];
5104 $line->total_ht = -100;
5105 $line->total_ttc = -119.6;
5106 $line->total_tva = -19.6;
5107 $line->multicurrency_total_ht = -200;
5108 $line->multicurrency_total_ttc = -239.2;
5109 $line->multicurrency_total_tva = -39.2;
5110 } elseif ($xnbp == 2) {
5111 $line->subprice = -100;
5112 $line->total_ht = -100;
5113 $line->total_ttc = -119.6;
5114 $line->total_tva = -19.6;
5115 $line->remise_percent = 0;
5116 $line->multicurrency_total_ht = -200;
5117 $line->multicurrency_total_ttc = -239.2;
5118 $line->multicurrency_total_tva = -39.2;
5119 } elseif ($xnbp == 3) {
5120 $prodid = mt_rand(1, $num_prods);
5121 $line->fk_product = $prodids[$prodid];
5122 $line->total_ht = 50;
5123 $line->total_ttc = 59.8;
5124 $line->total_tva = 9.8;
5125 $line->multicurrency_total_ht = 100;
5126 $line->multicurrency_total_ttc = 119.6;
5127 $line->multicurrency_total_tva = 19.6;
5128 $line->remise_percent = 50;
5130 $prodid = mt_rand(1, $num_prods);
5131 $line->fk_product = $prodids[$prodid];
5132 $line->total_ht = 100;
5133 $line->total_ttc = 119.6;
5134 $line->total_tva = 19.6;
5135 $line->multicurrency_total_ht = 200;
5136 $line->multicurrency_total_ttc = 239.2;
5137 $line->multicurrency_total_tva = 39.2;
5138 $line->remise_percent = 0;
5141 $this->lines[$xnbp] = $line;
5144 $this->total_ht += $line->total_ht;
5145 $this->total_tva += $line->total_tva;
5146 $this->total_ttc += $line->total_ttc;
5148 $this->multicurrency_total_ht += $line->multicurrency_total_ht;
5149 $this->multicurrency_total_tva += $line->multicurrency_total_tva;
5150 $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
5154 $this->revenuestamp = 0;
5158 $line->desc = $langs->trans(
"Description").
" (offered line)";
5160 $line->subprice = 100;
5161 $line->tva_tx = 19.6;
5162 $line->localtax1_tx = 0;
5163 $line->localtax2_tx = 0;
5164 $line->remise_percent = 100;
5165 $line->total_ht = 0;
5166 $line->total_ttc = 0;
5167 $line->total_tva = 0;
5168 $line->multicurrency_total_ht = 0;
5169 $line->multicurrency_total_ttc = 0;
5170 $line->multicurrency_total_tva = 0;
5171 $prodid = mt_rand(1, $num_prods);
5172 $line->fk_product = $prodids[$prodid];
5174 $this->lines[$xnbp] = $line;
5188 global $conf, $user;
5190 $this->nb = array();
5194 $sql =
"SELECT count(f.rowid) as nb";
5195 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5196 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe as s ON f.fk_soc = s.rowid";
5197 if (!$user->hasRight(
'societe',
'client',
'voir')) {
5198 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"societe_commerciaux as sc ON s.rowid = sc.fk_soc";
5199 $sql .=
" WHERE sc.fk_user = ".((int) $user->id);
5202 $sql .=
" ".$clause.
" f.entity IN (".
getEntity(
'invoice').
")";
5204 $resql = $this->db->query($sql);
5206 while ($obj = $this->db->fetch_object($resql)) {
5207 $this->nb[
"invoices"] = $obj->nb;
5209 $this->db->free($resql);
5213 $this->error = $this->db->error();
5239 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
5241 global $conf, $langs;
5243 $outputlangs->loadLangs(array(
"bills",
"products"));
5247 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$this->type;
5249 if (!empty($this->model_pdf)) {
5250 $modele = $this->model_pdf;
5258 $modelpath =
"core/modules/facture/doc/";
5260 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
5270 $sql =
"SELECT max(situation_cycle_ref) as maxsituationref";
5271 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture as f";
5272 $sql .=
" WHERE f.entity IN (".getEntity(
'invoice', 0).
")";
5274 $resql = $this->db->query($sql);
5276 if ($this->db->num_rows($resql) > 0) {
5278 $obj = $this->db->fetch_object($resql);
5280 $ref = $obj->maxsituationref;
5286 $this->db->free($resql);
5289 $this->error = $this->db->lasterror();
5290 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5304 return ($this->situation_counter == 1);
5318 $sql =
'SELECT rowid FROM '.MAIN_DB_PREFIX.
'facture';
5319 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5320 $sql .=
' AND situation_counter < '.((int) $this->situation_counter);
5321 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5322 $resql = $this->db->query($sql);
5324 if ($resql && $this->db->num_rows($resql) > 0) {
5325 while ($row = $this->db->fetch_object($resql)) {
5327 $situation =
new Facture($this->db);
5328 $situation->fetch($id);
5329 $res[] = $situation;
5332 $this->error = $this->db->error();
5333 dol_syslog(
"Error sql=".$sql.
", error=".$this->error, LOG_ERR);
5353 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture SET situation_final = '.((int) $this->situation_final).
' WHERE rowid = '.((int) $this->
id);
5356 $resql = $this->db->query($sql);
5358 $this->errors[] = $this->db->error();
5362 if (!$notrigger && empty($error)) {
5372 $this->db->commit();
5375 foreach ($this->errors as $errmsg) {
5376 dol_syslog(__METHOD__.
' Error: '.$errmsg, LOG_ERR);
5377 $this->error .= ($this->error ?
', '.$errmsg : $errmsg);
5379 $this->db->rollback();
5395 if (!empty($this->situation_cycle_ref)) {
5397 $sql =
'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.
'facture';
5398 $sql .=
' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
5399 $sql .=
' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
5400 $resql = $this->db->query($sql);
5402 if ($resql && $this->db->num_rows($resql) > 0 && $res = $this->db->fetch_array($resql)) {
5403 $last = $res[
'max(situation_counter)'];
5404 return ($last == $this->situation_counter);
5406 $this->error = $this->db->lasterror();
5407 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
5465 $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
5466 if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
5468 $totalpaid = (float) $totalpaid;
5470 if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) {
5471 if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
5473 } elseif ($totalpaid < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
5496 $displayWarranty =
false;
5497 if (!empty($this->retained_warranty)) {
5498 $displayWarranty =
true;
5502 $displayWarranty =
false;
5503 if (!empty($this->situation_final)) {
5504 $displayWarranty =
true;
5507 $displayWarranty =
true;
5509 foreach ($this->lines as $i => $line) {
5510 if ($line->product_type < 2 && $line->situation_percent < 100) {
5511 $displayWarranty =
false;
5519 return $displayWarranty;
5529 if (empty($this->retained_warranty)) {
5533 $retainedWarrantyAmount = 0;
5537 $displayWarranty =
true;
5539 if (!empty($this->lines)) {
5540 foreach ($this->lines as $i => $line) {
5541 if ($line->product_type < 2 && $line->situation_percent < 100) {
5542 $displayWarranty =
false;
5548 if ($displayWarranty && !empty($this->situation_final)) {
5550 $TPreviousIncoice = $this->tab_previous_situation_invoice;
5553 foreach ($TPreviousIncoice as &$fac) {
5554 $total2BillWT += $fac->total_ttc;
5556 $total2BillWT += $this->total_ttc;
5558 $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
5564 $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
5567 if ($rounding < 0) {
5571 if ($rounding > 0) {
5572 return round($retainedWarrantyAmount, $rounding);
5575 return $retainedWarrantyAmount;
5586 dol_syslog(get_class($this).
'::setRetainedWarranty('.$value.
')');
5588 if ($this->
status >= 0) {
5589 $fieldname =
'retained_warranty';
5590 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5591 $sql .=
" SET ".$fieldname.
" = ".((float) $value);
5592 $sql .=
' WHERE rowid='.((int) $this->
id);
5594 if ($this->db->query($sql)) {
5595 $this->retained_warranty = (float) $value;
5598 dol_syslog(get_class($this).
'::setRetainedWarranty Erreur '.$sql.
' - '.$this->db->error());
5599 $this->error = $this->db->error();
5603 dol_syslog(get_class($this).
'::setRetainedWarranty, status of the object is incompatible');
5604 $this->error =
'Status of the object is incompatible '.$this->status;
5619 if (!$timestamp && $dateYmd) {
5620 $timestamp = $this->db->jdate($dateYmd);
5624 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit('.$timestamp.
')');
5625 if ($this->
status >= 0) {
5626 $fieldname =
'retained_warranty_date_limit';
5627 $sql =
'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
5628 $sql .=
" SET ".$fieldname.
" = ".(strval($timestamp) !=
'' ?
"'".$this->db->idate($timestamp).
"'" :
'null');
5629 $sql .=
' WHERE rowid = '.((int) $this->
id);
5631 if ($this->db->query($sql)) {
5632 $this->retained_warranty_date_limit = $timestamp;
5635 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit Erreur '.$sql.
' - '.$this->db->error());
5636 $this->error = $this->db->error();
5640 dol_syslog(get_class($this).
'::setRetainedWarrantyDateLimit, status of the object is incompatible');
5641 $this->error =
'Status of the object is incompatible '.$this->status;
5660 global $conf, $langs, $user;
5666 $errorsMsg = array();
5668 $langs->load(
"bills");
5670 if (!isModEnabled(
'invoice')) {
5671 $this->output .= $langs->trans(
'ModuleNotEnabled', $langs->transnoentitiesnoconv(
"Facture"));
5674 if (!in_array($datetouse, array(
'duedate',
'invoicedate'))) {
5675 $this->output .=
'Bad value for parameter datetouse. Must be "duedate" or "invoicedate"';
5685 require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
5686 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmail.class.php';
5687 require_once DOL_DOCUMENT_ROOT.
'/core/class/CMailFile.class.php';
5688 $formmail =
new FormMail($this->db);
5693 $tmpinvoice =
new Facture($this->db);
5698 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"facture as f";
5699 if (!empty($paymentmode) && $paymentmode !=
'all') {
5700 $sql .=
", ".MAIN_DB_PREFIX.
"c_paiement as cp";
5702 $sql .=
" WHERE f.paye = 0";
5703 $sql .=
" AND f.fk_statut = ".self::STATUS_VALIDATED;
5704 if ($datetouse ==
'invoicedate') {
5705 $sql .=
" AND f.datef = '".$this->db->idate($tmpidate,
'gmt').
"'";
5707 $sql .=
" AND f.date_lim_reglement = '".$this->db->idate($tmpidate,
'gmt').
"'";
5709 $sql .=
" AND f.entity IN (".getEntity(
'facture', 0).
")";
5710 if (!empty($paymentmode) && $paymentmode !=
'all') {
5711 $sql .=
" AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode).
"'";
5714 if ($datetouse ==
'invoicedate') {
5715 $sql .= $this->db->order(
"datef",
"ASC");
5717 $sql .= $this->db->order(
"date_lim_reglement",
"ASC");
5720 $resql = $this->db->query($sql);
5723 if ($datetouse ==
'invoicedate') {
5724 $this->output .= $langs->transnoentitiesnoconv(
"SearchValidatedInvoicesWithDate", $stmpidate);
5726 $this->output .= $langs->transnoentitiesnoconv(
"SearchUnpaidInvoicesWithDueDate", $stmpidate);
5728 if (!empty($paymentmode) && $paymentmode !=
'all') {
5729 $this->output .=
' ('.$langs->transnoentitiesnoconv(
"PaymentMode").
' '.$paymentmode.
')';
5731 $this->output .=
'<br>';
5734 while ($obj = $this->db->fetch_object($resql)) {
5737 $res = $tmpinvoice->fetch($obj->id);
5739 $tmpinvoice->fetch_thirdparty();
5741 $outputlangs =
new Translate(
'', $conf);
5742 if ($tmpinvoice->thirdparty->default_lang) {
5743 $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
5744 $outputlangs->loadLangs(array(
"main",
"bills"));
5746 $outputlangs = $langs;
5750 $arraymessage = $formmail->getEMailTemplate($this->db,
'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ?
'' : $template));
5751 if (is_numeric($arraymessage) && $arraymessage <= 0) {
5752 $langs->load(
"errors");
5753 $this->output .= $langs->trans(
'ErrorFailedToFindEmailTemplate', $template);
5766 $sendTopic =
make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv(
'InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
5769 $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
5775 if ($forcerecipient) {
5776 $to = array($forcerecipient);
5778 $res = $tmpinvoice->fetch_thirdparty();
5779 $recipient = $tmpinvoice->thirdparty;
5781 $tmparraycontact = $tmpinvoice->liste_contact(-1,
'external', 0,
'BILLING');
5782 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
5783 foreach ($tmparraycontact as $data_email) {
5784 if (!empty($data_email[
'email'])) {
5785 $to[] = $tmpinvoice->thirdparty->contact_get_property($data_email[
'id'],
'email');
5789 if (empty($to) && !empty($recipient->email)) {
5790 $to[] = $recipient->email;
5793 $errormesg =
"Failed to send remind to thirdparty id=".$tmpinvoice->socid.
". No email defined for invoice or customer.";
5797 $errormesg =
"Failed to load recipient with thirdparty id=".$tmpinvoice->socid;
5804 if (!empty($arraymessage->email_from)) {
5805 $from = $arraymessage->email_from;
5808 $errormesg =
"Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
5812 if (!$error && !empty($to)) {
5815 $to = implode(
',', $to);
5816 if (!empty($arraymessage->email_to)) {
5817 $to = $to.
','.$arraymessage->email_to;
5823 $trackid =
'inv'.$tmpinvoice->id;
5824 $sendcontext =
'standard';
5827 if (!empty($arraymessage->email_tocc)) {
5828 $email_tocc = $arraymessage->email_tocc;
5832 if (!empty($arraymessage->email_tobcc)) {
5833 $email_tobcc = $arraymessage->email_tobcc;
5840 if ($arraymessage->joinfiles == 1 && !empty($tmpinvoice->last_main_doc)) {
5841 $joinFile[] = DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc;
5842 $joinFileName[] = basename($tmpinvoice->last_main_doc);
5843 $joinFileMime[] =
dol_mimetype(DOL_DATA_ROOT.
'/'.$tmpinvoice->last_main_doc);
5847 $cMailFile =
new CMailFile($sendTopic, $to, $from, $sendContent, $joinFile, $joinFileMime, $joinFileName, $email_tocc, $email_tobcc, 0, 1, $errors_to,
'', $trackid,
'', $sendcontext,
'');
5850 if ($cMailFile->sendfile()) {
5854 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5859 $actioncomm->type_code =
'AC_OTH_AUTO';
5860 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5861 $actioncomm->contact_id = 0;
5863 $actioncomm->code =
'AC_EMAIL';
5864 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateOK (nbdays='.$nbdays.
' paymentmode='.$paymentmode.
' template='.$template.
' datetouse='.$datetouse.
' forcerecipient='.$forcerecipient.
')';
5865 $actioncomm->note_private = $sendContent;
5866 $actioncomm->fk_project = $tmpinvoice->fk_project;
5867 $actioncomm->datep =
dol_now();
5868 $actioncomm->datef = $actioncomm->datep;
5869 $actioncomm->percentage = -1;
5870 $actioncomm->authorid = $user->id;
5871 $actioncomm->userownerid = $user->id;
5873 $actioncomm->email_msgid = $cMailFile->msgid;
5874 $actioncomm->email_subject = $sendTopic;
5875 $actioncomm->email_from = $from;
5876 $actioncomm->email_sender =
'';
5877 $actioncomm->email_to = $to;
5881 $actioncomm->errors_to = $errors_to;
5883 $actioncomm->elementtype =
'invoice';
5884 $actioncomm->fk_element = $tmpinvoice->id;
5888 $actioncomm->create($user);
5890 $errormesg = $cMailFile->error.
' : '.$to;
5894 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
5899 $actioncomm->type_code =
'AC_OTH_AUTO';
5900 $actioncomm->socid = $tmpinvoice->thirdparty->id;
5901 $actioncomm->contact_id = 0;
5903 $actioncomm->code =
'AC_EMAIL';
5904 $actioncomm->label =
'sendEmailsRemindersOnInvoiceDueDateKO';
5905 $actioncomm->note_private = $errormesg;
5906 $actioncomm->fk_project = $tmpinvoice->fk_project;
5907 $actioncomm->datep =
dol_now();
5908 $actioncomm->datef = $actioncomm->datep;
5909 $actioncomm->percentage = -1;
5910 $actioncomm->authorid = $user->id;
5911 $actioncomm->userownerid = $user->id;
5913 $actioncomm->email_msgid = $cMailFile->msgid;
5914 $actioncomm->email_from = $from;
5915 $actioncomm->email_sender =
'';
5916 $actioncomm->email_to = $to;
5920 $actioncomm->errors_to = $errors_to;
5924 $actioncomm->create($user);
5927 $this->db->commit();
5931 $errorsMsg[] = $errormesg;
5934 $errorsMsg[] =
'Failed to fetch record invoice with ID = '.$obj->id;
5944 $this->output .=
'Nb of emails sent : '.$nbMailSend;
5946 dol_syslog(__METHOD__.
" end - ".$this->output, LOG_INFO);
5950 $this->error =
'Nb of emails sent : '.$nbMailSend.
', '.(!empty($errorsMsg) ? implode(
', ', $errorsMsg) : $error);
5952 dol_syslog(__METHOD__.
" end - ".$this->error, LOG_INFO);
5967 $sql =
"SELECT datef";
5968 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture";
5969 $sql .=
" WHERE type = " . (int) $this->
type ;
5970 $sql .=
" AND date_valid IS NOT NULL";
5971 $sql .=
" AND entity IN (".getEntity(
'invoice').
")";
5972 $sql .=
" ORDER BY datef DESC LIMIT 1";
5974 $result = $this->db->query($sql);
5977 if ($this->db->num_rows($result)) {
5978 $obj = $this->db->fetch_object($result);
5979 $last_date = $this->db->jdate($obj->datef);
5980 $invoice_date = $this->date;
5982 $is_last_of_same_type = $invoice_date >= $last_date;
5983 if ($allow_validated_drafts) {
5987 return array($is_last_of_same_type, $last_date);
6010 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
6012 $picto = $this->picto;
6013 if ($this->
type == self::TYPE_REPLACEMENT) {
6016 if ($this->
type == self::TYPE_CREDIT_NOTE) {
6019 if ($this->
type == self::TYPE_DEPOSIT) {
6023 $return =
'<div class="box-flex-item box-flex-grow-zero">';
6024 $return .=
'<div class="info-box info-box-sm">';
6025 $return .=
'<span class="info-box-icon bg-infobox-action">';
6027 $return .=
'</span>';
6028 $return .=
'<div class="info-box-content">';
6029 $return .=
'<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this,
'getNomUrl') ? $this->
getNomUrl(1) : $this->ref).
'</span>';
6030 if ($selected >= 0) {
6031 $return .=
'<input id="cb'.$this->id.
'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->
id.
'"'.($selected ?
' checked="checked"' :
'').
'>';
6033 if (!empty($arraydata[
'thirdparty'])) {
6034 $return .=
'<br><span class="info-box-label">'.$arraydata[
'thirdparty'].
'</span>';
6036 if (property_exists($this,
'date')) {
6037 $return .=
'<br><span class="info-box-label">'.dol_print_date($this->date,
'day').
'</span>';
6039 if (property_exists($this,
'total_ht')) {
6040 $return .=
' <span class="info-box-label amount" title="'.dol_escape_htmltag($langs->trans(
"AmountHT")).
'">'.
price($this->total_ht);
6041 $return .=
' '.$langs->trans(
"HT");
6042 $return .=
'</span>';
6044 if (method_exists($this,
'getLibStatut')) {
6045 $alreadypaid = (empty($arraydata[
'alreadypaid']) ? 0 : $arraydata[
'alreadypaid']);
6046 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3, $alreadypaid).
'</div>';
6048 $return .=
'</div>';
6049 $return .=
'</div>';
6050 $return .=
'</div>';
6064 public $element =
'facturedet';
6069 public $table_element =
'facturedet';
6086 public $localtax1_type;
6087 public $localtax2_type;
6088 public $fk_remise_except;
6091 public $fk_fournprice;
6101 public $remise_percent;
6110 public $fk_warehouse;
6119 public $fk_code_ventilation = 0;
6125 public $skip_update_total;
6130 public $situation_percent;
6156 $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,';
6157 $sql .=
' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
6158 $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,';
6159 $sql .=
' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
6160 $sql .=
' fd.fk_code_ventilation,';
6161 $sql .=
' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
6162 $sql .=
' fd.situation_percent, fd.fk_prev_id,';
6163 $sql .=
' fd.multicurrency_subprice,';
6164 $sql .=
' fd.multicurrency_total_ht,';
6165 $sql .=
' fd.multicurrency_total_tva,';
6166 $sql .=
' fd.multicurrency_total_ttc,';
6167 $sql .=
' p.ref as product_ref, p.label as product_label, p.description as product_desc';
6168 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facturedet as fd';
6169 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'product as p ON fd.fk_product = p.rowid';
6170 $sql .=
' WHERE fd.rowid = '.((int) $rowid);
6172 $result = $this->db->query($sql);
6174 $objp = $this->db->fetch_object($result);
6177 $this->error =
'InvoiceLine with id '. $rowid .
' not found sql='.$sql;
6181 $this->
rowid = $objp->rowid;
6182 $this->
id = $objp->rowid;
6183 $this->fk_facture = $objp->fk_facture;
6184 $this->fk_parent_line = $objp->fk_parent_line;
6185 $this->label = $objp->custom_label;
6186 $this->desc = $objp->description;
6187 $this->qty = $objp->qty;
6188 $this->subprice = $objp->subprice;
6189 $this->ref_ext = $objp->ref_ext;
6190 $this->vat_src_code = $objp->vat_src_code;
6191 $this->tva_tx = $objp->tva_tx;
6192 $this->localtax1_tx = $objp->localtax1_tx;
6193 $this->localtax2_tx = $objp->localtax2_tx;
6194 $this->remise_percent = $objp->remise_percent;
6195 $this->fk_remise_except = $objp->fk_remise_except;
6196 $this->fk_product = $objp->fk_product;
6197 $this->product_type = $objp->product_type;
6198 $this->date_start = $this->db->jdate($objp->date_start);
6199 $this->date_end = $this->db->jdate($objp->date_end);
6200 $this->info_bits = $objp->info_bits;
6201 $this->tva_npr = (($objp->info_bits & 1) == 1) ? 1 : 0;
6202 $this->special_code = $objp->special_code;
6203 $this->total_ht = $objp->total_ht;
6204 $this->total_tva = $objp->total_tva;
6205 $this->total_localtax1 = $objp->total_localtax1;
6206 $this->total_localtax2 = $objp->total_localtax2;
6207 $this->total_ttc = $objp->total_ttc;
6208 $this->fk_code_ventilation = $objp->fk_code_ventilation;
6209 $this->rang = $objp->rang;
6210 $this->fk_fournprice = $objp->fk_fournprice;
6211 $marginInfos =
getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
6212 $this->pa_ht = $marginInfos[0];
6213 $this->marge_tx = $marginInfos[1];
6214 $this->marque_tx = $marginInfos[2];
6216 $this->
ref = $objp->product_ref;
6218 $this->product_ref = $objp->product_ref;
6219 $this->product_label = $objp->product_label;
6220 $this->product_desc = $objp->product_desc;
6222 $this->fk_unit = $objp->fk_unit;
6223 $this->fk_user_modif = $objp->fk_user_modif;
6224 $this->fk_user_author = $objp->fk_user_author;
6226 $this->situation_percent = $objp->situation_percent;
6227 $this->fk_prev_id = $objp->fk_prev_id;
6229 $this->multicurrency_subprice = $objp->multicurrency_subprice;
6230 $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
6231 $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
6232 $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
6236 $this->db->free($result);
6240 $this->error = $this->db->lasterror();
6252 public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
6254 global $langs, $user;
6258 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6260 dol_syslog(get_class($this).
"::insert rang=".$this->rang, LOG_DEBUG);
6263 $this->desc = trim($this->desc);
6264 if (empty($this->tva_tx)) {
6267 if (empty($this->localtax1_tx)) {
6268 $this->localtax1_tx = 0;
6270 if (empty($this->localtax2_tx)) {
6271 $this->localtax2_tx = 0;
6273 if (empty($this->localtax1_type)) {
6274 $this->localtax1_type = 0;
6276 if (empty($this->localtax2_type)) {
6277 $this->localtax2_type = 0;
6279 if (empty($this->total_localtax1)) {
6280 $this->total_localtax1 = 0;
6282 if (empty($this->total_localtax2)) {
6283 $this->total_localtax2 = 0;
6285 if (empty($this->rang)) {
6288 if (empty($this->remise_percent)) {
6289 $this->remise_percent = 0;
6291 if (empty($this->info_bits)) {
6292 $this->info_bits = 0;
6294 if (empty($this->subprice)) {
6295 $this->subprice = 0;
6297 if (empty($this->ref_ext)) {
6298 $this->ref_ext =
'';
6300 if (empty($this->special_code)) {
6301 $this->special_code = 0;
6303 if (empty($this->fk_parent_line)) {
6304 $this->fk_parent_line = 0;
6306 if (empty($this->fk_prev_id)) {
6307 $this->fk_prev_id = 0;
6309 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6310 $this->situation_percent = 100;
6313 if (empty($this->pa_ht)) {
6316 if (empty($this->multicurrency_subprice)) {
6317 $this->multicurrency_subprice = 0;
6319 if (empty($this->multicurrency_total_ht)) {
6320 $this->multicurrency_total_ht = 0;
6322 if (empty($this->multicurrency_total_tva)) {
6323 $this->multicurrency_total_tva = 0;
6325 if (empty($this->multicurrency_total_ttc)) {
6326 $this->multicurrency_total_ttc = 0;
6330 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6331 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6335 $this->pa_ht = $result;
6340 if ($this->product_type < 0) {
6341 $this->error =
'ErrorProductTypeMustBe0orMore';
6344 if (!empty($this->fk_product) && $this->fk_product > 0) {
6348 $this->error =
'ErrorProductIdDoesNotExists';
6349 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6357 $sql =
'INSERT INTO '.MAIN_DB_PREFIX.
'facturedet';
6358 $sql .=
' (fk_facture, fk_parent_line, label, description, qty,';
6359 $sql .=
' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
6360 $sql .=
' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
6361 $sql .=
' date_start, date_end, fk_code_ventilation,';
6362 $sql .=
' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
6363 $sql .=
' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
6364 $sql .=
' situation_percent, fk_prev_id,';
6365 $sql .=
' fk_unit, fk_user_author, fk_user_modif,';
6366 $sql .=
' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc,';
6367 $sql .=
' batch, fk_warehouse';
6369 $sql .=
" VALUES (".$this->fk_facture.
",";
6370 $sql .=
" ".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null").
",";
6371 $sql .=
" ".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null").
",";
6372 $sql .=
" '".$this->db->escape($this->desc).
"',";
6373 $sql .=
" ".price2num($this->qty).
",";
6374 $sql .=
" ".(empty($this->vat_src_code) ?
"''" :
"'".$this->db->escape($this->vat_src_code).
"'").
",";
6375 $sql .=
" ".price2num($this->tva_tx).
",";
6376 $sql .=
" ".price2num($this->localtax1_tx).
",";
6377 $sql .=
" ".price2num($this->localtax2_tx).
",";
6378 $sql .=
" '".$this->db->escape($this->localtax1_type).
"',";
6379 $sql .=
" '".$this->db->escape($this->localtax2_type).
"',";
6380 $sql .=
' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product :
"null").
',';
6381 $sql .=
" ".((int) $this->product_type).
",";
6382 $sql .=
" ".price2num($this->remise_percent).
",";
6383 $sql .=
" ".price2num($this->subprice).
",";
6384 $sql .=
" '".$this->db->escape($this->ref_ext).
"',";
6385 $sql .=
' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except :
"null").
',';
6386 $sql .=
" ".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null").
",";
6387 $sql .=
" ".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null").
",";
6388 $sql .=
' '.((int) $this->fk_code_ventilation).
',';
6389 $sql .=
' '.((int) $this->rang).
',';
6390 $sql .=
' '.((int) $this->special_code).
',';
6391 $sql .=
' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice :
"null").
',';
6392 $sql .=
' '.price2num($this->pa_ht).
',';
6393 $sql .=
" '".$this->db->escape($this->info_bits).
"',";
6394 $sql .=
" ".price2num($this->total_ht).
",";
6395 $sql .=
" ".price2num($this->total_tva).
",";
6396 $sql .=
" ".price2num($this->total_ttc).
",";
6397 $sql .=
" ".price2num($this->total_localtax1).
",";
6398 $sql .=
" ".price2num($this->total_localtax2);
6399 $sql .=
", ".((float) $this->situation_percent);
6400 $sql .=
", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id :
"null");
6401 $sql .=
", ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6402 $sql .=
", ".((int) $user->id);
6403 $sql .=
", ".((int) $user->id);
6404 $sql .=
", ".(int) $this->fk_multicurrency;
6405 $sql .=
", '".$this->db->escape($this->multicurrency_code).
"'";
6406 $sql .=
", ".price2num($this->multicurrency_subprice);
6407 $sql .=
", ".price2num($this->multicurrency_total_ht);
6408 $sql .=
", ".price2num($this->multicurrency_total_tva);
6409 $sql .=
", ".price2num($this->multicurrency_total_ttc);
6410 $sql .=
", '".$this->db->escape($this->batch).
"'";
6411 $sql .=
", ".((int) $this->fk_warehouse);
6414 dol_syslog(get_class($this).
"::insert", LOG_DEBUG);
6415 $resql = $this->db->query($sql);
6417 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.
'facturedet');
6418 $this->
rowid = $this->id;
6429 if ($this->fk_remise_except) {
6431 $result = $discount->fetch($this->fk_remise_except);
6436 if ($discount->fk_facture_line > 0) {
6437 if (empty($noerrorifdiscountalreadylinked)) {
6438 $this->error = $langs->trans(
"ErrorDiscountAlreadyUsed", $discount->id);
6439 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6440 $this->db->rollback();
6444 $result = $discount->link_to_invoice($this->
rowid, 0);
6446 $this->error = $discount->error;
6447 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6448 $this->db->rollback();
6453 $this->error = $langs->trans(
"ErrorADiscountThatHasBeenRemovedIsIncluded");
6454 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6455 $this->db->rollback();
6459 $this->error = $discount->error;
6460 dol_syslog(get_class($this).
"::insert Error ".$this->error, LOG_ERR);
6461 $this->db->rollback();
6468 $result = $this->
call_trigger(
'LINEBILL_INSERT', $user);
6470 $this->db->rollback();
6476 $this->db->commit();
6479 $this->error = $this->db->lasterror();
6480 $this->db->rollback();
6492 public function update($user =
null, $notrigger = 0)
6494 global $user, $conf;
6498 $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht ==
'');
6501 $this->desc = trim($this->desc);
6502 if (empty($this->ref_ext)) {
6503 $this->ref_ext =
'';
6505 if (empty($this->tva_tx)) {
6508 if (empty($this->localtax1_tx)) {
6509 $this->localtax1_tx = 0;
6511 if (empty($this->localtax2_tx)) {
6512 $this->localtax2_tx = 0;
6514 if (empty($this->localtax1_type)) {
6515 $this->localtax1_type = 0;
6517 if (empty($this->localtax2_type)) {
6518 $this->localtax2_type = 0;
6520 if (empty($this->total_localtax1)) {
6521 $this->total_localtax1 = 0;
6523 if (empty($this->total_localtax2)) {
6524 $this->total_localtax2 = 0;
6526 if (empty($this->remise_percent)) {
6527 $this->remise_percent = 0;
6529 if (empty($this->info_bits)) {
6530 $this->info_bits = 0;
6532 if (empty($this->special_code)) {
6533 $this->special_code = 0;
6535 if (empty($this->product_type)) {
6536 $this->product_type = 0;
6538 if (empty($this->fk_parent_line)) {
6539 $this->fk_parent_line = 0;
6541 if (!isset($this->situation_percent) || $this->situation_percent > 100 || (
string) $this->situation_percent ==
'') {
6542 $this->situation_percent = 100;
6544 if (empty($this->pa_ht)) {
6548 if (empty($this->multicurrency_subprice)) {
6549 $this->multicurrency_subprice = 0;
6551 if (empty($this->multicurrency_total_ht)) {
6552 $this->multicurrency_total_ht = 0;
6554 if (empty($this->multicurrency_total_tva)) {
6555 $this->multicurrency_total_tva = 0;
6557 if (empty($this->multicurrency_total_ttc)) {
6558 $this->multicurrency_total_ttc = 0;
6562 if ($this->product_type < 0) {
6567 if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
6569 $result = $this->
defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
6573 $this->pa_ht = $result;
6580 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6581 $sql .=
" description='".$this->db->escape($this->desc).
"'";
6582 $sql .=
", ref_ext='".$this->db->escape($this->ref_ext).
"'";
6583 $sql .=
", label=".(!empty($this->label) ?
"'".$this->db->escape($this->label).
"'" :
"null");
6584 $sql .=
", subprice=".price2num($this->subprice);
6585 $sql .=
", remise_percent=".price2num($this->remise_percent);
6586 if ($this->fk_remise_except) {
6587 $sql .=
", fk_remise_except=".$this->fk_remise_except;
6589 $sql .=
", fk_remise_except=null";
6591 $sql .=
", vat_src_code = '".(empty($this->vat_src_code) ?
'' : $this->db->escape($this->vat_src_code)).
"'";
6592 $sql .=
", tva_tx=".price2num($this->tva_tx);
6593 $sql .=
", localtax1_tx=".price2num($this->localtax1_tx);
6594 $sql .=
", localtax2_tx=".price2num($this->localtax2_tx);
6595 $sql .=
", localtax1_type='".$this->db->escape($this->localtax1_type).
"'";
6596 $sql .=
", localtax2_type='".$this->db->escape($this->localtax2_type).
"'";
6597 $sql .=
", qty=".price2num($this->qty);
6598 $sql .=
", date_start=".(!empty($this->date_start) ?
"'".$this->db->idate($this->date_start).
"'" :
"null");
6599 $sql .=
", date_end=".(!empty($this->date_end) ?
"'".$this->db->idate($this->date_end).
"'" :
"null");
6600 $sql .=
", product_type=".$this->product_type;
6601 $sql .=
", info_bits='".$this->db->escape($this->info_bits).
"'";
6602 $sql .=
", special_code=" . (int) $this->special_code;
6603 if (empty($this->skip_update_total)) {
6604 $sql .=
", total_ht=".price2num($this->total_ht);
6605 $sql .=
", total_tva=".price2num($this->total_tva);
6606 $sql .=
", total_ttc=".price2num($this->total_ttc);
6607 $sql .=
", total_localtax1=".price2num($this->total_localtax1);
6608 $sql .=
", total_localtax2=".price2num($this->total_localtax2);
6610 $sql .=
", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ?
"'".$this->db->escape($this->fk_fournprice).
"'" :
"null");
6611 $sql .=
", buy_price_ht=".(($this->pa_ht || (string) $this->pa_ht ===
'0') ?
price2num($this->pa_ht) :
"null");
6612 $sql .=
", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line :
"null");
6613 if (!empty($this->rang)) {
6614 $sql .=
", rang=".((int) $this->rang);
6616 $sql .=
", situation_percent = ".((float) $this->situation_percent);
6617 $sql .=
", fk_unit = ".(!$this->fk_unit ?
'NULL' : $this->fk_unit);
6618 $sql .=
", fk_user_modif = ".((int) $user->id);
6621 $sql .=
", multicurrency_subprice=".price2num($this->multicurrency_subprice);
6622 $sql .=
", multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
6623 $sql .=
", multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
6624 $sql .=
", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
6626 $sql .=
", batch = '".$this->db->escape($this->batch).
"'";
6627 $sql .=
", fk_warehouse = ".((int) $this->fk_warehouse);
6629 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6631 dol_syslog(get_class($this).
"::update", LOG_DEBUG);
6632 $resql = $this->db->query($sql);
6635 $this->
id = $this->rowid;
6642 if (!$error && !$notrigger) {
6644 $result = $this->
call_trigger(
'LINEBILL_MODIFY', $user);
6646 $this->db->rollback();
6651 $this->db->commit();
6654 $this->error = $this->db->error();
6655 $this->db->rollback();
6667 public function delete($tmpuser =
null, $notrigger = 0)
6674 if (empty($notrigger)) {
6675 $result = $this->
call_trigger(
'LINEBILL_DELETE', $user);
6677 $this->db->rollback();
6686 $this->db->rollback();
6691 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'societe_remise_except';
6692 $sql .=
' SET fk_facture_line = NULL';
6693 $sql .=
' WHERE fk_facture_line = '.((int) $this->
id);
6695 dol_syslog(get_class($this).
"::deleteline", LOG_DEBUG);
6696 $result = $this->db->query($sql);
6698 $this->error = $this->db->error();
6699 $this->errors[] = $this->error;
6700 $this->db->rollback();
6704 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'element_time';
6705 $sql .=
' SET invoice_id = NULL, invoice_line_id = NULL';
6706 $sql .=
' WHERE invoice_line_id = '.((int) $this->
id);
6707 if (!$this->db->query($sql)) {
6708 $this->error = $this->db->error().
" sql=".$sql;
6709 $this->errors[] = $this->error;
6710 $this->db->rollback();
6714 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $this->
id);
6716 if ($this->db->query($sql)) {
6717 $this->db->commit();
6720 $this->error = $this->db->error().
" sql=".$sql;
6721 $this->errors[] = $this->error;
6722 $this->db->rollback();
6738 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6741 if (empty($this->total_localtax1)) {
6742 $this->total_localtax1 = 0;
6744 if (empty($this->total_localtax2)) {
6745 $this->total_localtax2 = 0;
6749 $sql =
"UPDATE ".MAIN_DB_PREFIX.
"facturedet SET";
6750 $sql .=
" total_ht=".price2num($this->total_ht);
6751 $sql .=
",total_tva=".price2num($this->total_tva);
6752 $sql .=
",total_localtax1=".price2num($this->total_localtax1);
6753 $sql .=
",total_localtax2=".price2num($this->total_localtax2);
6754 $sql .=
",total_ttc=".price2num($this->total_ttc);
6755 $sql .=
" WHERE rowid = ".((int) $this->
rowid);
6757 dol_syslog(get_class($this).
"::update_total", LOG_DEBUG);
6759 $resql = $this->db->query($sql);
6761 $this->db->commit();
6764 $this->error = $this->db->error();
6765 $this->db->rollback();
6783 global $invoicecache;
6785 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6789 if (!isset($invoicecache[$invoiceid])) {
6790 $invoicecache[$invoiceid] =
new Facture($this->db);
6791 $invoicecache[$invoiceid]->fetch($invoiceid);
6797 $sql =
"SELECT situation_percent FROM ".MAIN_DB_PREFIX.
"facturedet";
6798 $sql .=
" WHERE rowid = ".((int) $this->fk_prev_id);
6800 $resql = $this->db->query($sql);
6802 if ($resql && $this->db->num_rows($resql) > 0) {
6805 $obj = $this->db->fetch_object($resql);
6807 $returnPercent = (float) $obj->situation_percent;
6810 if ($include_credit_note) {
6811 $sql =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6812 $sql .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6813 $sql .=
" WHERE fd.fk_prev_id = ".((int) $this->fk_prev_id);
6814 $sql .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6815 $sql .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6817 $res = $this->db->query($sql);
6819 while ($obj = $this->db->fetch_object($res)) {
6820 $returnPercent = $returnPercent + (float) $obj->situation_percent;
6827 return $returnPercent;
6829 $this->error = $this->db->error();
6830 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6831 $this->db->rollback();
6850 global $invoicecache;
6852 if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id ==
"") {
6856 if (!isset($invoicecache[$invoiceid])) {
6857 $invoicecache[$invoiceid] =
new Facture($this->db);
6858 $invoicecache[$invoiceid]->fetch($invoiceid);
6865 $lastprevid = $this->fk_prev_id;
6866 $cumulated_percent = 0.0;
6868 while (!$all_found) {
6869 $sql =
"SELECT situation_percent, fk_prev_id FROM ".MAIN_DB_PREFIX.
"facturedet WHERE rowid = ".((int) $lastprevid);
6870 $resql = $this->db->query($sql);
6872 if ($resql && $this->db->num_rows($resql) > 0) {
6873 $obj = $this->db->fetch_object($resql);
6874 $cumulated_percent += floatval($obj->situation_percent);
6876 if ($include_credit_note) {
6877 $sql_credit_note =
'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.
'facturedet fd';
6878 $sql_credit_note .=
' JOIN '.MAIN_DB_PREFIX.
'facture f ON (f.rowid = fd.fk_facture) ';
6879 $sql_credit_note .=
" WHERE fd.fk_prev_id = ".((int) $lastprevid);
6880 $sql_credit_note .=
" AND f.situation_cycle_ref = ".((int) $invoicecache[$invoiceid]->situation_cycle_ref);
6881 $sql_credit_note .=
" AND f.type = ".Facture::TYPE_CREDIT_NOTE;
6883 $res_credit_note = $this->db->query($sql_credit_note);
6884 if ($res_credit_note) {
6885 while ($cn = $this->db->fetch_object($res_credit_note)) {
6886 $cumulated_percent = $cumulated_percent + floatval($cn->situation_percent);
6894 if ($obj->fk_prev_id) {
6895 $lastprevid = $obj->fk_prev_id;
6900 $this->error = $this->db->error();
6901 dol_syslog(get_class($this).
"::select Error ".$this->error, LOG_ERR);
6902 $this->db->rollback();
6906 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