dolibarr 25.0.0-alpha
discount.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2024 Alexandre Janniaux <alexandre.janniaux@gmail.com>
5 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2024 Noé Cendrier <noe.cendrier@altairis.fr>
8 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
30require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31
36{
41 public $fk_soc;
45 public $socid;
46
50 public $discount_type; // 0 => customer discount, 1 => supplier discount
51
55 public $total_ht;
59 public $total_tva;
63 public $total_ttc;
68 public $amount_ht; // deprecated
73 public $amount_tva; // deprecated
78 public $amount_ttc; // deprecated
79
83 public $multicurrency_total_ht;
87 public $multicurrency_total_tva;
91 public $multicurrency_total_ttc;
96 public $multicurrency_amount_ht; // deprecated
101 public $multicurrency_amount_tva; // deprecated
106 public $multicurrency_amount_ttc; // deprecated
107
111 public $multicurrency_subprice;
112
116 public $fk_invoice_supplier;
117
121 public $fk_invoice_supplier_line;
122
126 public $tva_tx;
130 public $localtax1_tx;
134 public $localtax2_tx;
138 public $localtax1_type;
142 public $localtax2_type;
146 public $vat_src_code;
147
151 public $fk_user;
152
156 public $description;
157
163 public $datec;
164
168 public $fk_facture_line;
169
173 public $fk_facture;
174
178 public $fk_facture_source;
182 public $ref_facture_source; // Ref credit note or deposit used to create the discount
186 public $type_facture_source;
187
191 public $fk_invoice_supplier_source;
195 public $ref_invoice_supplier_source; // Ref credit note or deposit used to create the discount
199 public $type_invoice_supplier_source;
200
201 /* Customer Discount */
202 const TYPE_CUSTOMER = 0;
203
204 /* Supplier Discount */
205 const TYPE_SUPPLIER = 1;
206
212 public function __construct($db)
213 {
214 $this->db = $db;
215 }
216
217
226 public function fetch($rowid, $fk_facture_source = 0, $fk_invoice_supplier_source = 0)
227 {
228 // Check parameters
229 if (!$rowid && !$fk_facture_source && !$fk_invoice_supplier_source) {
230 $this->error = 'ErrorBadParameters';
231 return -1;
232 }
233
234 $sql = "SELECT sr.rowid, sr.fk_soc, sr.discount_type,";
235 $sql .= " sr.fk_user,";
236 $sql .= " sr.amount_ht, sr.amount_tva, sr.amount_localtax1, sr.amount_localtax2, sr.amount_ttc, sr.tva_tx, sr.localtax1_tx, sr.localtax1_type, sr.localtax2_tx, sr.localtax2_type, sr.vat_src_code,";
237 $sql .= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,";
238 $sql .= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.fk_invoice_supplier_line, sr.fk_invoice_supplier, sr.fk_invoice_supplier_source, sr.description,";
239 $sql .= " sr.datec,";
240 $sql .= " f.ref as ref_facture_source, f.type as type_facture_source,";
241 $sql .= " fsup.ref as ref_invoice_supplier_source, fsup.type as type_invoice_supplier_source";
242 $sql .= " FROM ".$this->db->prefix()."societe_remise_except as sr";
243 $sql .= " LEFT JOIN ".$this->db->prefix()."facture as f ON sr.fk_facture_source = f.rowid";
244 $sql .= " LEFT JOIN ".$this->db->prefix()."facture_fourn as fsup ON sr.fk_invoice_supplier_source = fsup.rowid";
245 $sql .= " WHERE sr.entity IN (".getEntity('invoice').")";
246 if ($rowid) {
247 $sql .= " AND sr.rowid = ".((int) $rowid);
248 }
249 if ($fk_facture_source) {
250 $sql .= " AND sr.fk_facture_source = ".((int) $fk_facture_source);
251 }
252 if ($fk_invoice_supplier_source) {
253 $sql .= " AND sr.fk_invoice_supplier_source = ".((int) $fk_invoice_supplier_source);
254 }
255
256 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
257 $resql = $this->db->query($sql);
258 if ($resql) {
259 if ($this->db->num_rows($resql)) {
260 $obj = $this->db->fetch_object($resql);
261
262 $this->id = $obj->rowid;
263 $this->fk_soc = $obj->fk_soc;
264 $this->socid = $obj->fk_soc;
265 $this->discount_type = $obj->discount_type;
266
267 $this->total_ht = $obj->amount_ht;
268 $this->total_tva = $obj->amount_tva;
269 $this->total_localtax1 = $obj->amount_localtax1;
270 $this->total_localtax2 = $obj->amount_localtax2;
271 $this->total_ttc = $obj->amount_ttc;
272 // For backward compatibility
273 $this->amount_ht = $this->total_ht;
274 $this->amount_tva = $this->total_tva;
275 $this->amount_ttc = $this->total_ttc;
276
277 $this->multicurrency_total_ht = $this->multicurrency_subprice = $obj->multicurrency_amount_ht;
278 $this->multicurrency_total_tva = $obj->multicurrency_amount_tva;
279 $this->multicurrency_total_ttc = $obj->multicurrency_amount_ttc;
280 // For backward compatibility
281 $this->multicurrency_amount_ht = $this->multicurrency_total_ht;
282 $this->multicurrency_amount_tva = $this->multicurrency_total_tva;
283 $this->multicurrency_amount_ttc = $this->multicurrency_total_ttc;
284
285 $this->tva_tx = $obj->tva_tx;
286 $this->localtax1_tx = $obj->localtax1_tx;
287 $this->localtax1_type = $obj->localtax1_type;
288 $this->localtax2_tx = $obj->localtax2_tx;
289 $this->localtax2_type = $obj->localtax2_type;
290 $this->vat_src_code = $obj->vat_src_code;
291
292 $this->fk_user = $obj->fk_user;
293 $this->fk_facture_line = $obj->fk_facture_line;
294 $this->fk_facture = $obj->fk_facture;
295 $this->fk_facture_source = $obj->fk_facture_source; // Id credit note or deposit source
296 $this->ref_facture_source = $obj->ref_facture_source; // Ref credit note or deposit source
297 $this->type_facture_source = $obj->type_facture_source; // Type credit note or deposit source
298 $this->fk_invoice_supplier_line = $obj->fk_invoice_supplier_line;
299 $this->fk_invoice_supplier = $obj->fk_invoice_supplier;
300 $this->fk_invoice_supplier_source = $obj->fk_invoice_supplier_source; // Id credit note or deposit source
301 $this->ref_invoice_supplier_source = $obj->ref_invoice_supplier_source; // Ref credit note or deposit source
302 $this->type_invoice_supplier_source = $obj->type_invoice_supplier_source; // Type credit note or deposit source
303 $this->description = $obj->description;
304 $this->datec = $this->db->jdate($obj->datec);
305
306 $this->db->free($resql);
307 return 1;
308 } else {
309 $this->db->free($resql);
310 return 0;
311 }
312 } else {
313 $this->error = $this->db->error();
314 return -1;
315 }
316 }
317
318
325 public function create($user)
326 {
327 global $conf;
328
329 // Clean parameters
330 $this->amount_ht = price2num($this->amount_ht);
331 $this->amount_tva = price2num($this->amount_tva);
332 $this->amount_ttc = price2num($this->amount_ttc);
333
334 $this->tva_tx = price2num($this->tva_tx);
335 $this->localtax1_tx = price2num($this->localtax1_tx);
336 $this->localtax1_type = price2num($this->localtax1_type);
337 $this->localtax2_tx = price2num($this->localtax2_tx);
338 $this->localtax2_type = price2num($this->localtax2_type);
339
340 $this->multicurrency_amount_ht = price2num($this->multicurrency_amount_ht);
341 $this->multicurrency_amount_tva = price2num($this->multicurrency_amount_tva);
342 $this->multicurrency_amount_ttc = price2num($this->multicurrency_amount_ttc);
343
344 if (empty($this->multicurrency_amount_ht)) {
345 $this->multicurrency_amount_ht = 0;
346 }
347 if (empty($this->multicurrency_amount_tva)) {
348 $this->multicurrency_amount_tva = 0;
349 }
350 if (empty($this->multicurrency_amount_ttc)) {
351 $this->multicurrency_amount_ttc = 0;
352 }
353 if (empty($this->tva_tx)) {
354 $this->tva_tx = 0;
355 }
356 if (empty($this->localtax1_tx)) {
357 $this->localtax1_tx = 0;
358 $this->localtax1_type = 0;
359 }
360 if (empty($this->localtax2_tx)) {
361 $this->localtax2_tx = 0;
362 $this->localtax2_type = 0;
363 }
364
365 // Check parameters
366 if (empty($this->description)) {
367 $this->error = 'BadValueForPropertyDescriptionOfDiscount';
368 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
369 return -1;
370 }
371
372 $userid = $user->id;
373 if (!($userid > 0)) { // For example when record is saved into an anonymous context with a not loaded object $user.
374 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
375 $tmpinvoice = new Facture($this->db);
376 $tmpinvoice->fetch($this->fk_facture_source);
377 $userid = $tmpinvoice->user_creation_id; // We use the author of invoice
378 }
379
380 // Insert request
381 $sql = "INSERT INTO ".$this->db->prefix()."societe_remise_except";
382 $sql .= " (entity, datec, fk_soc, discount_type, fk_user, description,";
383 $sql .= " amount_ht, amount_tva, amount_localtax1, amount_localtax2, amount_ttc, tva_tx, localtax1_tx, localtax1_type, localtax2_tx, localtax2_type, vat_src_code,";
384 $sql .= " multicurrency_amount_ht, multicurrency_amount_tva, multicurrency_amount_ttc,";
385 $sql .= " fk_facture_source, fk_invoice_supplier_source, multicurrency_code, multicurrency_tx";
386 $sql .= ")";
387 $sql .= " VALUES (".((int) $conf->entity).", '".$this->db->idate($this->datec != '' ? $this->datec : dol_now())."', ".((int) $this->socid).", ".(empty($this->discount_type) ? 0 : intval($this->discount_type)).", ".((int) $userid).", '".$this->db->escape($this->description)."',";
388 $sql .= " ".price2num($this->amount_ht).", ".price2num($this->amount_tva).", ";
389 $sql .= " ".($this->total_localtax1 ? price2num($this->total_localtax1) : 0).", ".($this->total_localtax2 ? price2num($this->total_localtax2) : 0).", ".price2num($this->amount_ttc).", ".price2num($this->tva_tx).",";
390 $sql .= " ".($this->localtax1_tx ? price2num($this->localtax1_tx) : 0).", ".($this->localtax1_type ? price2num($this->localtax1_type) : 0).", ";
391 $sql .= " ".($this->localtax2_tx ? price2num($this->localtax2_tx) : 0).", ".($this->localtax2_type ? price2num($this->localtax2_type) : 0).", '".$this->db->escape($this->vat_src_code)."',";
392 $sql .= " ".price2num($this->multicurrency_amount_ht).", ".price2num($this->multicurrency_amount_tva).", ";
393 $sql .= " ".price2num($this->multicurrency_amount_ttc).", ";
394 $sql .= " ".($this->fk_facture_source ? ((int) $this->fk_facture_source) : "null").",";
395 $sql .= " ".($this->fk_invoice_supplier_source ? ((int) $this->fk_invoice_supplier_source) : "null").",";
396 $sql .= " ".($this->multicurrency_code ? "'".$this->db->escape($this->multicurrency_code)."'" : "null").",";
397 $sql .= " ".($this->multicurrency_tx ? price2num($this->multicurrency_tx) : "null");
398 $sql .= ")";
399
400 dol_syslog(get_class($this)."::create", LOG_DEBUG);
401 $resql = $this->db->query($sql);
402 if ($resql) {
403 $this->id = $this->db->last_insert_id($this->db->prefix()."societe_remise_except");
404
405 // Call trigger
406 $result = $this->call_trigger('DISCOUNTABSOLUTE_CREATE', $user);
407 if ($result < 0) {
408 return -1;
409 }
410 // End call triggers
411
412 return $this->id;
413 } else {
414 $this->error = $this->db->lasterror().' - sql='.$sql;
415 return -1;
416 }
417 }
418
419
427 public function delete($user, $noresetinvoice = false)
428 {
429 // Check if we can remove the discount
430 if ($this->fk_facture_source) {
431 $sql = "SELECT COUNT(rowid) as nb";
432 $sql .= " FROM ".$this->db->prefix()."societe_remise_except";
433 $sql .= " WHERE (fk_facture_line IS NOT NULL"; // Not used as absolute simple discount
434 $sql .= " OR fk_facture IS NOT NULL)"; // Not used as credit note and not used as deposit
435 $sql .= " AND fk_facture_source = ".((int) $this->fk_facture_source);
436 //$sql.=" AND rowid != ".((int) $this->id);
437
438 dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG);
439 $resql = $this->db->query($sql);
440 if ($resql) {
441 $obj = $this->db->fetch_object($resql);
442 if ($obj->nb > 0) {
443 $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
444 return -2;
445 }
446 } else {
447 dol_print_error($this->db);
448 return -1;
449 }
450 }
451
452 // Check if we can remove the discount
453 if ($this->fk_invoice_supplier_source) {
454 $sql = "SELECT COUNT(rowid) as nb";
455 $sql .= " FROM ".$this->db->prefix()."societe_remise_except";
456 $sql .= " WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount
457 $sql .= " OR fk_invoice_supplier IS NOT NULL)"; // Not used as credit note and not used as deposit
458 $sql .= " AND fk_invoice_supplier_source = ".((int) $this->fk_invoice_supplier_source);
459 //$sql.=" AND rowid != ".((int) $this->id);
460
461 dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG);
462 $resql = $this->db->query($sql);
463 if ($resql) {
464 $obj = $this->db->fetch_object($resql);
465 if ($obj->nb > 0) {
466 $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
467 return -2;
468 }
469 } else {
470 dol_print_error($this->db);
471 return -1;
472 }
473 }
474
475 $this->db->begin();
476
477 // Delete but only if not used
478 $sql = "DELETE FROM ".$this->db->prefix()."societe_remise_except ";
479 if ($this->fk_facture_source) {
480 $sql .= " WHERE fk_facture_source = ".((int) $this->fk_facture_source); // Delete all lines of same series
481 } elseif ($this->fk_invoice_supplier_source) {
482 $sql .= " WHERE fk_invoice_supplier_source = ".((int) $this->fk_invoice_supplier_source); // Delete all lines of same series
483 } else {
484 $sql .= " WHERE rowid = ".((int) $this->id); // Delete only line
485 }
486 $sql .= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount
487 $sql .= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit
488 $sql .= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount
489 $sql .= " AND fk_invoice_supplier IS NULL)"; // Not used as credit note and not used as deposit
490
491 dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG);
492
493 require_once DOL_DOCUMENT_ROOT. '/core/class/commoninvoice.class.php';
494 $result = $this->db->query($sql);
495 if ($result) {
496 // If source of discount was a credit note or deposit, we change source statut.
497 if (!$noresetinvoice && $this->fk_facture_source) {
498 $sql = "UPDATE ".$this->db->prefix()."facture";
499 $sql .= " set paye=0, fk_statut=1";
500 $sql .= " WHERE type IN (".$this->db->sanitize(CommonInvoice::TYPE_CREDIT_NOTE.", ".CommonInvoice::TYPE_DEPOSIT).") AND rowid = ".((int) $this->fk_facture_source);
501
502 dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG);
503 $result = $this->db->query($sql);
504 if ($result) {
505 $this->db->commit();
506 return 1;
507 } else {
508 $this->error = $this->db->lasterror();
509 $this->db->rollback();
510 return -1;
511 }
512 } elseif (!$noresetinvoice && $this->fk_invoice_supplier_source) {
513 $sql = "UPDATE ".$this->db->prefix()."facture_fourn";
514 $sql .= " set paye=0, fk_statut=1";
515 $sql .= " WHERE type IN (".$this->db->sanitize(CommonInvoice::TYPE_CREDIT_NOTE.", ".CommonInvoice::TYPE_DEPOSIT).") AND rowid = ".((int) $this->fk_invoice_supplier_source);
516
517 dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG);
518 $result = $this->db->query($sql);
519 if ($result) {
520 $this->db->commit();
521 return 1;
522 } else {
523 $this->error = $this->db->lasterror();
524 $this->db->rollback();
525 return -1;
526 }
527 } else {
528 $this->db->commit();
529 return 1;
530 }
531 } else {
532 $this->error = $this->db->lasterror();
533 $this->db->rollback();
534 return -1;
535 }
536 }
537
538
539
540 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
551 public function link_to_invoice($rowidline, $rowidinvoice, $notrigger = 0)
552 {
553 // phpcs:enable
554 global $user;
555
556 // Check parameters
557 if (!$rowidline && !$rowidinvoice) {
558 $this->error = 'ErrorBadParameters';
559 return -1;
560 }
561 if ($rowidline && $rowidinvoice) {
562 $this->error = 'ErrorBadParameters';
563 return -2;
564 }
565
566 $sql = "UPDATE ".$this->db->prefix()."societe_remise_except";
567 if (!empty($this->discount_type)) {
568 if ($rowidline) {
569 $sql .= " SET fk_invoice_supplier_line = ".((int) $rowidline);
570 }
571 if ($rowidinvoice) {
572 $sql .= " SET fk_invoice_supplier = ".((int) $rowidinvoice);
573 }
574 } else {
575 if ($rowidline) {
576 $sql .= " SET fk_facture_line = ".((int) $rowidline);
577 }
578 if ($rowidinvoice) {
579 $sql .= " SET fk_facture = ".((int) $rowidinvoice);
580 }
581 }
582 $sql .= " WHERE rowid = ".((int) $this->id);
583
584 dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG);
585 $resql = $this->db->query($sql);
586 if ($resql) {
587 if (!empty($this->discount_type)) {
588 $this->fk_invoice_supplier_line = $rowidline;
589 $this->fk_invoice_supplier = $rowidinvoice;
590 } else {
591 $this->fk_facture_line = $rowidline;
592 $this->fk_facture = $rowidinvoice;
593 }
594
595 // If a discount comes from a source invoice (deposit/credit note/excess) and is applied to another invoice,
596 // also create a link between the source invoice and the target invoice.
597 if ($rowidinvoice) {
598 $sourcetype = '';
599 $targettype = '';
600 $sourceinvoiceid = 0;
601
602 if (!empty($this->discount_type)) {
603 $sourcetype = 'invoice_supplier';
604 $targettype = 'invoice_supplier';
605 $sourceinvoiceid = (int) $this->fk_invoice_supplier_source;
606 } else {
607 $sourcetype = 'facture';
608 $targettype = 'facture';
609 $sourceinvoiceid = (int) $this->fk_facture_source;
610 }
611
612 if ($sourceinvoiceid > 0 && $sourceinvoiceid !== (int) $rowidinvoice) {
613 $sqlcheck = "SELECT 1";
614 $sqlcheck .= " FROM ".$this->db->prefix()."element_element";
615 $sqlcheck .= " WHERE fk_source = ".((int) $sourceinvoiceid);
616 $sqlcheck .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
617 $sqlcheck .= " AND fk_target = ".((int) $rowidinvoice);
618 $sqlcheck .= " AND targettype = '".$this->db->escape($targettype)."'";
619 $sqlcheck .= $this->db->plimit(1);
620
621 $rescheck = $this->db->query($sqlcheck);
622 if ($rescheck && $this->db->num_rows($rescheck) === 0) {
623 $sqladd = "INSERT INTO ".$this->db->prefix()."element_element (fk_source, sourcetype, fk_target, targettype)";
624 $sqladd .= " VALUES (".((int) $sourceinvoiceid).", '".$this->db->escape($sourcetype)."', ".((int) $rowidinvoice).", '".$this->db->escape($targettype)."')";
625 $this->db->query($sqladd); // Best-effort: do not fail discount link if object link can't be created.
626 }
627 }
628 }
629
630 if (!$notrigger) {
631 // Call trigger
632 $result = $this->call_trigger('DISCOUNT_MODIFY', $user);
633 if ($result < 0) {
634 return -2;
635 }
636 // End call triggers
637 }
638 return 1;
639 } else {
640 $this->error = $this->db->error();
641 return -3;
642 }
643 }
644
645
646 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
654 public function unlink_invoice($notrigger = 0)
655 {
656 // phpcs:enable
657 global $user;
658
659 $sql = "UPDATE ".$this->db->prefix()."societe_remise_except";
660 if (!empty($this->discount_type)) {
661 $sql .= " SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL";
662 } else {
663 $sql .= " SET fk_facture_line = NULL, fk_facture = NULL";
664 }
665 $sql .= " WHERE rowid = ".((int) $this->id);
666
667 dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG);
668 $resql = $this->db->query($sql);
669 if ($resql) {
670 if (!$notrigger) {
671 // Call trigger
672 $result = $this->call_trigger('DISCOUNT_MODIFY', $user);
673 if ($result < 0) {
674 return -2;
675 }
676 // End call triggers
677 }
678 return 1;
679 } else {
680 $this->error = $this->db->error();
681 return -3;
682 }
683 }
684
685
697 public function getAvailableDiscounts($company = null, $user = null, $filter = '', $maxvalue = 0, $discount_type = 0, $multicurrency = 0)
698 {
699 global $conf, $hookmanager;
700
701 dol_syslog(get_class($this)."::getAvailableDiscounts discount_type=".$discount_type, LOG_DEBUG);
702
703 $parameters = array(
704 'company' => $company,
705 'user' => $user,
706 'filter' => $filter,
707 'maxvalue' => $maxvalue,
708 'discount_type' => $discount_type,
709 'multicurrency' => $multicurrency
710 );
711
712 $reshook = $hookmanager->executeHooks('getAvailableDiscounts', $parameters);
713 if (empty($reshook)) {
714 $sql = "SELECT SUM(rc.amount_ttc) as amount, SUM(rc.multicurrency_amount_ttc) as multicurrency_amount";
715 $sql .= " FROM ".$this->db->prefix()."societe_remise_except as rc";
716 $sql .= " WHERE rc.entity = ".((int) $conf->entity);
717 $sql .= " AND rc.discount_type=".((int) $discount_type);
718 if (!empty($discount_type)) {
719 $sql .= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier
720 } else {
721 $sql .= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer
722 }
723 if (is_object($company)) {
724 $sql .= " AND rc.fk_soc = ".((int) $company->id);
725 }
726 if (is_object($user)) {
727 $sql .= " AND rc.fk_user = ".((int) $user->id);
728 }
729 if ($filter) {
730 $sql .= " AND (".$filter.")"; // @phan-suppress-current-line SqlInjection
731 }
732 if ($maxvalue) {
733 $sql .= ' AND rc.amount_ttc <= '.((float) price2num($maxvalue));
734 }
735 } else {
736 $sql = $hookmanager->resArray['sql'];
737 }
738
739 $resql = $this->db->query($sql);
740 if ($resql) {
741 $obj = $this->db->fetch_object($resql);
742 //while ($obj)
743 //{
744 //print 'zz'.$obj->amount;
745 //$obj = $this->db->fetch_object($resql);
746 //}
747 if ($multicurrency) {
748 return $obj->multicurrency_amount;
749 }
750
751 return $obj->amount;
752 }
753 return -1;
754 }
755
764 public function getSumDepositsUsed($invoice, $multicurrency = 0)
765 {
766 dol_syslog(get_class($this)."::getSumDepositsUsed", LOG_DEBUG);
767
768 if ($invoice->element == 'facture' || $invoice->element == 'invoice') {
769 $sql = "SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount";
770 $sql .= " FROM ".$this->db->prefix()."societe_remise_except as rc, ".$this->db->prefix()."facture as f";
771 $sql .= " WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = ".((int) $invoice->id);
772 $sql .= " AND f.type = ". (int) $invoice::TYPE_DEPOSIT;
773 } elseif ($invoice->element == 'invoice_supplier') {
774 $sql = "SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount";
775 $sql .= " FROM ".$this->db->prefix()."societe_remise_except as rc, ".$this->db->prefix()."facture_fourn as f";
776 $sql .= " WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = ".((int) $invoice->id);
777 $sql .= " AND f.type = ". (int) $invoice::TYPE_DEPOSIT;
778 } else {
779 $this->error = get_class($this)."::getSumDepositsUsed was called with a bad object as a first parameter";
780 dol_print_error($this->db, $this->error);
781 return -1;
782 }
783
784 $resql = $this->db->query($sql);
785 if ($resql) {
786 $obj = $this->db->fetch_object($resql);
787 if ($multicurrency == 1) {
788 return $obj->multicurrency_amount;
789 } else {
790 return $obj->amount;
791 }
792 } else {
793 $this->error = $this->db->lasterror();
794 return -1;
795 }
796 }
797
805 public function getSumCreditNotesUsed($invoice, $multicurrency = 0)
806 {
807 dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG);
808
809 if ($invoice->element == 'facture' || $invoice->element == 'invoice') {
810 $sql = "SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount";
811 $sql .= " FROM ".$this->db->prefix()."societe_remise_except as rc, ".$this->db->prefix()."facture as f";
812 $sql .= " WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = ".((int) $invoice->id);
813 $sql .= " AND f.type IN (".$this->db->sanitize($invoice::TYPE_STANDARD.", ".$invoice::TYPE_CREDIT_NOTE.", ".$invoice::TYPE_SITUATION).")"; // Find discount coming from credit note or excess received
814 } elseif ($invoice->element == 'invoice_supplier') {
815 $sql = "SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount";
816 $sql .= " FROM ".$this->db->prefix()."societe_remise_except as rc, ".$this->db->prefix()."facture_fourn as f";
817 $sql .= " WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = ".((int) $invoice->id);
818 $sql .= " AND f.type IN (".$this->db->sanitize($invoice::TYPE_STANDARD.", ".$invoice::TYPE_CREDIT_NOTE).")"; // Find discount coming from credit note or excess paid
819 } else {
820 $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
821 dol_print_error($this->db, $this->error);
822 return 'ErrorBadElementType';
823 }
824
825 $resql = $this->db->query($sql);
826 if ($resql) {
827 $obj = $this->db->fetch_object($resql);
828 if ($multicurrency == 1) {
829 return $obj->multicurrency_amount;
830 } else {
831 return $obj->amount;
832 }
833 } else {
834 $this->error = $this->db->lasterror();
835 return 'ErrorBadSQLquery';
836 }
837 }
845 public function getSumFromThisCreditNotesNotUsed($invoice, $multicurrency = 0)
846 {
847 dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG);
848
849 if ($invoice->element == 'facture' || $invoice->element == 'invoice') {
850 $sql = "SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount";
851 $sql .= " FROM ".$this->db->prefix()."societe_remise_except as rc";
852 $sql .= " WHERE rc.fk_facture IS NULL AND rc.fk_facture_source = ".((int) $invoice->id);
853 } elseif ($invoice->element == 'invoice_supplier') {
854 $sql = "SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount";
855 $sql .= " FROM ".$this->db->prefix()."societe_remise_except as rc";
856 $sql .= " WHERE rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_source = ".((int) $invoice->id);
857 } else {
858 $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
859 dol_print_error($this->db, $this->error);
860 return -1;
861 }
862
863 $resql = $this->db->query($sql);
864 if ($resql) {
865 $obj = $this->db->fetch_object($resql);
866 if ($multicurrency) {
867 return $obj->multicurrency_amount;
868 } else {
869 return $obj->amount;
870 }
871 } else {
872 $this->error = $this->db->lasterror();
873 return -1;
874 }
875 }
876
884 public function getNomUrl($withpicto = 0, $option = 'invoice')
885 {
886 global $langs;
887
888 $result = '';
889 $link = '';
890 $linkend = '';
891 $label = '';
892 $picto = '';
893 $ref = '';
894
895 if ($option == 'invoice') {
896 $facid = !empty($this->discount_type) ? $this->fk_invoice_supplier_source : $this->fk_facture_source;
897 $link = !empty($this->discount_type) ? '/fourn/facture/card.php' : '/compta/facture/card.php';
898 $label = $langs->trans("ShowSourceInvoice").': '.$this->ref_facture_source;
899 $link = '<a href="'.DOL_URL_ROOT.$link.'?facid='.$facid.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
900 $linkend = '</a>';
901 $ref = !empty($this->discount_type) ? $this->ref_invoice_supplier_source : $this->ref_facture_source;
902 $picto = 'bill';
903 }
904 if ($option == 'discount') {
905 $label = $langs->trans("Discount");
906 $link = '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$this->socid.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
907 $linkend = '</a>';
908 $ref = $langs->trans("Discount");
909 $picto = 'generic';
910 }
911
912
913 if ($withpicto) {
914 $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
915 }
916 if ($withpicto && $withpicto != 2) {
917 $result .= ' ';
918 }
919 $result .= $link.$ref.$linkend;
920 return $result;
921 }
922
923
931 public function initAsSpecimen()
932 {
933 $this->socid = 1;
934 $this->amount_ht = 10;
935 $this->amount_tva = 1.96;
936 $this->amount_ttc = 11.96;
937 $this->tva_tx = 19.6;
938 $this->description = 'Specimen discount';
939
940 return 1;
941 }
942
956 public function generateFromAmount($amount, $amount_type, $tva_tx, $localtax1_tx, $localtax2_tx, $localtax1_type = 1, $localtax2_type = 1)
957 {
958 $tva_tx_pct = (float) ($tva_tx / 100);
959 $localtax1_tx_pct = (float) ($localtax1_tx / 100);
960 $localtax2_tx_pct = (float) ($localtax2_tx / 100);
961
962 $err = 0;
963
964 //var_dump("amount=$amount, amount_type=$amount_type, tva_tx=$tva_tx, localtax1_tx=$localtax1_tx, localtax2_tx=$localtax2_tx, localtax1_type=$localtax1_type, localtax2_type=$localtax2_type");
965
966 // Test if localtax type is 2, 4 or 6 (loca tax are calculated on ht + vat)
967 $localtax1_type2 = ((int) $localtax1_type > 0 && (int) $localtax1_type % 2 == 0 ? 1 : 0);
968 $localtax2_type2 = ((int) $localtax2_type > 0 && (int) $localtax2_type % 2 == 0 ? 1 : 0);
969
970 if ($amount_type == 1) {
971 // TTC
972 $this->total_ttc = (float) price2num($amount, 'MT');
973
974 $ttc = (float) $this->total_ttc;
975
976 // Calculate lt1 and/or lt2 = taxes added after VAT
977 $lt1 = 0;
978 $lt2 = 0;
979 $tx_before_vat = 0;
980 $tx_before_vat_without1 = 0;
981 $tx_before_vat_without2 = 0;
982 $tx_after_vat = 0;
983 $tx_after_vat_without1 = 0;
984 $tx_after_vat_without2 = 0;
985 if ($localtax1_type2 && $localtax1_tx_pct > 0) {
986 $tx_after_vat += $localtax1_tx_pct;
987 $tx_after_vat_without2 += $localtax1_tx_pct;
988 } else {
989 $tx_before_vat += $localtax1_tx_pct;
990 $tx_before_vat_without2 += $localtax1_tx_pct;
991 }
992 if ($localtax2_type2 && $localtax2_tx_pct > 0) {
993 $tx_after_vat += $localtax2_tx_pct;
994 $tx_after_vat_without1 += $localtax2_tx_pct;
995 } else {
996 $tx_before_vat += $localtax2_tx_pct;
997 $tx_before_vat_without1 += $localtax2_tx_pct;
998 }
999 $tx_before_vat += $tva_tx_pct;
1000 $tx_before_vat_without1 += $tva_tx_pct;
1001 $tx_before_vat_without2 += $tva_tx_pct;
1002 if ($localtax1_type2 && $localtax1_tx_pct > 0) {
1003 $lt1 = (float) price2num($ttc - $ttc / (1 + $tx_after_vat) * (1 + $tx_after_vat_without1), 'MT');
1004 }
1005 if ($localtax2_type2 && $localtax2_tx_pct > 0) {
1006 $lt2 = (float) price2num($ttc - $ttc / (1 + $tx_after_vat) * (1 + $tx_after_vat_without2), 'MT');
1007 }
1008
1009 // lt1 and lt2 if calculated including taxes
1010 //var_dump("if lt1 or lt2 are calculated including vat: lt1=$lt1 lt2=$lt2");
1011
1012 $htplusbeforevat = $ttc - $lt1 - $lt2; // $htplusbeforevat = amount with HT + taxes added before VAT
1013
1014 if (!$localtax1_type2 && $localtax1_tx_pct > 0) {
1015 $lt1 = (float) price2num($htplusbeforevat - $htplusbeforevat / (1 + $tx_before_vat) * (1 + $tx_before_vat_without1), 'MT');
1016 }
1017 if (!$localtax2_type2 && $localtax2_tx_pct > 0) {
1018 $lt2 = (float) price2num($htplusbeforevat - $htplusbeforevat / (1 + $tx_before_vat) * (1 + $tx_before_vat_without2), 'MT');
1019 }
1020
1021 // lt1 and lt2 are now local taxes (whatever they are calculated before of after vat)
1022 //var_dump("lt1 or lt2 whatever is calculation mode: lt1=$lt1 lt2=$lt2");
1023
1024 $tva = ($ttc - $lt2 - $lt1) - ($ttc - $lt2 - $lt1) / (1 + $tva_tx_pct);
1025 $this->total_tva = (float) price2num($tva, 'MT');
1026 $this->total_localtax1 = $lt1;
1027 $this->total_localtax2 = $lt2;
1028 $this->total_ht = (float) price2num($this->total_ttc - $this->total_localtax1 - $this->total_localtax2 - $this->total_tva, 'MT');
1029
1030
1031 $this->multicurrency_total_ttc = (float) price2num($amount * (float) $this->multicurrency_tx, 'MT');
1032 $this->multicurrency_total_ht = (float) price2num((float) $amount / (1 + $tva_tx_pct) * (float) $this->multicurrency_tx, 'MT');
1033 $this->multicurrency_total_tva = (float) price2num($this->multicurrency_total_ttc - $this->multicurrency_total_ht, 'MT');
1034 } elseif ($amount_type == 0) {
1035 // HT
1036 $this->total_ht = (float) price2num($amount, 'MT');
1037 $this->total_tva = (float) price2num((float) $this->total_ht * $tva_tx_pct, 'MT');
1038 //$this->total_ttc = price2num((float) $this->total_ht + (float) $this->total_tva + ..., 'MT'); // Is set later
1039
1040 $this->multicurrency_total_ht = (float) price2num($amount * (float) $this->multicurrency_tx, 'MT');
1041 $this->multicurrency_total_tva = (float) price2num(((float) $amount * $tva_tx_pct) * (float) $this->multicurrency_tx, 'MT');
1042 //$this->multicurrency_total_ttc = price2num(((float) $this->total_ht + (float) $this->total_tva + ...) * (float) $this->multicurrency_tx, 'MT'); // Is set later
1043
1044 if ($localtax1_type2 == 0) {
1045 $this->total_localtax1 = (float) price2num((float) $this->total_ht * $localtax1_tx_pct, 'MT');
1046 } elseif ($localtax1_type2 == 1) {
1047 $this->total_localtax1 = (float) price2num(((float) $this->total_ht + (float) $this->total_tva) * $localtax1_tx_pct, 'MT');
1048 }
1049
1050 if ($localtax2_type2 == 0) {
1051 $this->total_localtax2 = (float) price2num((float) $this->total_ht * $localtax2_tx_pct, 'MT');
1052 } elseif ($localtax2_type2 == 1) {
1053 $this->total_localtax2 = (float) price2num(((float) $this->total_ht + (float) $this->total_tva) * $localtax2_tx_pct, 'MT');
1054 }
1055 }
1056
1057 // For backward compatibility
1058 $this->amount_ht = $this->total_ht;
1059 $this->amount_tva = $this->total_tva;
1060 $this->amount_ttc = $this->total_ttc;
1061 $this->multicurrency_amount_ht = $this->multicurrency_total_ht;
1062 $this->multicurrency_amount_tva = $this->multicurrency_total_tva;
1063 $this->multicurrency_amount_ttc = $this->multicurrency_total_ttc;
1064
1065 $this->tva_tx = $tva_tx;
1066 $this->localtax1_tx = $localtax1_tx;
1067 $this->localtax1_type = $localtax1_type;
1068 $this->localtax2_tx = $localtax2_tx;
1069 $this->localtax2_type = $localtax2_type;
1070
1071 //var_dump("localtax1 mode=$localtax1_type2 localtax2 mode=$localtax2_type2");
1072
1073
1074 if (empty($this->total_ttc)) {
1075 // If the total amount comes from a split discount, we take it as-is
1076 // because recalculating the total amount from the net amount creates precision errors.
1077 $this->total_ttc = (float) price2num((float) $this->total_ht + (float) $this->total_tva + $this->total_localtax1 + $this->total_localtax2, 'MT');
1078 $this->multicurrency_total_ttc = (float) price2num(((float) $this->total_ht + (float) $this->total_tva + $this->total_localtax1 + $this->total_localtax2) * (float) $this->multicurrency_tx, 'MT');
1079
1080 // For backward compatibility
1081 $this->amount_ttc = $this->total_ttc;
1082 $this->multicurrency_amount_ttc = $this->multicurrency_total_ttc;
1083 }
1084
1085 //var_dump("total_ht=".$this->total_ht." total_tva=".$this->total_tva." total_localtax1=".$this->total_localtax1." total_localtax2=".$this->total_localtax2." total_ttc=".$this->total_ttc);
1086
1087 return $err;
1088 }
1089
1097 public function splitAmount($amount_ttc1, $amount_ttc2)
1098 {
1099 // Moved from remx.php :: domain-related operations within action confirm_split
1100 $newdiscount1 = new DiscountAbsolute($this->db);
1101 $newdiscount2 = new DiscountAbsolute($this->db);
1102 $newdiscount1->fk_facture_source = $this->fk_facture_source;
1103 $newdiscount2->fk_facture_source = $this->fk_facture_source;
1104 $newdiscount1->fk_facture = $this->fk_facture;
1105 $newdiscount2->fk_facture = $this->fk_facture;
1106 $newdiscount1->fk_facture_line = $this->fk_facture_line;
1107 $newdiscount2->fk_facture_line = $this->fk_facture_line;
1108 $newdiscount1->fk_invoice_supplier_source = $this->fk_invoice_supplier_source;
1109 $newdiscount2->fk_invoice_supplier_source = $this->fk_invoice_supplier_source;
1110 $newdiscount1->fk_invoice_supplier = $this->fk_invoice_supplier;
1111 $newdiscount2->fk_invoice_supplier = $this->fk_invoice_supplier;
1112 $newdiscount1->fk_invoice_supplier_line = $this->fk_invoice_supplier_line;
1113 $newdiscount2->fk_invoice_supplier_line = $this->fk_invoice_supplier_line;
1114 if ($this->description == '(CREDIT_NOTE)' || $this->description == '(DEPOSIT)') {
1115 $newdiscount1->description = $this->description;
1116 $newdiscount2->description = $this->description;
1117 } else {
1118 $newdiscount1->description = $this->description.' (1)';
1119 $newdiscount2->description = $this->description.' (2)';
1120 }
1121 $newdiscount1->fk_user = $this->fk_user;
1122 $newdiscount2->fk_user = $this->fk_user;
1123 $newdiscount1->fk_soc = $this->fk_soc;
1124 $newdiscount1->socid = $this->socid;
1125 $newdiscount2->fk_soc = $this->fk_soc;
1126 $newdiscount2->socid = $this->socid;
1127 $newdiscount1->discount_type = $this->discount_type;
1128 $newdiscount2->discount_type = $this->discount_type;
1129 $newdiscount1->datec = $this->datec;
1130 $newdiscount2->datec = $this->datec;
1131 $newdiscount1->tva_tx = $this->tva_tx;
1132 $newdiscount2->tva_tx = $this->tva_tx;
1133 $newdiscount1->localtax1_tx = $this->localtax1_tx;
1134 $newdiscount2->localtax1_tx = $this->localtax1_tx;
1135 $newdiscount1->localtax2_tx = $this->localtax2_tx;
1136 $newdiscount2->localtax2_tx = $this->localtax2_tx;
1137 $newdiscount1->vat_src_code = $this->vat_src_code;
1138 $newdiscount2->vat_src_code = $this->vat_src_code;
1139
1140 $newdiscount1->generateFromAmount($amount_ttc1, 1, $newdiscount1->tva_tx, $newdiscount1->localtax1_tx, $newdiscount1->localtax2_tx, $this->localtax1_type, $this->localtax2_type);
1141 $newdiscount2->generateFromAmount($amount_ttc2, 1, $newdiscount2->tva_tx, $newdiscount2->localtax1_tx, $newdiscount2->localtax2_tx, $this->localtax1_type, $this->localtax2_type);
1142
1143 return array($newdiscount1, $newdiscount2);
1144 }
1145}
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
const TYPE_CREDIT_NOTE
Credit note invoice.
const TYPE_DEPOSIT
Deposit invoice.
Class to manage absolute discounts.
generateFromAmount($amount, $amount_type, $tva_tx, $localtax1_tx, $localtax2_tx, $localtax1_type=1, $localtax2_type=1)
Helper method to create a discount from an amount.
getAvailableDiscounts($company=null, $user=null, $filter='', $maxvalue=0, $discount_type=0, $multicurrency=0)
Return amount (with tax) of discounts currently available for a company, user or other criteria.
getSumFromThisCreditNotesNotUsed($invoice, $multicurrency=0)
initAsSpecimen()
Initialise an instance with random values.
splitAmount($amount_ttc1, $amount_ttc2)
Helper method to create two new discounts from split amount.
fetch($rowid, $fk_facture_source=0, $fk_invoice_supplier_source=0)
Load object from database into memory.
unlink_invoice($notrigger=0)
Link the discount to a particular invoice line or a particular invoice.
getNomUrl($withpicto=0, $option='invoice')
Return clickable ref of object (with picto or not)
create($user)
Create a discount into database.
getSumDepositsUsed($invoice, $multicurrency=0)
Return amount (with tax) of all deposits invoices used by invoice as a payment.
getSumCreditNotesUsed($invoice, $multicurrency=0)
Return amount (with tax) of all credit notes invoices + excess received used by invoice as a payment.
link_to_invoice($rowidline, $rowidinvoice, $notrigger=0)
Link the discount to a particular invoice line or a particular invoice.
__construct($db)
Constructor.
Class to manage invoices.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183