dolibarr 23.0.3
api_invoices.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2020 Thibault FOUCART <support@ptibogxiv.net>
4 * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
5 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2025 Charlene Benke <charlene@patas-monkey.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23use Luracast\Restler\RestException;
24
25require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
26require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
27
28
35class Invoices extends DolibarrApi
36{
40 public static $FIELDS = array(
41 'socid',
42 );
43
47 private $invoice;
48
52 private $template_invoice;
53
54
58 public function __construct()
59 {
60 global $db;
61 $this->db = $db;
62 $this->invoice = new Facture($this->db);
63 $this->template_invoice = new FactureRec($this->db);
64 }
65
79 public function get($id, $contact_list = 1, $properties = '', $withLines = true)
80 {
81 $invoice = $this->_fetch($id, '', '', $contact_list);
82
83 if (!$withLines) {
84 unset($invoice->lines);
85 }
86
87 return $this->_filterObjectProperties($invoice, $properties);
88 }
89
103 public function getByRef($ref, $contact_list = 1)
104 {
105 return $this->_fetch(0, $ref, '', $contact_list);
106 }
107
121 public function getByRefExt($ref_ext, $contact_list = 1)
122 {
123 return $this->_fetch(0, '', $ref_ext, $contact_list);
124 }
125
139 private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
140 {
141 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
142 throw new RestException(403);
143 }
144 if (empty($id) && empty($ref)&& empty($ref_ext)) {
145 throw new RestException(400, 'No invoice can be found with no criteria');
146 }
147 $result = $this->invoice->fetch($id, $ref, $ref_ext);
148 if (!$result) {
149 throw new RestException(404, 'Invoice not found');
150 }
151
152 // Get payment details
153 $this->invoice->totalpaid = $this->invoice->getSommePaiement();
154 $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
155 $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed();
156 $this->invoice->remaintopay = price2num($this->invoice->total_ttc - $this->invoice->totalpaid - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits, 'MT');
157
158 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
159 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
160 }
161
162 // Retrieve credit note ids
163 $this->invoice->getListIdAvoirFromInvoice();
164
165 // Add external contacts ids
166 if ($contact_list > -1) {
167 $tmparray = $this->invoice->liste_contact(-1, 'external', $contact_list);
168 if (is_array($tmparray)) {
169 $this->invoice->contacts_ids = $tmparray;
170 }
171 $tmparray = $this->invoice->liste_contact(-1, 'internal', $contact_list);
172 if (is_array($tmparray)) {
173 $this->invoice->contacts_ids = $tmparray;
174 }
175 }
176
177 $this->invoice->fetchObjectLinked();
178
179 // Add online_payment_url, copied from order
180 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
181 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $this->invoice->ref);
182
183 return $this->_cleanObjectDatas($this->invoice);
184 }
185
209 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
210 {
211 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
212 throw new RestException(403);
213 }
214
215 $obj_ret = array();
216
217 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
218 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
219
220 // If the internal user must only see his customers, force searching by him
221 $search_sale = 0;
222 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
223 $search_sale = DolibarrApiAccess::$user->id;
224 }
225
226 $sql = "SELECT t.rowid";
227 $sql .= " FROM ".MAIN_DB_PREFIX."facture AS t";
228 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
229 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
230 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
231 if ($socids) {
232 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
233 }
234 // Search on sale representative
235 if ($search_sale && $search_sale != '-1') {
236 if ($search_sale == -2) {
237 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
238 } elseif ($search_sale > 0) {
239 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
240 }
241 }
242 // Filter by status
243 if ($status == 'draft') {
244 $sql .= " AND t.fk_statut IN (0)";
245 }
246 if ($status == 'unpaid') {
247 $sql .= " AND t.fk_statut IN (1)";
248 }
249 if ($status == 'paid') {
250 $sql .= " AND t.fk_statut IN (2)";
251 }
252 if ($status == 'cancelled') {
253 $sql .= " AND t.fk_statut IN (3)";
254 }
255 // Add sql filters
256 if ($sqlfilters) {
257 $errormessage = '';
258 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
259 if ($errormessage) {
260 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
261 }
262 }
263
264 //this query will return total invoices with the filters given
265 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
266
267 $sql .= $this->db->order($sortfield, $sortorder);
268 if ($limit) {
269 if ($page < 0) {
270 $page = 0;
271 }
272 $offset = $limit * $page;
273
274 $sql .= $this->db->plimit($limit + 1, $offset);
275 }
276
277 $result = $this->db->query($sql);
278 if ($result) {
279 $i = 0;
280 $num = $this->db->num_rows($result);
281 $min = min($num, ($limit <= 0 ? $num : $limit));
282 while ($i < $min) {
283 $obj = $this->db->fetch_object($result);
284 $invoice_static = new Facture($this->db);
285 if ($invoice_static->fetch($obj->rowid) > 0) {
286 // Get payment details
287 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
288 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
289 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
290 $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
291
292 // Retrieve credit note ids
293 $invoice_static->getListIdAvoirFromInvoice();
294
295 // Add external contacts ids
296 $tmparray = $invoice_static->liste_contact(-1, 'external', 1);
297 if (is_array($tmparray)) {
298 $invoice_static->contacts_ids = $tmparray;
299 }
300
301 if ($loadlinkedobjects) {
302 // retrieve linked objects
303 $invoice_static->fetchObjectLinked();
304 }
305
306 if (!$withLines) {
307 unset($invoice_static->lines);
308 }
309
310 // Add online_payment_url, copied from order
311 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
312 $invoice_static->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $invoice_static->ref);
313
314 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
315 }
316 $i++;
317 }
318 } else {
319 throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror());
320 }
321
322 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
323 if ($pagination_data) {
324 $totalsResult = $this->db->query($sqlTotals);
325 $total = $this->db->fetch_object($totalsResult)->total;
326
327 $tmp = $obj_ret;
328 $obj_ret = [];
329
330 $obj_ret['data'] = $tmp;
331 $obj_ret['pagination'] = [
332 'total' => (int) $total,
333 'page' => $page, //count starts from 0
334 'page_count' => ceil((int) $total / $limit),
335 'limit' => $limit
336 ];
337 }
338
339 return $obj_ret;
340 }
341
350 public function post($request_data = null)
351 {
352 global $conf;
353 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
354 throw new RestException(403, "Insufficiant rights");
355 }
356
357 if (!is_array($request_data)) {
358 $request_data = array();
359 }
360
361 // Check mandatory fields (not using output, only possible exception is important)
362 $this->_validate($request_data);
363
364 // Check thirdparty validity
365 $socid = (int) $request_data['socid'];
366 $thirdpartytmp = new Societe($this->db);
367 $thirdparty_result = $thirdpartytmp->fetch($socid);
368 if ($thirdparty_result < 1) {
369 throw new RestException(404, 'Thirdparty with id='.$socid.' not found or not allowed');
370 }
371 if (!DolibarrApi::_checkAccessToResource('societe', $thirdpartytmp->id)) {
372 throw new RestException(404, 'Thirdparty with id='.$thirdpartytmp->id.' not found or not allowed');
373 }
374
375 foreach ($request_data as $field => $value) {
376 if ($field === 'caller') {
377 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
378 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
379 continue;
380 }
381 if ($field == 'id') {
382 throw new RestException(400, 'Creating with id field is forbidden');
383 }
384 if ($field == 'entity' && ((int) $value) != ((int) $conf->entity)) {
385 throw new RestException(403, 'Creating with entity='.((int) $value).' MUST be the same entity='.((int) $conf->entity).' as your API user/key belongs to');
386 }
387
388 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
389 }
390 if (!array_key_exists('date', $request_data)) {
391 $this->invoice->date = dol_now();
392 }
393 /* We keep lines as an array
394 if (isset($request_data["lines"])) {
395 $lines = array();
396 foreach ($request_data["lines"] as $line) {
397 array_push($lines, (object) $line);
398 }
399 $this->invoice->lines = $lines;
400 }*/
401
402 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) {
403 throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
404 }
405 return ((int) $this->invoice->id);
406 }
407
422 public function createInvoiceFromOrder($orderid)
423 {
424 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
425
426 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
427 throw new RestException(403);
428 }
429 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
430 throw new RestException(403);
431 }
432 if (empty($orderid)) {
433 throw new RestException(400, 'Order ID is mandatory');
434 }
435 if (!DolibarrApi::_checkAccessToResource('commande', $orderid)) {
436 throw new RestException(403, 'Access not allowed on order for login '.DolibarrApiAccess::$user->login);
437 }
438
439 $order = new Commande($this->db);
440 $result = $order->fetch($orderid);
441 if (!$result) {
442 throw new RestException(404, 'Order not found');
443 }
444
445 // Refuse orders that cannot be billed, to mirror the GUI (order card "CreateBill" button and list mass action):
446 // this excludes draft and canceled orders, as well as orders already classified as billed.
447 if ($order->status <= Commande::STATUS_DRAFT || !empty($order->billed)) {
448 throw new RestException(405, 'Order '.$order->ref.' is not eligible for invoicing: its status does not allow creating an invoice');
449 }
450
451 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
452 if ($result < 0) {
453 throw new RestException(405, $this->invoice->error);
454 }
455 $this->invoice->fetchObjectLinked();
456 return $this->_cleanObjectDatas($this->invoice);
457 }
458
472 public function createInvoiceFromContract($contractid)
473 {
474 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
475
476 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
477 throw new RestException(403);
478 }
479 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
480 throw new RestException(403);
481 }
482 if (empty($contractid)) {
483 throw new RestException(400, 'Contract ID is mandatory');
484 }
485
486 $contract = new Contrat($this->db);
487 $result = $contract->fetch($contractid);
488 if (!$result) {
489 throw new RestException(404, 'Contract not found');
490 }
491
492 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
493 if ($result < 0) {
494 throw new RestException(405, $this->invoice->error);
495 }
496 $this->invoice->fetchObjectLinked();
497 return $this->_cleanObjectDatas($this->invoice);
498 }
499
510 public function getLines($id)
511 {
512 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
513 throw new RestException(403);
514 }
515
516 $result = $this->invoice->fetch($id);
517 if (!$result) {
518 throw new RestException(404, 'Invoice not found');
519 }
520
521 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
522 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
523 }
524 $this->invoice->getLinesArray();
525 $result = array();
526 foreach ($this->invoice->lines as $line) {
527 array_push($result, $this->_cleanObjectDatas($line));
528 }
529 return $result;
530 }
531
548 public function putLine($id, $lineid, $request_data = null)
549 {
550 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
551 throw new RestException(403);
552 }
553
554 $result = $this->invoice->fetch($id);
555 if (!$result) {
556 throw new RestException(404, 'Invoice not found');
557 }
558
559 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
560 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
561 }
562
563 $request_data = (object) $request_data;
564
565 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
566 $request_data->label = sanitizeVal($request_data->label);
567
568 $updateRes = $this->invoice->updateline(
569 $lineid,
570 $request_data->desc,
571 $request_data->subprice,
572 $request_data->qty,
573 $request_data->remise_percent,
574 $request_data->date_start,
575 $request_data->date_end,
576 $request_data->tva_tx,
577 $request_data->localtax1_tx,
578 $request_data->localtax2_tx,
579 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
580 $request_data->info_bits,
581 $request_data->product_type,
582 $request_data->fk_parent_line,
583 0,
584 $request_data->fk_fournprice,
585 $request_data->pa_ht,
586 $request_data->label,
587 $request_data->special_code,
588 $request_data->array_options,
589 $request_data->situation_percent,
590 $request_data->fk_unit,
591 $request_data->multicurrency_subprice,
592 0,
593 $request_data->ref_ext,
594 $request_data->rang
595 );
596
597 if ($updateRes > 0) {
598 $result = $this->get($id);
599 unset($result->line);
600 return $this->_cleanObjectDatas($result);
601 } else {
602 throw new RestException(304, $this->invoice->error);
603 }
604 }
605
623 public function postContact($id, $contactid, $type, $source = 'external', $notrigger = 0)
624 {
625 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
626 throw new RestException(403);
627 }
628
629 // test source
630 if (empty($source)) {
631 throw new RestException(400, 'Source can not be empty');
632 }
633 $sql_distinct_source = "SELECT DISTINCT source";
634 $sql_distinct_source .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
635 $sql_distinct_source .= " WHERE element LIKE 'facture'";
636 $sql_distinct_source .= " AND source is NOT NULL";
637 $sql_distinct_source .= " AND active != 0";
638 $source_result = $this->db->query($sql_distinct_source);
639 $source_array = array();
640
641 if ($source_result) {
642 $num = $this->db->num_rows($source_result);
643 $i = 0;
644 while ($i < $num) {
645 $obj = $this->db->fetch_object($source_result);
646 $source_kind = (string) $obj->source;
647 array_push($source_array, $source_kind);
648 dol_syslog("source_kind=".$source_kind);
649 $i++;
650 }
651 } else {
652 throw new RestException(503, 'Error when retrieving a list of invoice contact sources: '.$this->db->lasterror());
653 }
654 if (!in_array($source, (array) $source_array, true)) {
655 throw new RestException(400, 'Combo of Source='.$source.' and Type='.$type.' not found in dictionary with active invoice contact types');
656 }
657
658 // test type
659 if (empty($type)) {
660 throw new RestException(400, 'type can not be empty');
661 }
662 // variable called type here, but code in dictionary and database
663 $sql_distinct_type = "SELECT DISTINCT code";
664 $sql_distinct_type .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
665 $sql_distinct_type .= " WHERE element LIKE 'facture'";
666 $sql_distinct_type .= " AND source='".$this->db->escape($source)."'";
667 $sql_distinct_type .= " AND code is NOT NULL";
668 $sql_distinct_type .= " AND active != 0";
669 $type_result = $this->db->query($sql_distinct_type);
670 $type_array = array();
671
672 if ($type_result) {
673 $num = $this->db->num_rows($type_result);
674 $i = 0;
675 while ($i < $num) {
676 $obj = $this->db->fetch_object($type_result);
677 // variable called type here, but code in dictionary and database
678 $type_kind = (string) $obj->code;
679 array_push($type_array, $type_kind);
680 dol_syslog("type_kind=".$type_kind);
681 $i++;
682 }
683 } else {
684 throw new RestException(503, 'Error when retrieving a list of invoice contact types: '.$this->db->lasterror());
685 }
686 if (!in_array($type, (array) $type_array, true)) {
687 throw new RestException(400, 'Combo of Type='.$type.' and Source='.$source.' not found in dictionary with active invoice contact types');
688 }
689
690 // tests done, let's get it
691 $result = $this->invoice->fetch($id);
692 if (!$result) {
693 throw new RestException(404, 'Invoice not found');
694 }
695 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
696 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
697 }
698
699 $result = $this->invoice->add_contact($contactid, $type, $source, $notrigger);
700
701 if ($result == 0) {
702 throw new RestException(400, 'Already exists: Contact='.$contactid.' is already linked to the invoice='.$id.' as source='.$source.' and type='.$type);
703 } elseif ($result == -1) {
704 throw new RestException(400, 'Wrong contact='.$contactid);
705 } elseif ($result == -2) {
706 throw new RestException(400, 'Wrong type='.$type);
707 } elseif ($result == -3) {
708 throw new RestException(400, 'Not allowed contacts');
709 } elseif ($result == -4) {
710 throw new RestException(400, 'ErrorCommercialNotAllowedForThirdparty');
711 } elseif ($result == -5) {
712 throw new RestException(400, 'Trigger failed');
713 } elseif ($result == -6) {
714 throw new RestException(400, 'DB_ERROR_RECORD_ALREADY_EXISTS');
715 } elseif ($result == -7) {
716 throw new RestException(400, 'Some other error');
717 }
718
719 if (!$result) {
720 throw new RestException(500, 'Error when added the contact');
721 }
722
723 return array(
724 'success' => array(
725 'code' => 200,
726 'message' => 'Contact='.$contactid.' linked to the invoice='.$id.' as '.$source.' '.$type
727 )
728 );
729 }
730
744 public function getContacts($id, $type = '')
745 {
746 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
747 throw new RestException(403);
748 }
749
750 $result = $this->invoice->fetch($id);
751 if (!$result) {
752 throw new RestException(404, 'Invoice not found');
753 }
754
755 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
756 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
757 }
758
759 $contacts = $this->invoice->liste_contact(-1, 'external', 0, $type);
760 $socpeoples = $this->invoice->liste_contact(-1, 'internal', 0, $type);
761
762 $contacts = array_merge($contacts, $socpeoples);
763
764 return $contacts;
765 }
766
781 public function deleteContact($id, $contactid, $type)
782 {
783 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
784 throw new RestException(403);
785 }
786
787 $result = $this->invoice->fetch($id);
788
789 if (!$result) {
790 throw new RestException(404, 'Invoice not found');
791 }
792
793 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
794 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
795 }
796
797 $contacts = $this->invoice->liste_contact();
798
799 foreach ($contacts as $contact) {
800 if ($contact['id'] == $contactid && $contact['code'] == $type) {
801 $result = $this->invoice->delete_contact($contact['rowid']);
802
803 if (!$result) {
804 throw new RestException(500, 'Error when deleted the contact');
805 }
806 }
807 }
808
809 return $this->_cleanObjectDatas($this->invoice);
810 }
811
826 public function deleteLine($id, $lineid)
827 {
828 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
829 throw new RestException(403);
830 }
831 if (empty($lineid)) {
832 throw new RestException(400, 'Line ID is mandatory');
833 }
834
835 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
836 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
837 }
838
839 $result = $this->invoice->fetch($id);
840 if (!$result) {
841 throw new RestException(404, 'Invoice not found');
842 }
843 if ($this->invoice->status != 0) {
844 throw new RestException(403, 'Invoice not in Draft Status : '.$this->invoice->getLibStatut(1));
845 }
846
847 $updateRes = $this->invoice->deleteLine($lineid, $id);
848 if ($updateRes > 0) {
849 return $this->get($id);
850 } else {
851 throw new RestException(405, $this->invoice->error);
852 }
853 }
854
864 public function put($id, $request_data = null)
865 {
866 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
867 throw new RestException(403);
868 }
869 if ($id == 0) {
870 throw new RestException(400, 'No invoice with id=0 can exist');
871 }
872 $result = $this->invoice->fetch($id);
873 if (!$result) {
874 throw new RestException(404, 'Invoice not found');
875 }
876
877 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
878 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
879 }
880
881 foreach ($request_data as $field => $value) {
882 if ($field == 'id') {
883 continue;
884 }
885 if ($field === 'caller') {
886 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
887 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
888 continue;
889 }
890 if ($field == 'array_options' && is_array($value)) {
891 foreach ($value as $index => $val) {
892 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
893 }
894 continue;
895 }
896
897 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
898
899 // If cond reglement => update date lim reglement
900 if ($field == 'cond_reglement_id') {
901 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
902 }
903 }
904
905 // update bank account
906 if (!empty($this->invoice->fk_account)) {
907 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
908 throw new RestException(400, $this->invoice->error);
909 }
910 }
911
912 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
913 return $this->get($id);
914 } else {
915 throw new RestException(500, $this->invoice->error);
916 }
917 }
918
927 public function delete($id)
928 {
929 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
930 throw new RestException(403);
931 }
932 if ($id == 0) {
933 throw new RestException(400, 'No invoice with id=0 can exist');
934 }
935 $result = $this->invoice->fetch($id);
936 if (!$result) {
937 throw new RestException(404, 'Invoice not found');
938 }
939
940 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
941 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
942 }
943
944 $result = $this->invoice->delete(DolibarrApiAccess::$user);
945 if ($result < 0) {
946 throw new RestException(500, 'Error when deleting invoice');
947 } elseif ($result == 0) {
948 throw new RestException(403, 'Invoice not erasable');
949 }
950
951 return array(
952 'success' => array(
953 'code' => 200,
954 'message' => 'Invoice deleted'
955 )
956 );
957 }
958
984 public function postLine($id, $request_data = null)
985 {
986 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
987 throw new RestException(403);
988 }
989
990 $result = $this->invoice->fetch($id);
991 if (!$result) {
992 throw new RestException(404, 'Invoice not found');
993 }
994
995 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
996 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
997 }
998
999 $request_data = (object) $request_data;
1000
1001 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
1002 $request_data->label = sanitizeVal($request_data->label);
1003
1004 // Reset fk_parent_line for no child products and special product
1005 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
1006 $request_data->fk_parent_line = 0;
1007 }
1008
1009 // calculate pa_ht
1010 $marginInfos = getMarginInfos($request_data->subprice, $request_data->remise_percent, $request_data->tva_tx, $request_data->localtax1_tx, $request_data->localtax2_tx, $request_data->fk_fournprice, $request_data->pa_ht);
1011 $pa_ht = $marginInfos[0];
1012
1013 $updateRes = $this->invoice->addline(
1014 $request_data->desc,
1015 $request_data->subprice,
1016 $request_data->qty,
1017 $request_data->tva_tx,
1018 $request_data->localtax1_tx,
1019 $request_data->localtax2_tx,
1020 $request_data->fk_product,
1021 $request_data->remise_percent,
1022 $request_data->date_start,
1023 $request_data->date_end,
1024 $request_data->fk_code_ventilation,
1025 $request_data->info_bits,
1026 $request_data->fk_remise_except,
1027 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
1028 $request_data->subprice,
1029 $request_data->product_type,
1030 $request_data->rang,
1031 $request_data->special_code,
1032 $request_data->origin,
1033 $request_data->origin_id,
1034 $request_data->fk_parent_line,
1035 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
1036 $pa_ht,
1037 $request_data->label,
1038 $request_data->array_options,
1039 $request_data->situation_percent,
1040 $request_data->fk_prev_id,
1041 $request_data->fk_unit,
1042 0,
1043 $request_data->ref_ext
1044 );
1045
1046 if ($updateRes < 0) {
1047 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
1048 }
1049
1050 return $updateRes;
1051 }
1052
1071 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
1072 {
1073 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1074 throw new RestException(403);
1075 }
1076 $result = $this->invoice->fetch($id);
1077 if (!$result) {
1078 throw new RestException(404, 'Invoice not found');
1079 }
1080
1081 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1082 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1083 }
1084
1085 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
1086 if ($result < 0) {
1087 throw new RestException(500, 'Error : '.$this->invoice->error);
1088 }
1089
1090 $result = $this->invoice->fetch($id);
1091 if (!$result) {
1092 throw new RestException(404, 'Invoice not found');
1093 }
1094
1095 // test already done
1096 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1097 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1098 // }
1099
1100 return $this->_cleanObjectDatas($this->invoice);
1101 }
1102
1103
1104
1119 public function settodraft($id, $idwarehouse = -1)
1120 {
1121 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1122 throw new RestException(403);
1123 }
1124 $result = $this->invoice->fetch($id);
1125 if (!$result) {
1126 throw new RestException(404, 'Invoice not found');
1127 }
1128
1129 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1130 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1131 }
1132
1133 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
1134 if ($result == 0) {
1135 throw new RestException(304, 'Nothing done.');
1136 }
1137 if ($result < 0) {
1138 throw new RestException(500, 'Error : '.$this->invoice->error);
1139 }
1140
1141 $result = $this->invoice->fetch($id);
1142 if (!$result) {
1143 throw new RestException(404, 'Invoice not found');
1144 }
1145
1146 return $this->_cleanObjectDatas($this->invoice);
1147 }
1148
1149
1167 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1168 {
1169 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1170 throw new RestException(403);
1171 }
1172 $result = $this->invoice->fetch($id);
1173 if (!$result) {
1174 throw new RestException(404, 'Invoice not found');
1175 }
1176
1177 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1178 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1179 }
1180
1181 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
1182 if ($result == 0) {
1183 throw new RestException(304, 'Error nothing done. May be object is already validated');
1184 }
1185 if ($result < 0) {
1186 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
1187 }
1188
1189 $result = $this->invoice->fetch($id);
1190 if (!$result) {
1191 throw new RestException(404, 'Invoice not found');
1192 }
1193
1194 // test already done
1195 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1196 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1197 // }
1198
1199 // copy from order
1200 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1201 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $this->invoice->ref);
1202
1203 return $this->_cleanObjectDatas($this->invoice);
1204 }
1205
1221 public function settopaid($id, $close_code = '', $close_note = '')
1222 {
1223 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1224 throw new RestException(403);
1225 }
1226 $result = $this->invoice->fetch($id);
1227 if (!$result) {
1228 throw new RestException(404, 'Invoice not found');
1229 }
1230
1231 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1232 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1233 }
1234
1235 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1236 if ($result == 0) {
1237 throw new RestException(304, 'Error nothing done. May be object is already validated');
1238 }
1239 if ($result < 0) {
1240 throw new RestException(500, 'Error : '.$this->invoice->error);
1241 }
1242
1243
1244 $result = $this->invoice->fetch($id);
1245 if (!$result) {
1246 throw new RestException(404, 'Invoice not found');
1247 }
1248
1249 // test already done
1250 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1251 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1252 // }
1253
1254 return $this->_cleanObjectDatas($this->invoice);
1255 }
1256
1257
1271 public function settounpaid($id)
1272 {
1273 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1274 throw new RestException(403);
1275 }
1276 $result = $this->invoice->fetch($id);
1277 if (!$result) {
1278 throw new RestException(404, 'Invoice not found');
1279 }
1280
1281 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1282 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1283 }
1284
1285 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1286 if ($result == 0) {
1287 throw new RestException(304, 'Nothing done');
1288 }
1289 if ($result < 0) {
1290 throw new RestException(500, 'Error : '.$this->invoice->error);
1291 }
1292
1293
1294 $result = $this->invoice->fetch($id);
1295 if (!$result) {
1296 throw new RestException(404, 'Invoice not found');
1297 }
1298
1299 // test already done
1300 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1301 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1302 // }
1303
1304 return $this->_cleanObjectDatas($this->invoice);
1305 }
1306
1315 public function getDiscount($id)
1316 {
1317 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1318
1319 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1320 throw new RestException(403);
1321 }
1322
1323 $result = $this->invoice->fetch($id);
1324 if (!$result) {
1325 throw new RestException(404, 'Invoice not found');
1326 }
1327
1328 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1329 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1330 }
1331
1332 $discountcheck = new DiscountAbsolute($this->db);
1333 $result = $discountcheck->fetch(0, $this->invoice->id);
1334
1335 if ($result == 0) {
1336 throw new RestException(404, 'Discount not found');
1337 }
1338 if ($result < 0) {
1339 throw new RestException(500, $discountcheck->error);
1340 }
1341
1342 return parent::_cleanObjectDatas($discountcheck);
1343 }
1344
1359 {
1360 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1361
1362 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1363 throw new RestException(403);
1364 }
1365
1366 $result = $this->invoice->fetch($id);
1367 if (!$result) {
1368 throw new RestException(404, 'Invoice not found');
1369 }
1370
1371 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1372 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1373 }
1374
1375 if ($this->invoice->paye) { // TODO Replace by a test on status
1376 throw new RestException(500, 'Alreay paid');
1377 }
1378
1379 $this->invoice->fetch($id);
1380 $this->invoice->fetch_thirdparty();
1381
1382 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1383 $discountcheck = new DiscountAbsolute($this->db);
1384 $result = $discountcheck->fetch(0, $this->invoice->id);
1385
1386 $canconvert = 0;
1387 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1388 $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
1389 }
1390 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1391 $canconvert = 1; // we can convert credit note into discount if credit note is not paid back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
1392 }
1393 if ($canconvert) {
1394 $this->db->begin();
1395
1396 $amount_ht = $amount_tva = $amount_ttc = array();
1397 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1398 '
1399 @phan-var-force array<string,float> $amount_ht
1400 @phan-var-force array<string,float> $amount_tva
1401 @phan-var-force array<string,float> $amount_ttc
1402 @phan-var-force array<string,float> $multicurrency_amount_ht
1403 @phan-var-force array<string,float> $multicurrency_amount_tva
1404 @phan-var-force array<string,float> $multicurrency_amount_ttc
1405 ';
1406
1407 // Loop on each vat rate
1408 $i = 0;
1409 foreach ($this->invoice->lines as $line) {
1410 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1411 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1412 $amount_ht[$line->tva_tx] = 0.0;
1413 $amount_tva[$line->tva_tx] = 0.0;
1414 $amount_ttc[$line->tva_tx] = 0.0;
1415 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1416 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1417 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1418 }
1419 // no need to create discount if amount is null
1420 $amount_ht[$line->tva_tx] += $line->total_ht;
1421 $amount_tva[$line->tva_tx] += $line->total_tva;
1422 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1423 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1424 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1425 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1426 $i++;
1427 }
1428 }
1429
1430 // Insert one discount by VAT rate category
1431 $discount = new DiscountAbsolute($this->db);
1432 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1433 $discount->description = '(CREDIT_NOTE)';
1434 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1435 $discount->description = '(DEPOSIT)';
1436 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1437 $discount->description = '(EXCESS RECEIVED)';
1438 } else {
1439 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1440 }
1441
1442 $discount->fk_soc = $this->invoice->socid;
1443 $discount->socid = $this->invoice->socid;
1444 $discount->fk_facture_source = $this->invoice->id;
1445
1446 $error = 0;
1447
1448 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1449 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1450
1451 // Total payments
1452 $sql = 'SELECT SUM(pf.amount) as total_payments';
1453 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1454 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1455 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1456 $sql .= ' AND pf.fk_paiement = p.rowid';
1457 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1458 $resql = $this->db->query($sql);
1459 if (!$resql) {
1460 dol_print_error($this->db);
1461 }
1462
1463 $res = $this->db->fetch_object($resql);
1464 $total_payments = $res->total_payments;
1465
1466 // Total credit note and deposit
1467 $total_creditnote_and_deposit = 0;
1468 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1469 $sql .= " re.description, re.fk_facture_source";
1470 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1471 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1472 $resql = $this->db->query($sql);
1473 if (!empty($resql)) {
1474 while ($obj = $this->db->fetch_object($resql)) {
1475 $total_creditnote_and_deposit += $obj->amount_ttc;
1476 }
1477 } else {
1478 dol_print_error($this->db);
1479 }
1480
1481 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1482 $discount->total_ht = $discount->total_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1483 $discount->amount_tva = 0;
1484 $discount->total_tva = 0;
1485 $discount->tva_tx = 0;
1486
1487 $result = $discount->create(DolibarrApiAccess::$user);
1488 if ($result < 0) {
1489 $error++;
1490 }
1491 }
1492 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1493 foreach ($amount_ht as $tva_tx => $xxx) {
1494 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1495 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1496 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1497 $discount->total_ht = abs($amount_ht[$tva_tx]);
1498 $discount->total_tva = abs($amount_tva[$tva_tx]);
1499 $discount->total_ttc = abs($amount_ttc[$tva_tx]);
1500 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1501 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1502 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1503 $discount->multicurrency_total_ht = abs($multicurrency_amount_ht[$tva_tx]);
1504 $discount->multicurrency_total_tva = abs($multicurrency_amount_tva[$tva_tx]);
1505 $discount->multicurrency_total_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1506 $discount->tva_tx = abs((float) $tva_tx);
1507
1508 $result = $discount->create(DolibarrApiAccess::$user);
1509 if ($result < 0) {
1510 $error++;
1511 break;
1512 }
1513 }
1514 }
1515
1516 if (empty($error)) {
1517 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1518 // Set the invoice as paid
1519 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1520 if ($result >= 0) {
1521 $this->db->commit();
1522 } else {
1523 $this->db->rollback();
1524 throw new RestException(500, 'Could not set paid');
1525 }
1526 } else {
1527 $this->db->commit();
1528 }
1529 } else {
1530 $this->db->rollback();
1531 throw new RestException(500, 'Discount creation error');
1532 }
1533 }
1534
1535 return $this->_cleanObjectDatas($this->invoice);
1536 }
1537
1554 public function useDiscount($id, $discountid)
1555 {
1556 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1557 throw new RestException(403);
1558 }
1559 if (empty($id)) {
1560 throw new RestException(400, 'Invoice ID is mandatory');
1561 }
1562 if (empty($discountid)) {
1563 throw new RestException(400, 'Discount ID is mandatory');
1564 }
1565
1566 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1567 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1568 }
1569
1570 $result = $this->invoice->fetch($id);
1571 if (!$result) {
1572 throw new RestException(404, 'Invoice not found');
1573 }
1574
1575 $result = $this->invoice->insert_discount($discountid);
1576 if ($result < 0) {
1577 throw new RestException(405, $this->invoice->error);
1578 }
1579
1580 return $result;
1581 }
1582
1599 public function useCreditNote($id, $discountid)
1600 {
1601 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1602
1603 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1604 throw new RestException(403);
1605 }
1606 if (empty($id)) {
1607 throw new RestException(400, 'Invoice ID is mandatory');
1608 }
1609 if (empty($discountid)) {
1610 throw new RestException(400, 'Credit ID is mandatory');
1611 }
1612
1613 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1614 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1615 }
1616 $discount = new DiscountAbsolute($this->db);
1617 $result = $discount->fetch($discountid);
1618 if (!$result) {
1619 throw new RestException(404, 'Credit not found');
1620 }
1621
1622 $result = $discount->link_to_invoice(0, $id);
1623 if ($result < 0) {
1624 throw new RestException(405, $discount->error);
1625 }
1626
1627 return $result;
1628 }
1629
1645 public function getPayments($id)
1646 {
1647 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1648 throw new RestException(403);
1649 }
1650 if (empty($id)) {
1651 throw new RestException(400, 'Invoice ID is mandatory');
1652 }
1653
1654 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1655 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1656 }
1657
1658 $result = $this->invoice->fetch($id);
1659 if (!$result) {
1660 throw new RestException(404, 'Invoice not found');
1661 }
1662
1663 $result = $this->invoice->getListOfPayments();
1664 if (!is_array($result) && $result < 0) {
1665 throw new RestException(405, $this->invoice->error);
1666 }
1667
1668 return $result;
1669 }
1670
1671
1693 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1694 {
1695 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1696
1697 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1698 throw new RestException(403);
1699 }
1700 if (empty($id)) {
1701 throw new RestException(400, 'Invoice ID is mandatory');
1702 }
1703
1704 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1705 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1706 }
1707
1708 if (isModEnabled("bank")) {
1709 if (empty($accountid)) {
1710 throw new RestException(400, 'Account ID is mandatory');
1711 }
1712 }
1713
1714 if (empty($paymentid)) {
1715 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1716 }
1717
1718
1719 $result = $this->invoice->fetch($id);
1720 if (!$result) {
1721 throw new RestException(404, 'Invoice not found');
1722 }
1723
1724 // Calculate amount to pay
1725 $totalpaid = $this->invoice->getSommePaiement();
1726 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1727 $totaldeposits = $this->invoice->getSumDepositsUsed();
1728 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1729
1730 $this->db->begin();
1731
1732 $amounts = array();
1733 $multicurrency_amounts = array();
1734
1735 // Clean parameters amount if payment is for a credit note
1736 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1737 $resteapayer = price2num($resteapayer, 'MT');
1738 $amounts[$id] = (float) price2num(-1 * abs((float) $resteapayer), 'MT');
1739 // Multicurrency
1740 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1741 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1742 } else {
1743 $resteapayer = price2num($resteapayer, 'MT');
1744 $amounts[$id] = (float) $resteapayer;
1745 // Multicurrency
1746 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1747 $multicurrency_amounts[$id] = (float) $newvalue;
1748 }
1749
1750 // Creation of payment line
1751 $paymentobj = new Paiement($this->db);
1752 if (is_numeric($datepaye)) {
1753 $paymentobj->datepaye = $datepaye;
1754 } else {
1755 $paymentobj->datepaye = dol_stringtotime($datepaye);
1756 }
1757 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1758 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1759 $paymentobj->paiementid = $paymentid;
1760 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1761 $paymentobj->num_payment = $num_payment;
1762 $paymentobj->note_private = $comment;
1763
1764 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1765 if ($payment_id < 0) {
1766 $this->db->rollback();
1767 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1768 }
1769
1770 if (isModEnabled("bank")) {
1771 $label = '(CustomerInvoicePayment)';
1772
1773 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1774 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1775 }
1776 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1777 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1778 }
1779 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1780 if ($result < 0) {
1781 $this->db->rollback();
1782 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1783 }
1784 }
1785
1786 $this->db->commit();
1787
1788 return $payment_id;
1789 }
1790
1819 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1820 {
1821 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1822
1823 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1824 throw new RestException(403);
1825 }
1826 foreach ($arrayofamounts as $id => $amount) {
1827 if (empty($id)) {
1828 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1829 }
1830 if (!DolibarrApi::_checkAccessToResource('facture', (int) $id)) {
1831 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1832 }
1833 }
1834
1835 if (isModEnabled("bank")) {
1836 if (empty($accountid)) {
1837 throw new RestException(400, 'Account ID is mandatory');
1838 }
1839 }
1840 if (empty($paymentid)) {
1841 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1842 }
1843
1844 $this->db->begin();
1845
1846 $amounts = array();
1847 $multicurrency_amounts = array();
1848
1849 // Loop on each invoice to pay
1850 foreach ($arrayofamounts as $id => $amountarray) {
1851 $result = $this->invoice->fetch((int) $id);
1852 if (!$result) {
1853 $this->db->rollback();
1854 throw new RestException(404, 'Invoice ID '.$id.' not found');
1855 }
1856
1857 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1858 $this->db->rollback();
1859 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1860 }
1861
1862 $is_multicurrency = 0;
1863 $total_ttc = $this->invoice->total_ttc;
1864
1865 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1866 $is_multicurrency = 1;
1867 $total_ttc = $this->invoice->multicurrency_total_ttc;
1868 }
1869
1870 // Calculate amount to pay
1871 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1872 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1873 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1874 $remainstopay = $amount = (float) price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1875
1876 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1877 $amount = (float) price2num($amountarray["amount"], 'MT');
1878 }
1879
1880 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1881 $amount = (float) price2num($amountarray["multicurrency_amount"], 'MT');
1882 }
1883
1884 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
1885 $this->db->rollback();
1886 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1887 }
1888
1889 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1890 $amount = (float) price2num(-1 * abs((float) $amount), 'MT');
1891 }
1892
1893 if ($is_multicurrency) {
1894 $amounts[$id] = null;
1895 // Multicurrency
1896 $multicurrency_amounts[$id] = (float) $amount;
1897 } else {
1898 $amounts[$id] = (float) $amount;
1899 // Multicurrency
1900 $multicurrency_amounts[$id] = null;
1901 }
1902 }
1903
1904 // Creation of payment line
1905 $paymentobj = new Paiement($this->db);
1906 if (is_numeric($datepaye)) {
1907 $paymentobj->datepaye = $datepaye;
1908 } else {
1909 $paymentobj->datepaye = dol_stringtotime($datepaye);
1910 }
1911 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1912 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1913 $paymentobj->paiementid = $paymentid;
1914 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1915 $paymentobj->num_payment = $num_payment;
1916 $paymentobj->note_private = $comment;
1917 $paymentobj->ref_ext = $ref_ext;
1918 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1919 if ($payment_id < 0) {
1920 $this->db->rollback();
1921 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1922 }
1923 if (isModEnabled("bank")) {
1924 $label = '(CustomerInvoicePayment)';
1925 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1926 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1927 }
1928 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1929 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1930 }
1931 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1932 if ($result < 0) {
1933 $this->db->rollback();
1934 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1935 }
1936 }
1937
1938 $this->db->commit();
1939
1940 return $payment_id;
1941 }
1942
1959 public function putPayment($id, $num_payment = '')
1960 {
1961 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1962
1963 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1964 throw new RestException(403);
1965 }
1966 if (empty($id)) {
1967 throw new RestException(400, 'Payment ID is mandatory');
1968 }
1969
1970 $paymentobj = new Paiement($this->db);
1971 $result = $paymentobj->fetch($id);
1972
1973 if (!$result) {
1974 throw new RestException(404, 'Payment not found');
1975 }
1976
1977 if (!empty($num_payment)) {
1978 $result = $paymentobj->update_num($num_payment);
1979 if ($result < 0) {
1980 throw new RestException(500, 'Error when updating the payment num');
1981 }
1982 }
1983
1984 return [
1985 'success' => [
1986 'code' => 200,
1987 'message' => 'Payment updated'
1988 ]
1989 ];
1990 }
1991
1992 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2002 protected function _cleanObjectDatas($object)
2003 {
2004 // phpcs:enable
2005 $object = parent::_cleanObjectDatas($object);
2006
2007 unset($object->note);
2008 unset($object->address);
2009 unset($object->barcode_type);
2010 unset($object->barcode_type_code);
2011 unset($object->barcode_type_label);
2012 unset($object->barcode_type_coder);
2013 unset($object->canvas);
2014
2015 return $object;
2016 }
2017
2026 private function _validate($data)
2027 {
2028 if ($data === null) {
2029 $data = array();
2030 }
2031 $invoice = array();
2032 foreach (Invoices::$FIELDS as $field) {
2033 if (!isset($data[$field])) {
2034 throw new RestException(400, "$field field missing");
2035 }
2036 $invoice[$field] = $data[$field];
2037 }
2038 return $invoice;
2039 }
2040
2041
2055 public function getTemplateInvoice($id, $contact_list = 1)
2056 {
2057 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
2058 }
2059
2060
2086 public function indexTemplateInvoices($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
2087 {
2088 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2089 throw new RestException(403);
2090 }
2091
2092 $obj_ret = array();
2093
2094 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
2095 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
2096
2097
2098 // If the internal user must only see his customers, force searching by him
2099 $search_sale = 0;
2100 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
2101 $search_sale = DolibarrApiAccess::$user->id;
2102 }
2103
2104 $sql = "SELECT t.rowid";
2105 $sql .= " FROM ".MAIN_DB_PREFIX."facture_rec AS t";
2106 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
2107 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_rec_extrafields AS ef ON (ef.fk_object = t.rowid)";
2108 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
2109 if ($socids) {
2110 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
2111 }
2112
2113 // Search on sale representative
2114 if ($search_sale && $search_sale != '-1') {
2115 if ($search_sale == -2) {
2116 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux AS sc WHERE sc.fk_soc = t.fk_soc)";
2117 } elseif ($search_sale > 0) {
2118 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux AS sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
2119 }
2120 }
2121
2122 // Filter by status
2123 if ($status == 'active') {
2124 $sql .= " AND t.suspended = 0 AND t.frequency IS NOT NULL";
2125 }
2126 if ($status == 'suspended') {
2127 $sql .= " AND t.suspended = 1 AND t.frequency IS NOT NULL";
2128 }
2129 if ($status == 'draft') {
2130 $sql .= " AND t.frequency IS NULL";
2131 }
2132 // add sql filters
2133 if ($sqlfilters) {
2134 $errormessage = '';
2135 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
2136 if ($errormessage) {
2137 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
2138 }
2139 }
2140
2141 //this query will return total template invoices with the filters given
2142 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
2143
2144 $sql .= $this->db->order($sortfield, $sortorder);
2145 if ($limit) {
2146 if ($page < 0) {
2147 $page = 0;
2148 }
2149 $offset = $limit * $page;
2150
2151 $sql .= $this->db->plimit($limit + 1, $offset);
2152 }
2153
2154 $result = $this->db->query($sql);
2155 if ($result) {
2156 $i = 0;
2157 $num = $this->db->num_rows($result);
2158 $min = min($num, ($limit <= 0 ? $num : $limit));
2159 while ($i < $min) {
2160 $obj = $this->db->fetch_object($result);
2161 $factureRec = new FactureRec($this->db);
2162 if ($factureRec->fetch($obj->rowid) > 0) {
2163 if ($loadlinkedobjects) {
2164 // retrieve linked objects
2165 $factureRec->fetchObjectLinked();
2166 }
2167
2168 if (!$withLines) {
2169 unset($factureRec->lines);
2170 }
2171
2172 $obj_ret[] = $this->_filterObjectProperties($this->_cleanTemplateObjectDatas($factureRec), $properties);
2173 }
2174 $i++;
2175 }
2176 } else {
2177 throw new RestException(503, 'Error when retrieving recurring invoice templates: '.$this->db->lasterror());
2178 }
2179
2180 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
2181 if ($pagination_data) {
2182 $totalsResult = $this->db->query($sqlTotals);
2183 $total = $this->db->fetch_object($totalsResult)->total;
2184
2185 $tmp = $obj_ret;
2186 $obj_ret = array();
2187
2188 $obj_ret['data'] = $tmp;
2189 $obj_ret['pagination'] = array(
2190 'total' => (int) $total,
2191 'page' => $page,
2192 'page_count' => ceil((int) $total / $limit),
2193 'limit' => $limit
2194 );
2195 }
2196
2197 return $obj_ret;
2198 }
2199
2213 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
2214 {
2215 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2216 throw new RestException(403);
2217 }
2218
2219 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
2220 if (!$result) {
2221 throw new RestException(404, 'Template invoice not found');
2222 }
2223
2224 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
2225 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2226 }
2227
2228 // Add external contacts ids
2229 if ($contact_list > -1) {
2230 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
2231 if (is_array($tmparray)) {
2232 $this->template_invoice->contacts_ids = $tmparray;
2233 }
2234 }
2235
2236 $this->template_invoice->fetchObjectLinked();
2237 return $this->_cleanTemplateObjectDatas($this->template_invoice);
2238 }
2239
2240
2241 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2249 {
2250 // phpcs:enable
2251 $object = parent::_cleanObjectDatas($object);
2252
2253 unset($object->note);
2254 unset($object->address);
2255 unset($object->barcode_type);
2256 unset($object->barcode_type_code);
2257 unset($object->barcode_type_label);
2258 unset($object->barcode_type_coder);
2259 unset($object->canvas);
2260
2261 return $object;
2262 }
2263}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage customers orders.
const STATUS_DRAFT
Draft status.
Class to manage absolute discounts.
Class for API REST v1.
Definition api.class.php:33
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:98
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoice templates.
putPayment($id, $num_payment='')
Update a payment.
addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0)
Adds a contact to an invoice.
indexTemplateInvoices($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false, $loadlinkedobjects=0, $withLines=true)
List template invoices.
createInvoiceFromOrder($orderid)
Create an invoice using an existing order.
markAsCreditAvailable($id)
Create a discount (credit available) for a credit note or a deposit.
getDiscount($id)
Get discount from invoice.
__construct()
Constructor.
put($id, $request_data=null)
Update invoice.
validate($id, $force_number='', $idwarehouse=0, $notrigger=0)
Validate an invoice.
getContacts($id, $type='')
Get contacts of given invoice.
getByRefExt($ref_ext, $contact_list=1)
Get properties of an invoice object by ref_ext.
_fetch($id, $ref='', $ref_ext='', $contact_list=1)
Get properties of an invoice object.
getByRef($ref, $contact_list=1)
Get properties of an invoice object by ref.
getPayments($id)
Get list of payments of a given invoice.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
post($request_data=null)
Create invoice object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false, $loadlinkedobjects=0, $withLines=true)
List invoices.
useDiscount($id, $discountid)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount.
settounpaid($id)
Sets an invoice as unpaid.
getTemplateInvoice($id, $contact_list=1)
Get properties of a template invoice object.
putLine($id, $lineid, $request_data=null)
Update a line to a given invoice.
getLines($id)
Get lines of an invoice.
useCreditNote($id, $discountid)
Add an available credit note discount to payments of an existing invoice.
createInvoiceFromContract($contractid)
Create an invoice using a contract.
addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='', $ref_ext='', $accepthigherpayment=false)
Add a payment to pay partially or completely one or several invoices.
postContact($id, $contactid, $type, $source='external', $notrigger=0)
Add a contact type of given invoice.
_cleanTemplateObjectDatas($object)
Clean sensible object datas.
deleteContact($id, $contactid, $type)
Delete a contact type of given invoice.
postLine($id, $request_data=null)
Add a line to a given invoice.
_fetchTemplateInvoice($id, $ref='', $ref_ext='', $contact_list=1)
Get properties of an invoice object.
_validate($data)
Validate fields before create or update object.
addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='')
Add payment line to a specific invoice with the remain to pay as amount.
settopaid($id, $close_code='', $close_note='')
Sets an invoice as paid.
settodraft($id, $idwarehouse=-1)
Sets an invoice as draft.
deleteLine($id, $lineid)
Deletes a line of a given invoice.
Class to manage payments of customer invoices.
Class to manage third parties objects (customers, suppliers, prospects...)
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:434
dol_now($mode='gmt')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.