dolibarr 24.0.1
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-2026 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
36class Invoices extends DolibarrApi
37{
41 public static $FIELDS = array(
42 'socid',
43 );
44
48 private $invoice;
49
53 private $template_invoice;
54
55
59 public function __construct()
60 {
61 global $db;
62 $this->db = $db;
63 $this->invoice = new Facture($this->db);
64 $this->template_invoice = new FactureRec($this->db);
65 }
66
82 public function get($id, $contact_list = 1, $properties = '', $withLines = true)
83 {
84 $invoice = $this->_fetch($id, '', '', $contact_list);
85
86 if (!$withLines) {
87 unset($invoice->lines);
88 }
89
90 return $this->_filterObjectProperties($invoice, $properties);
91 }
92
108 public function getByRef($ref, $contact_list = 1)
109 {
110 return $this->_fetch(0, $ref, '', $contact_list);
111 }
112
128 public function getByRefExt($ref_ext, $contact_list = 1)
129 {
130 return $this->_fetch(0, '', $ref_ext, $contact_list);
131 }
132
146 private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
147 {
148 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
149 throw new RestException(403);
150 }
151 if (empty($id) && empty($ref) && empty($ref_ext)) {
152 throw new RestException(400, 'No invoice can be found with no criteria');
153 }
154 $result = $this->invoice->fetch($id, $ref, $ref_ext);
155 if (!$result) {
156 throw new RestException(404, 'Invoice not found');
157 }
158
159 // Get payment details
160 $this->invoice->totalpaid = $this->invoice->getSommePaiement();
161 $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
162 $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed();
163 $this->invoice->remaintopay = price2num($this->invoice->total_ttc - $this->invoice->totalpaid - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits, 'MT');
164
165 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
166 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
167 }
168
169 // Retrieve credit note ids
170 $this->invoice->getListIdAvoirFromInvoice();
171
172 // Add external contacts ids
173 if ($contact_list > -1) {
174 $tmparray = $this->invoice->liste_contact(-1, 'external', $contact_list);
175 if (is_array($tmparray)) {
176 $this->invoice->contacts_ids = $tmparray;
177 }
178 $tmparray = $this->invoice->liste_contact(-1, 'internal', $contact_list);
179 if (is_array($tmparray)) {
180 $this->invoice->contacts_ids = $tmparray;
181 }
182 }
183
184 $this->invoice->fetchObjectLinked();
185
186 // Add online_payment_url, copied from order
187 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
188 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', (string) $this->invoice->ref);
189
190 return $this->_cleanObjectDatas($this->invoice);
191 }
192
218 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
219 {
220 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
221 throw new RestException(403);
222 }
223
224 $obj_ret = array();
225
226 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
227 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
228
229 // If the internal user must only see his customers, force searching by him
230 $search_sale = 0;
231 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
232 $search_sale = DolibarrApiAccess::$user->id;
233 }
234
235 $sql = "SELECT t.rowid";
236 $sql .= " FROM ".MAIN_DB_PREFIX."facture AS t";
237 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
238 $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
239 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
240 if ($socids) {
241 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
242 }
243 // Search on sale representative
244 if ($search_sale && $search_sale != '-1') {
245 if ($search_sale == -2) {
246 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
247 } elseif ($search_sale > 0) {
248 $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).")";
249 }
250 }
251 // Filter by status
252 if ($status == 'draft') {
253 $sql .= " AND t.fk_statut IN (0)";
254 }
255 if ($status == 'unpaid') {
256 $sql .= " AND t.fk_statut IN (1)";
257 }
258 if ($status == 'paid') {
259 $sql .= " AND t.fk_statut IN (2)";
260 }
261 if ($status == 'cancelled') {
262 $sql .= " AND t.fk_statut IN (3)";
263 }
264 // Add sql filters
265 if ($sqlfilters) {
266 $errormessage = '';
267 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
268 if ($errormessage) {
269 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
270 }
271 }
272
273 //this query will return total invoices with the filters given
274 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
275
276 $sql .= $this->db->order($sortfield, $sortorder);
277 if ($limit) {
278 if ($page < 0) {
279 $page = 0;
280 }
281 $offset = $limit * $page;
282
283 $sql .= $this->db->plimit($limit + 1, $offset);
284 }
285
286 $result = $this->db->query($sql);
287 if ($result) {
288 $i = 0;
289 $num = $this->db->num_rows($result);
290 $min = min($num, ($limit <= 0 ? $num : $limit));
291 while ($i < $min) {
292 $obj = $this->db->fetch_object($result);
293 $invoice_static = new Facture($this->db);
294 if ($invoice_static->fetch($obj->rowid) > 0) {
295 // Get payment details
296 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
297 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
298 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
299 $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
300
301 // Retrieve credit note ids
302 $invoice_static->getListIdAvoirFromInvoice();
303
304 // Add external contacts ids
305 $tmparray = $invoice_static->liste_contact(-1, 'external', 1);
306 if (is_array($tmparray)) {
307 $invoice_static->contacts_ids = $tmparray;
308 }
309
310 if ($loadlinkedobjects) {
311 // retrieve linked objects
312 $invoice_static->fetchObjectLinked();
313 }
314
315 if (!$withLines) {
316 unset($invoice_static->lines);
317 }
318
319 // Add online_payment_url, copied from order
320 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
321 $invoice_static->online_payment_url = getOnlinePaymentUrl(0, 'invoice', (string) $invoice_static->ref);
322
323 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
324 }
325 $i++;
326 }
327 } else {
328 throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror());
329 }
330
331 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
332 if ($pagination_data) {
333 $totalsResult = $this->db->query($sqlTotals);
334 $total = $this->db->fetch_object($totalsResult)->total;
335
336 $tmp = $obj_ret;
337 $obj_ret = [];
338
339 $obj_ret['data'] = $tmp;
340 $obj_ret['pagination'] = [
341 'total' => (int) $total,
342 'page' => $page, //count starts from 0
343 'page_count' => ceil((int) $total / $limit),
344 'limit' => $limit
345 ];
346 }
347
348 return $obj_ret;
349 }
350
361 public function post($request_data = null)
362 {
363 global $conf;
364 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
365 throw new RestException(403, "Insufficiant rights");
366 }
367
368 if (!is_array($request_data)) {
369 $request_data = array();
370 }
371
372 // Check mandatory fields (not using output, only possible exception is important)
373 $this->_validate($request_data);
374
375 // Check thirdparty validity
376 $socid = (int) $request_data['socid'];
377 $thirdpartytmp = new Societe($this->db);
378 $thirdparty_result = $thirdpartytmp->fetch($socid);
379 if ($thirdparty_result < 1) {
380 throw new RestException(404, 'Thirdparty with id='.$socid.' not found or not allowed');
381 }
382 if (!DolibarrApi::_checkAccessToResource('societe', $thirdpartytmp->id)) {
383 throw new RestException(404, 'Thirdparty with id='.$thirdpartytmp->id.' not found or not allowed');
384 }
385
386 foreach ($request_data as $field => $value) {
387 if ($field === 'caller') {
388 // 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
389 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
390 continue;
391 }
392 if ($field == 'id') {
393 throw new RestException(400, 'Creating with id field is forbidden');
394 }
395 if ($field == 'entity' && ((int) $value) != ((int) $conf->entity)) {
396 throw new RestException(403, 'Creating with entity='.((int) $value).' MUST be the same entity='.((int) $conf->entity).' as your API user/key belongs to');
397 }
398
399 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
400 }
401 if (!array_key_exists('date', $request_data)) {
402 $this->invoice->date = dol_now();
403 }
404 /* We keep lines as an array
405 if (isset($request_data["lines"])) {
406 $lines = array();
407 foreach ($request_data["lines"] as $line) {
408 array_push($lines, (object) $line);
409 }
410 $this->invoice->lines = $lines;
411 }*/
412
413 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) {
414 throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
415 }
416 return ((int) $this->invoice->id);
417 }
418
435 public function createInvoiceFromOrder($orderid)
436 {
437 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
438
439 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
440 throw new RestException(403);
441 }
442 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
443 throw new RestException(403);
444 }
445 if (empty($orderid)) {
446 throw new RestException(400, 'Order ID is mandatory');
447 }
448 if (!DolibarrApi::_checkAccessToResource('commande', $orderid)) {
449 throw new RestException(403, 'Access not allowed on order for login '.DolibarrApiAccess::$user->login);
450 }
451
452 $order = new Commande($this->db);
453 $result = $order->fetch($orderid);
454 if (!$result) {
455 throw new RestException(404, 'Order not found');
456 }
457
458 // Refuse orders that cannot be billed, to mirror the GUI (order card "CreateBill" button and list mass action):
459 // this excludes draft and canceled orders, as well as orders already classified as billed.
460 if ($order->status <= Commande::STATUS_DRAFT || !empty($order->billed)) {
461 throw new RestException(405, 'Order '.$order->ref.' is not eligible for invoicing: its status does not allow creating an invoice');
462 }
463
464 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
465 if ($result < 0) {
466 throw new RestException(405, $this->invoice->error);
467 }
468 $this->invoice->fetchObjectLinked();
469 return $this->_cleanObjectDatas($this->invoice);
470 }
471
487 public function createInvoiceFromContract($contractid)
488 {
489 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
490
491 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
492 throw new RestException(403);
493 }
494 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
495 throw new RestException(403);
496 }
497 if (empty($contractid)) {
498 throw new RestException(400, 'Contract ID is mandatory');
499 }
500
501 $contract = new Contrat($this->db);
502 $result = $contract->fetch($contractid);
503 if (!$result) {
504 throw new RestException(404, 'Contract not found');
505 }
506
507 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
508 if ($result < 0) {
509 throw new RestException(405, $this->invoice->error);
510 }
511 $this->invoice->fetchObjectLinked();
512 return $this->_cleanObjectDatas($this->invoice);
513 }
514
527 public function getLines($id)
528 {
529 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
530 throw new RestException(403);
531 }
532
533 $result = $this->invoice->fetch($id);
534 if (!$result) {
535 throw new RestException(404, 'Invoice not found');
536 }
537
538 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
539 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
540 }
541 $this->invoice->getLinesArray();
542 $result = array();
543 foreach ($this->invoice->lines as $line) {
544 array_push($result, $this->_cleanObjectDatas($line));
545 }
546 return $result;
547 }
548
567 public function putLine($id, $lineid, $request_data = null)
568 {
569 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
570 throw new RestException(403);
571 }
572
573 $result = $this->invoice->fetch($id);
574 if (!$result) {
575 throw new RestException(404, 'Invoice not found');
576 }
577
578 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
579 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
580 }
581
582 $request_data = (object) $request_data;
583
584 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
585 $request_data->label = sanitizeVal($request_data->label);
586
587 $invoiceline = new FactureLigne($this->db);
588 $result = $invoiceline->fetch($lineid);
589 if (!$result) {
590 throw new RestException(404, 'Invoice line not found');
591 }
592
593 if ($invoiceline->fk_facture != $id) {
594 throw new RestException(403, 'Line does not belong to this invoice');
595 }
596
597 $updateRes = $this->invoice->updateline(
598 $lineid,
599 $request_data->desc,
600 $request_data->subprice,
601 $request_data->qty,
602 $request_data->remise_percent,
603 $request_data->date_start,
604 $request_data->date_end,
605 $request_data->tva_tx,
606 $request_data->localtax1_tx,
607 $request_data->localtax2_tx,
608 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
609 $request_data->info_bits,
610 $request_data->product_type,
611 $request_data->fk_parent_line,
612 0,
613 $request_data->fk_fournprice,
614 $request_data->pa_ht,
615 $request_data->label,
616 $request_data->special_code,
617 $request_data->array_options,
618 $request_data->situation_percent,
619 $request_data->fk_unit,
620 $request_data->multicurrency_subprice,
621 0,
622 $request_data->ref_ext,
623 $request_data->rang
624 );
625
626 if ($updateRes > 0) {
627 $result = $this->get($id);
628 unset($result->line);
629 return $this->_cleanObjectDatas($result);
630 } else {
631 throw new RestException(304, $this->invoice->error);
632 }
633 }
634
654 public function postContact($id, $contactid, $type, $source = 'external', $notrigger = 0)
655 {
656 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
657 throw new RestException(403);
658 }
659
660 // test source
661 if (empty($source)) {
662 throw new RestException(400, 'Source can not be empty');
663 }
664 $sql_distinct_source = "SELECT DISTINCT source";
665 $sql_distinct_source .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
666 $sql_distinct_source .= " WHERE element LIKE 'facture'";
667 $sql_distinct_source .= " AND source is NOT NULL";
668 $sql_distinct_source .= " AND active != 0";
669 $source_result = $this->db->query($sql_distinct_source);
670 $source_array = array();
671
672 if ($source_result) {
673 $num = $this->db->num_rows($source_result);
674 $i = 0;
675 while ($i < $num) {
676 $obj = $this->db->fetch_object($source_result);
677 $source_kind = (string) $obj->source;
678 array_push($source_array, $source_kind);
679 dol_syslog("source_kind=".$source_kind);
680 $i++;
681 }
682 } else {
683 throw new RestException(503, 'Error when retrieving a list of invoice contact sources: '.$this->db->lasterror());
684 }
685 if (!in_array($source, (array) $source_array, true)) {
686 throw new RestException(400, 'Combo of Source='.$source.' and Type='.$type.' not found in dictionary with active invoice contact types');
687 }
688
689 // test type
690 if (empty($type)) {
691 throw new RestException(400, 'type can not be empty');
692 }
693 // variable called type here, but code in dictionary and database
694 $sql_distinct_type = "SELECT DISTINCT code";
695 $sql_distinct_type .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
696 $sql_distinct_type .= " WHERE element LIKE 'facture'";
697 $sql_distinct_type .= " AND source='".$this->db->escape($source)."'";
698 $sql_distinct_type .= " AND code is NOT NULL";
699 $sql_distinct_type .= " AND active != 0";
700 $type_result = $this->db->query($sql_distinct_type);
701 $type_array = array();
702
703 if ($type_result) {
704 $num = $this->db->num_rows($type_result);
705 $i = 0;
706 while ($i < $num) {
707 $obj = $this->db->fetch_object($type_result);
708 // variable called type here, but code in dictionary and database
709 $type_kind = (string) $obj->code;
710 array_push($type_array, $type_kind);
711 dol_syslog("type_kind=".$type_kind);
712 $i++;
713 }
714 } else {
715 throw new RestException(503, 'Error when retrieving a list of invoice contact types: '.$this->db->lasterror());
716 }
717 if (!in_array($type, (array) $type_array, true)) {
718 throw new RestException(400, 'Combo of Type='.$type.' and Source='.$source.' not found in dictionary with active invoice contact types');
719 }
720
721 // tests done, let's get it
722 $result = $this->invoice->fetch($id);
723 if (!$result) {
724 throw new RestException(404, 'Invoice not found');
725 }
726 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
727 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
728 }
729
730 $result = $this->invoice->add_contact($contactid, $type, $source, $notrigger);
731
732 if ($result == 0) {
733 throw new RestException(400, 'Already exists: Contact='.$contactid.' is already linked to the invoice='.$id.' as source='.$source.' and type='.$type);
734 } elseif ($result == -1) {
735 throw new RestException(400, 'Wrong contact='.$contactid);
736 } elseif ($result == -2) {
737 throw new RestException(400, 'Wrong type='.$type);
738 } elseif ($result == -3) {
739 throw new RestException(400, 'Not allowed contacts');
740 } elseif ($result == -4) {
741 throw new RestException(400, 'ErrorCommercialNotAllowedForThirdparty');
742 } elseif ($result == -5) {
743 throw new RestException(400, 'Trigger failed');
744 } elseif ($result == -6) {
745 throw new RestException(400, 'DB_ERROR_RECORD_ALREADY_EXISTS');
746 } elseif ($result == -7) {
747 throw new RestException(400, 'Some other error');
748 }
749
750 if (!$result) {
751 throw new RestException(500, 'Error when added the contact');
752 }
753
754 return array(
755 'success' => array(
756 'code' => 200,
757 'message' => 'Contact='.$contactid.' linked to the invoice='.$id.' as '.$source.' '.$type
758 )
759 );
760 }
761
777 public function getContacts($id, $type = '')
778 {
779 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
780 throw new RestException(403);
781 }
782
783 $result = $this->invoice->fetch($id);
784 if (!$result) {
785 throw new RestException(404, 'Invoice not found');
786 }
787
788 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
789 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
790 }
791
792 $contacts = $this->invoice->liste_contact(-1, 'external', 0, $type);
793 $socpeoples = $this->invoice->liste_contact(-1, 'internal', 0, $type);
794
795 $contacts = array_merge($contacts, $socpeoples);
796
797 return $contacts;
798 }
799
816 public function deleteContact($id, $contactid, $type)
817 {
818 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
819 throw new RestException(403);
820 }
821
822 $result = $this->invoice->fetch($id);
823
824 if (!$result) {
825 throw new RestException(404, 'Invoice not found');
826 }
827
828 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
829 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
830 }
831
832 $contacts = $this->invoice->liste_contact();
833
834 foreach ($contacts as $contact) {
835 if ($contact['id'] == $contactid && $contact['code'] == $type) {
836 $result = $this->invoice->delete_contact($contact['rowid']);
837
838 if (!$result) {
839 throw new RestException(500, 'Error when deleted the contact');
840 }
841 }
842 }
843
844 return $this->_cleanObjectDatas($this->invoice);
845 }
846
863 public function deleteLine($id, $lineid)
864 {
865 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
866 throw new RestException(403);
867 }
868 if (empty($lineid)) {
869 throw new RestException(400, 'Line ID is mandatory');
870 }
871
872 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
873 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
874 }
875
876 $result = $this->invoice->fetch($id);
877 if (!$result) {
878 throw new RestException(404, 'Invoice not found');
879 }
880 if ($this->invoice->status != 0) {
881 throw new RestException(403, 'Invoice not in Draft Status : '.$this->invoice->getLibStatut(1));
882 }
883
884 $updateRes = $this->invoice->deleteLine($lineid, $id);
885 if ($updateRes > 0) {
886 return $this->get($id);
887 } else {
888 throw new RestException(405, $this->invoice->error);
889 }
890 }
891
903 public function put($id, $request_data = null)
904 {
905 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
906 throw new RestException(403);
907 }
908 if ($id == 0) {
909 throw new RestException(400, 'No invoice with id=0 can exist');
910 }
911 $result = $this->invoice->fetch($id);
912 if (!$result) {
913 throw new RestException(404, 'Invoice not found');
914 }
915
916 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
917 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
918 }
919
920 foreach ($request_data as $field => $value) {
921 if ($field == 'id') {
922 continue;
923 }
924 if ($field === 'caller') {
925 // 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
926 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
927 continue;
928 }
929 if ($field == 'array_options' && is_array($value)) {
930 foreach ($value as $index => $val) {
931 $this->invoice->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->invoice);
932 }
933 continue;
934 }
935
936 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
937
938 // If cond reglement => update date lim reglement
939 if ($field == 'cond_reglement_id') {
940 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
941 }
942 }
943
944 // update bank account
945 if (!empty($this->invoice->fk_account)) {
946 if ($this->invoice->setBankAccount((int) $this->invoice->fk_account) == 0) {
947 throw new RestException(400, $this->invoice->error);
948 }
949 }
950
951 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
952 return $this->get($id);
953 } else {
954 throw new RestException(500, $this->invoice->error);
955 }
956 }
957
968 public function delete($id)
969 {
970 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
971 throw new RestException(403);
972 }
973 if ($id == 0) {
974 throw new RestException(400, 'No invoice with id=0 can exist');
975 }
976 $result = $this->invoice->fetch($id);
977 if (!$result) {
978 throw new RestException(404, 'Invoice not found');
979 }
980
981 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
982 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
983 }
984
985 $result = $this->invoice->delete(DolibarrApiAccess::$user);
986 if ($result < 0) {
987 throw new RestException(500, 'Error when deleting invoice');
988 } elseif ($result == 0) {
989 throw new RestException(403, 'Invoice not erasable');
990 }
991
992 return array(
993 'success' => array(
994 'code' => 200,
995 'message' => 'Invoice deleted'
996 )
997 );
998 }
999
1027 public function postLine($id, $request_data = null)
1028 {
1029 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1030 throw new RestException(403);
1031 }
1032
1033 $result = $this->invoice->fetch($id);
1034 if (!$result) {
1035 throw new RestException(404, 'Invoice not found');
1036 }
1037
1038 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1039 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1040 }
1041
1042 $request_data = (object) $request_data;
1043
1044 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
1045 $request_data->label = sanitizeVal($request_data->label);
1046
1047 // Reset fk_parent_line for no child products and special product
1048 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
1049 $request_data->fk_parent_line = 0;
1050 }
1051
1052 // calculate pa_ht
1053 $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);
1054 $pa_ht = $marginInfos[0];
1055
1056 $updateRes = $this->invoice->addline(
1057 $request_data->desc,
1058 $request_data->subprice,
1059 $request_data->qty,
1060 $request_data->tva_tx,
1061 $request_data->localtax1_tx,
1062 $request_data->localtax2_tx,
1063 $request_data->fk_product,
1064 $request_data->remise_percent,
1065 $request_data->date_start,
1066 $request_data->date_end,
1067 $request_data->fk_code_ventilation,
1068 $request_data->info_bits,
1069 $request_data->fk_remise_except,
1070 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
1071 $request_data->subprice,
1072 $request_data->product_type,
1073 $request_data->rang,
1074 $request_data->special_code,
1075 $request_data->origin,
1076 $request_data->origin_id,
1077 $request_data->fk_parent_line,
1078 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
1079 $pa_ht,
1080 $request_data->label,
1081 $request_data->array_options,
1082 $request_data->situation_percent,
1083 $request_data->fk_prev_id,
1084 $request_data->fk_unit,
1085 0,
1086 $request_data->ref_ext
1087 );
1088
1089 if ($updateRes < 0) {
1090 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
1091 }
1092
1093 return $updateRes;
1094 }
1095
1116 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
1117 {
1118 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1119 throw new RestException(403);
1120 }
1121 $result = $this->invoice->fetch($id);
1122 if (!$result) {
1123 throw new RestException(404, 'Invoice not found');
1124 }
1125
1126 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1127 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1128 }
1129
1130 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
1131 if ($result < 0) {
1132 throw new RestException(500, 'Error : '.$this->invoice->error);
1133 }
1134
1135 $result = $this->invoice->fetch($id);
1136 if (!$result) {
1137 throw new RestException(404, 'Invoice not found');
1138 }
1139
1140 // test already done
1141 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1142 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1143 // }
1144
1145 return $this->_cleanObjectDatas($this->invoice);
1146 }
1147
1148
1149
1166 public function settodraft($id, $idwarehouse = -1)
1167 {
1168 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1169 throw new RestException(403);
1170 }
1171 $result = $this->invoice->fetch($id);
1172 if (!$result) {
1173 throw new RestException(404, 'Invoice not found');
1174 }
1175
1176 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1177 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1178 }
1179
1180 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
1181 if ($result == 0) {
1182 throw new RestException(304, 'Nothing done.');
1183 }
1184 if ($result < 0) {
1185 throw new RestException(500, 'Error : '.$this->invoice->error);
1186 }
1187
1188 $result = $this->invoice->fetch($id);
1189 if (!$result) {
1190 throw new RestException(404, 'Invoice not found');
1191 }
1192
1193 return $this->_cleanObjectDatas($this->invoice);
1194 }
1195
1196
1216 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1217 {
1218 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1219 throw new RestException(403);
1220 }
1221 $result = $this->invoice->fetch($id);
1222 if (!$result) {
1223 throw new RestException(404, 'Invoice not found');
1224 }
1225
1226 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1227 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1228 }
1229
1230 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
1231 if ($result == 0) {
1232 throw new RestException(304, 'Error nothing done. May be object is already validated');
1233 }
1234 if ($result < 0) {
1235 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
1236 }
1237
1238 $result = $this->invoice->fetch($id);
1239 if (!$result) {
1240 throw new RestException(404, 'Invoice not found');
1241 }
1242
1243 // test already done
1244 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1245 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1246 // }
1247
1248 // copy from order
1249 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1250 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', (string) $this->invoice->ref);
1251
1252 return $this->_cleanObjectDatas($this->invoice);
1253 }
1254
1272 public function settopaid($id, $close_code = '', $close_note = '')
1273 {
1274 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1275 throw new RestException(403);
1276 }
1277 $result = $this->invoice->fetch($id);
1278 if (!$result) {
1279 throw new RestException(404, 'Invoice not found');
1280 }
1281
1282 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1283 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1284 }
1285
1286 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1287 if ($result == 0) {
1288 throw new RestException(304, 'Error nothing done. May be object is already validated');
1289 }
1290 if ($result < 0) {
1291 throw new RestException(500, 'Error : '.$this->invoice->error);
1292 }
1293
1294
1295 $result = $this->invoice->fetch($id);
1296 if (!$result) {
1297 throw new RestException(404, 'Invoice not found');
1298 }
1299
1300 // test already done
1301 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1302 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1303 // }
1304
1305 return $this->_cleanObjectDatas($this->invoice);
1306 }
1307
1308
1324 public function settounpaid($id)
1325 {
1326 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1327 throw new RestException(403);
1328 }
1329 $result = $this->invoice->fetch($id);
1330 if (!$result) {
1331 throw new RestException(404, 'Invoice not found');
1332 }
1333
1334 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1335 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1336 }
1337
1338 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1339 if ($result == 0) {
1340 throw new RestException(304, 'Nothing done');
1341 }
1342 if ($result < 0) {
1343 throw new RestException(500, 'Error : '.$this->invoice->error);
1344 }
1345
1346
1347 $result = $this->invoice->fetch($id);
1348 if (!$result) {
1349 throw new RestException(404, 'Invoice not found');
1350 }
1351
1352 // test already done
1353 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1354 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1355 // }
1356
1357 return $this->_cleanObjectDatas($this->invoice);
1358 }
1359
1370 public function getDiscount($id)
1371 {
1372 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1373
1374 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1375 throw new RestException(403);
1376 }
1377
1378 $result = $this->invoice->fetch($id);
1379 if (!$result) {
1380 throw new RestException(404, 'Invoice not found');
1381 }
1382
1383 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1384 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1385 }
1386
1387 $discountcheck = new DiscountAbsolute($this->db);
1388 $result = $discountcheck->fetch(0, $this->invoice->id);
1389
1390 if ($result == 0) {
1391 throw new RestException(404, 'Discount not found');
1392 }
1393 if ($result < 0) {
1394 throw new RestException(500, $discountcheck->error);
1395 }
1396
1397 return parent::_cleanObjectDatas($discountcheck);
1398 }
1399
1416 {
1417 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1418
1419 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1420 throw new RestException(403);
1421 }
1422
1423 $result = $this->invoice->fetch($id);
1424 if (!$result) {
1425 throw new RestException(404, 'Invoice not found');
1426 }
1427
1428 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1429 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1430 }
1431
1432 if ($this->invoice->paye) { // TODO Replace by a test on status
1433 throw new RestException(500, 'Alreay paid');
1434 }
1435
1436 $this->invoice->fetch($id);
1437 $this->invoice->fetch_thirdparty();
1438
1439 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1440 $discountcheck = new DiscountAbsolute($this->db);
1441 $result = $discountcheck->fetch(0, $this->invoice->id);
1442
1443 $canconvert = 0;
1444 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1445 $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)
1446 }
1447 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1448 $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)
1449 }
1450 if ($canconvert) {
1451 $this->db->begin();
1452
1453 $amount_ht = $amount_tva = $amount_ttc = array();
1454 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1455 '
1456 @phan-var-force array<string,float> $amount_ht
1457 @phan-var-force array<string,float> $amount_tva
1458 @phan-var-force array<string,float> $amount_ttc
1459 @phan-var-force array<string,float> $multicurrency_amount_ht
1460 @phan-var-force array<string,float> $multicurrency_amount_tva
1461 @phan-var-force array<string,float> $multicurrency_amount_ttc
1462 ';
1463
1464 // Loop on each vat rate
1465 $i = 0;
1466 foreach ($this->invoice->lines as $line) {
1467 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1468 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1469 $amount_ht[$line->tva_tx] = 0.0;
1470 $amount_tva[$line->tva_tx] = 0.0;
1471 $amount_ttc[$line->tva_tx] = 0.0;
1472 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1473 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1474 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1475 }
1476 // no need to create discount if amount is null
1477 $amount_ht[$line->tva_tx] += $line->total_ht;
1478 $amount_tva[$line->tva_tx] += $line->total_tva;
1479 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1480 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1481 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1482 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1483 $i++;
1484 }
1485 }
1486
1487 // Insert one discount by VAT rate category
1488 $discount = new DiscountAbsolute($this->db);
1489 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1490 $discount->description = '(CREDIT_NOTE)';
1491 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1492 $discount->description = '(DEPOSIT)';
1493 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1494 $discount->description = '(EXCESS RECEIVED)';
1495 } else {
1496 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1497 }
1498
1499 $discount->fk_soc = $this->invoice->socid;
1500 $discount->socid = $this->invoice->socid;
1501 $discount->fk_facture_source = $this->invoice->id;
1502
1503 $error = 0;
1504
1505 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1506 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1507
1508 // Total payments
1509 $sql = 'SELECT SUM(pf.amount) as total_payments';
1510 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1511 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1512 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1513 $sql .= ' AND pf.fk_paiement = p.rowid';
1514 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1515 $resql = $this->db->query($sql);
1516 if (!$resql) {
1517 dol_print_error($this->db);
1518 }
1519
1520 $res = $this->db->fetch_object($resql);
1521 $total_payments = $res->total_payments;
1522
1523 // Total credit note and deposit
1524 $total_creditnote_and_deposit = 0;
1525 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1526 $sql .= " re.description, re.fk_facture_source";
1527 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1528 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1529 $resql = $this->db->query($sql);
1530 if (!empty($resql)) {
1531 while ($obj = $this->db->fetch_object($resql)) {
1532 $total_creditnote_and_deposit += $obj->amount_ttc;
1533 }
1534 } else {
1535 dol_print_error($this->db);
1536 }
1537
1538 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1539 $discount->total_ht = $discount->total_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1540 $discount->amount_tva = 0;
1541 $discount->total_tva = 0;
1542 $discount->tva_tx = 0;
1543
1544 $result = $discount->create(DolibarrApiAccess::$user);
1545 if ($result < 0) {
1546 $error++;
1547 }
1548 }
1549 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1550 foreach ($amount_ht as $tva_tx => $xxx) {
1551 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1552 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1553 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1554 $discount->total_ht = abs($amount_ht[$tva_tx]);
1555 $discount->total_tva = abs($amount_tva[$tva_tx]);
1556 $discount->total_ttc = abs($amount_ttc[$tva_tx]);
1557 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1558 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1559 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1560 $discount->multicurrency_total_ht = abs($multicurrency_amount_ht[$tva_tx]);
1561 $discount->multicurrency_total_tva = abs($multicurrency_amount_tva[$tva_tx]);
1562 $discount->multicurrency_total_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1563 $discount->tva_tx = abs((float) $tva_tx);
1564
1565 $result = $discount->create(DolibarrApiAccess::$user);
1566 if ($result < 0) {
1567 $error++;
1568 break;
1569 }
1570 }
1571 }
1572
1573 if (empty($error)) {
1574 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1575 // Set the invoice as paid
1576 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1577 if ($result >= 0) {
1578 $this->db->commit();
1579 } else {
1580 $this->db->rollback();
1581 throw new RestException(500, 'Could not set paid');
1582 }
1583 } else {
1584 $this->db->commit();
1585 }
1586 } else {
1587 $this->db->rollback();
1588 throw new RestException(500, 'Discount creation error');
1589 }
1590 }
1591
1592 return $this->_cleanObjectDatas($this->invoice);
1593 }
1594
1613 public function useDiscount($id, $discountid)
1614 {
1615 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1616 throw new RestException(403);
1617 }
1618 if (empty($id)) {
1619 throw new RestException(400, 'Invoice ID is mandatory');
1620 }
1621 if (empty($discountid)) {
1622 throw new RestException(400, 'Discount ID is mandatory');
1623 }
1624
1625 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1626 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1627 }
1628
1629 $result = $this->invoice->fetch($id);
1630 if (!$result) {
1631 throw new RestException(404, 'Invoice not found');
1632 }
1633
1634 $result = $this->invoice->insert_discount($discountid);
1635 if ($result < 0) {
1636 throw new RestException(405, $this->invoice->error);
1637 }
1638
1639 return $result;
1640 }
1641
1660 public function useCreditNote($id, $discountid)
1661 {
1662 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1663
1664 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1665 throw new RestException(403);
1666 }
1667 if (empty($id)) {
1668 throw new RestException(400, 'Invoice ID is mandatory');
1669 }
1670 if (empty($discountid)) {
1671 throw new RestException(400, 'Credit ID is mandatory');
1672 }
1673
1674 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1675 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1676 }
1677 $discount = new DiscountAbsolute($this->db);
1678 $result = $discount->fetch($discountid);
1679 if (!$result) {
1680 throw new RestException(404, 'Credit not found');
1681 }
1682
1683 $result = $discount->link_to_invoice(0, $id);
1684 if ($result < 0) {
1685 throw new RestException(405, $discount->error);
1686 }
1687
1688 return $result;
1689 }
1690
1708 public function getPayments($id)
1709 {
1710 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1711 throw new RestException(403);
1712 }
1713 if (empty($id)) {
1714 throw new RestException(400, 'Invoice ID is mandatory');
1715 }
1716
1717 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1718 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1719 }
1720
1721 $result = $this->invoice->fetch($id);
1722 if (!$result) {
1723 throw new RestException(404, 'Invoice not found');
1724 }
1725
1726 $result = $this->invoice->getListOfPayments();
1727 if (!is_array($result) && $result < 0) {
1728 throw new RestException(405, $this->invoice->error);
1729 }
1730
1731 return $result;
1732 }
1733
1734
1758 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1759 {
1760 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1761
1762 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
1763 throw new RestException(403);
1764 }
1765 if (empty($id)) {
1766 throw new RestException(400, 'Invoice ID is mandatory');
1767 }
1768
1769 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1770 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1771 }
1772
1773 if (isModEnabled("bank")) {
1774 if (empty($accountid)) {
1775 throw new RestException(400, 'Account ID is mandatory');
1776 }
1777 }
1778
1779 if (empty($paymentid)) {
1780 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1781 }
1782
1783
1784 $result = $this->invoice->fetch($id);
1785 if (!$result) {
1786 throw new RestException(404, 'Invoice not found');
1787 }
1788
1789 // Calculate amount to pay
1790 $totalpaid = $this->invoice->getSommePaiement();
1791 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1792 $totaldeposits = $this->invoice->getSumDepositsUsed();
1793
1794 $this->db->begin();
1795
1796 $amounts = array();
1797 $multicurrency_amounts = array();
1798
1799 // Clean parameters amount if payment is for a credit note
1800 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1801 $resteapayer = price2num($this->invoice->total_ttc + $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1802 $amounts[$id] = (float) price2num(-1 * abs((float) $resteapayer), 'MT');
1803 // Multicurrency
1804 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1805 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1806 } else {
1807 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1808 $amounts[$id] = (float) $resteapayer;
1809 // Multicurrency
1810 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1811 $multicurrency_amounts[$id] = (float) $newvalue;
1812 }
1813
1814 // Creation of payment line
1815 $paymentobj = new Paiement($this->db);
1816 if (is_numeric($datepaye)) {
1817 $paymentobj->datepaye = $datepaye;
1818 } else {
1819 $paymentobj->datepaye = dol_stringtotime($datepaye);
1820 }
1821 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1822 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1823 $paymentobj->paiementid = $paymentid;
1824 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1825 $paymentobj->num_payment = $num_payment;
1826 $paymentobj->note_private = $comment;
1827
1828 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1829 if ($payment_id < 0) {
1830 $this->db->rollback();
1831 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1832 }
1833
1834 if (isModEnabled("bank")) {
1835 $label = '(CustomerInvoicePayment)';
1836
1837 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1838 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1839 }
1840 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1841 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1842 }
1843 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1844 if ($result < 0) {
1845 $this->db->rollback();
1846 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1847 }
1848 }
1849
1850 $this->db->commit();
1851
1852 return $payment_id;
1853 }
1854
1885 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1886 {
1887 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1888
1889 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
1890 throw new RestException(403);
1891 }
1892 foreach ($arrayofamounts as $id => $amount) {
1893 if (empty($id)) {
1894 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1895 }
1896 if (!DolibarrApi::_checkAccessToResource('facture', (int) $id)) {
1897 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1898 }
1899 }
1900
1901 if (isModEnabled("bank")) {
1902 if (empty($accountid)) {
1903 throw new RestException(400, 'Account ID is mandatory');
1904 }
1905 }
1906 if (empty($paymentid)) {
1907 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1908 }
1909
1910 $this->db->begin();
1911
1912 $amounts = array();
1913 $multicurrency_amounts = array();
1914
1915 // Loop on each invoice to pay
1916 foreach ($arrayofamounts as $id => $amountarray) {
1917 $id = (int) $id; // Ensure $id is seen as int, required by function calls and array indexes.
1918 $result = $this->invoice->fetch($id);
1919 if (!$result) {
1920 $this->db->rollback();
1921 throw new RestException(404, 'Invoice ID '.$id.' not found');
1922 }
1923
1924 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1925 $this->db->rollback();
1926 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1927 }
1928
1929 $is_multicurrency = 0;
1930 $total_ttc = $this->invoice->total_ttc;
1931
1932 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1933 $is_multicurrency = 1;
1934 $total_ttc = $this->invoice->multicurrency_total_ttc;
1935 }
1936
1937 // Calculate amount to pay
1938 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1939 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1940 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1941 $remainstopay = $amount = (float) price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1942
1943 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1944 $amount = (float) price2num($amountarray["amount"], 'MT');
1945 }
1946
1947 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1948 $amount = (float) price2num($amountarray["multicurrency_amount"], 'MT');
1949 }
1950
1951 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
1952 $this->db->rollback();
1953 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1954 }
1955
1956 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1957 $amount = (float) price2num(-1 * abs((float) $amount), 'MT');
1958 }
1959
1960 if ($is_multicurrency) {
1961 $amounts[$id] = null;
1962 // Multicurrency
1963 $multicurrency_amounts[$id] = (float) $amount;
1964 } else {
1965 $amounts[$id] = (float) $amount;
1966 // Multicurrency
1967 $multicurrency_amounts[$id] = null;
1968 }
1969 }
1970
1971 // Creation of payment line
1972 $paymentobj = new Paiement($this->db);
1973 if (is_numeric($datepaye)) {
1974 $paymentobj->datepaye = $datepaye;
1975 } else {
1976 $paymentobj->datepaye = dol_stringtotime($datepaye);
1977 }
1978 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1979 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1980 $paymentobj->paiementid = $paymentid;
1981 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1982 $paymentobj->num_payment = $num_payment;
1983 $paymentobj->note_private = $comment;
1984 $paymentobj->ref_ext = $ref_ext;
1985 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1986 if ($payment_id < 0) {
1987 $this->db->rollback();
1988 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1989 }
1990 if (isModEnabled("bank")) {
1991 $label = '(CustomerInvoicePayment)';
1992 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1993 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1994 }
1995 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1996 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1997 }
1998 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1999 if ($result < 0) {
2000 $this->db->rollback();
2001 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
2002 }
2003 }
2004
2005 $this->db->commit();
2006
2007 return $payment_id;
2008 }
2009
2028 public function putPayment($id, $num_payment = '')
2029 {
2030 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2031
2032 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
2033 throw new RestException(403);
2034 }
2035 if (empty($id)) {
2036 throw new RestException(400, 'Payment ID is mandatory');
2037 }
2038
2039 $paymentobj = new Paiement($this->db);
2040 $result = $paymentobj->fetch($id);
2041
2042 if (!$result) {
2043 throw new RestException(404, 'Payment not found');
2044 }
2045
2046 // Check all invoices of the payment to see if the user has permission on them for the object level permission test
2047 $tmparray = $paymentobj->getBillsArray();
2048 foreach ($tmparray as $tmpinvoiceid) {
2049 if (!DolibarrApi::_checkAccessToResource('facture', $tmpinvoiceid)) {
2050 throw new RestException(403, 'Payment is on invoices that are not all allowed for login '.DolibarrApiAccess::$user->login);
2051 }
2052 }
2053
2054 if (!empty($num_payment)) {
2055 $result = $paymentobj->update_num($num_payment);
2056 if ($result < 0) {
2057 throw new RestException(500, 'Error when updating the payment num');
2058 }
2059 }
2060
2061 return [
2062 'success' => [
2063 'code' => 200,
2064 'message' => 'Payment updated'
2065 ]
2066 ];
2067 }
2068
2069 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2079 protected function _cleanObjectDatas($object)
2080 {
2081 // phpcs:enable
2082 $object = parent::_cleanObjectDatas($object);
2083
2084 unset($object->note);
2085 unset($object->address);
2086 unset($object->barcode_type);
2087 unset($object->barcode_type_code);
2088 unset($object->barcode_type_label);
2089 unset($object->barcode_type_coder);
2090 unset($object->canvas);
2091
2092 return $object;
2093 }
2094
2103 private function _validate($data)
2104 {
2105 if ($data === null) {
2106 $data = array();
2107 }
2108 $invoice = array();
2109 foreach (Invoices::$FIELDS as $field) {
2110 if (!isset($data[$field])) {
2111 throw new RestException(400, "$field field missing");
2112 }
2113 $invoice[$field] = $data[$field];
2114 }
2115 return $invoice;
2116 }
2117
2118
2134 public function getTemplateInvoice($id, $contact_list = 1)
2135 {
2136 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
2137 }
2138
2139
2167 public function indexTemplateInvoices($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
2168 {
2169 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2170 throw new RestException(403);
2171 }
2172
2173 $obj_ret = array();
2174
2175 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
2176 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
2177
2178
2179 // If the internal user must only see his customers, force searching by him
2180 $search_sale = 0;
2181 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
2182 $search_sale = DolibarrApiAccess::$user->id;
2183 }
2184
2185 $sql = "SELECT t.rowid";
2186 $sql .= " FROM ".MAIN_DB_PREFIX."facture_rec AS t";
2187 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
2188 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_rec_extrafields AS ef ON (ef.fk_object = t.rowid)";
2189 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
2190 if ($socids) {
2191 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
2192 }
2193
2194 // Search on sale representative
2195 if ($search_sale && $search_sale != '-1') {
2196 if ($search_sale == -2) {
2197 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux AS sc WHERE sc.fk_soc = t.fk_soc)";
2198 } elseif ($search_sale > 0) {
2199 $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).")";
2200 }
2201 }
2202
2203 // Filter by status
2204 if ($status == 'active') {
2205 $sql .= " AND t.suspended = 0 AND t.frequency IS NOT NULL";
2206 }
2207 if ($status == 'suspended') {
2208 $sql .= " AND t.suspended = 1 AND t.frequency IS NOT NULL";
2209 }
2210 if ($status == 'draft') {
2211 $sql .= " AND t.frequency IS NULL";
2212 }
2213 // add sql filters
2214 if ($sqlfilters) {
2215 $errormessage = '';
2216 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
2217 if ($errormessage) {
2218 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
2219 }
2220 }
2221
2222 //this query will return total template invoices with the filters given
2223 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
2224
2225 $sql .= $this->db->order($sortfield, $sortorder);
2226 if ($limit) {
2227 if ($page < 0) {
2228 $page = 0;
2229 }
2230 $offset = $limit * $page;
2231
2232 $sql .= $this->db->plimit($limit + 1, $offset);
2233 }
2234
2235 $result = $this->db->query($sql);
2236 if ($result) {
2237 $i = 0;
2238 $num = $this->db->num_rows($result);
2239 $min = min($num, ($limit <= 0 ? $num : $limit));
2240 while ($i < $min) {
2241 $obj = $this->db->fetch_object($result);
2242 $factureRec = new FactureRec($this->db);
2243 if ($factureRec->fetch($obj->rowid) > 0) {
2244 if ($loadlinkedobjects) {
2245 // retrieve linked objects
2246 $factureRec->fetchObjectLinked();
2247 }
2248
2249 if (!$withLines) {
2250 unset($factureRec->lines);
2251 }
2252
2253 $obj_ret[] = $this->_filterObjectProperties($this->_cleanTemplateObjectDatas($factureRec), $properties);
2254 }
2255 $i++;
2256 }
2257 } else {
2258 throw new RestException(503, 'Error when retrieving recurring invoice templates: '.$this->db->lasterror());
2259 }
2260
2261 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
2262 if ($pagination_data) {
2263 $totalsResult = $this->db->query($sqlTotals);
2264 $total = $this->db->fetch_object($totalsResult)->total;
2265
2266 $tmp = $obj_ret;
2267 $obj_ret = array();
2268
2269 $obj_ret['data'] = $tmp;
2270 $obj_ret['pagination'] = array(
2271 'total' => (int) $total,
2272 'page' => $page,
2273 'page_count' => ceil((int) $total / $limit),
2274 'limit' => $limit
2275 );
2276 }
2277
2278 return $obj_ret;
2279 }
2280
2294 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
2295 {
2296 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2297 throw new RestException(403);
2298 }
2299
2300 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
2301 if (!$result) {
2302 throw new RestException(404, 'Template invoice not found');
2303 }
2304
2305 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
2306 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2307 }
2308
2309 // Add external contacts ids
2310 if ($contact_list > -1) {
2311 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
2312 if (is_array($tmparray)) {
2313 $this->template_invoice->contacts_ids = $tmparray;
2314 }
2315 }
2316
2317 $this->template_invoice->fetchObjectLinked();
2318 return $this->_cleanTemplateObjectDatas($this->template_invoice);
2319 }
2320
2321
2322 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2330 {
2331 // phpcs:enable
2332 $object = parent::_cleanObjectDatas($object);
2333
2334 unset($object->note);
2335 unset($object->address);
2336 unset($object->barcode_type);
2337 unset($object->barcode_type_code);
2338 unset($object->barcode_type_label);
2339 unset($object->barcode_type_coder);
2340 unset($object->canvas);
2341
2342 return $object;
2343 }
2344}
$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:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
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 lines.
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:436
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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, $forbiddenfields=array())
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.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.