dolibarr 24.0.2
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 if (!DolibarrApi::_checkAccessToResource('contrat', $contract->id)) {
507 throw new RestException(403, 'Access to contract '.$contract->id.' not allowed for login '.DolibarrApiAccess::$user->login);
508 }
509
510 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
511 if ($result < 0) {
512 throw new RestException(405, $this->invoice->error);
513 }
514 $this->invoice->fetchObjectLinked();
515 return $this->_cleanObjectDatas($this->invoice);
516 }
517
530 public function getLines($id)
531 {
532 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
533 throw new RestException(403);
534 }
535
536 $result = $this->invoice->fetch($id);
537 if (!$result) {
538 throw new RestException(404, 'Invoice not found');
539 }
540
541 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
542 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
543 }
544 $this->invoice->getLinesArray();
545 $result = array();
546 foreach ($this->invoice->lines as $line) {
547 array_push($result, $this->_cleanObjectDatas($line));
548 }
549 return $result;
550 }
551
570 public function putLine($id, $lineid, $request_data = null)
571 {
572 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
573 throw new RestException(403);
574 }
575
576 $result = $this->invoice->fetch($id);
577 if (!$result) {
578 throw new RestException(404, 'Invoice not found');
579 }
580
581 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
582 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
583 }
584
585 $request_data = (object) $request_data;
586
587 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
588 $request_data->label = sanitizeVal($request_data->label);
589
590 $invoiceline = new FactureLigne($this->db);
591 $result = $invoiceline->fetch($lineid);
592 if (!$result) {
593 throw new RestException(404, 'Invoice line not found');
594 }
595
596 if ($invoiceline->fk_facture != $id) {
597 throw new RestException(403, 'Line does not belong to this invoice');
598 }
599
600 $updateRes = $this->invoice->updateline(
601 $lineid,
602 $request_data->desc,
603 $request_data->subprice,
604 $request_data->qty,
605 $request_data->remise_percent,
606 $request_data->date_start,
607 $request_data->date_end,
608 $request_data->tva_tx,
609 $request_data->localtax1_tx,
610 $request_data->localtax2_tx,
611 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
612 $request_data->info_bits,
613 $request_data->product_type,
614 $request_data->fk_parent_line,
615 0,
616 $request_data->fk_fournprice,
617 $request_data->pa_ht,
618 $request_data->label,
619 $request_data->special_code,
620 $request_data->array_options,
621 $request_data->situation_percent,
622 $request_data->fk_unit,
623 $request_data->multicurrency_subprice,
624 0,
625 $request_data->ref_ext,
626 $request_data->rang
627 );
628
629 if ($updateRes > 0) {
630 $result = $this->get($id);
631 unset($result->line);
632 return $this->_cleanObjectDatas($result);
633 } else {
634 throw new RestException(304, $this->invoice->error);
635 }
636 }
637
657 public function postContact($id, $contactid, $type, $source = 'external', $notrigger = 0)
658 {
659 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
660 throw new RestException(403);
661 }
662
663 // test source
664 if (empty($source)) {
665 throw new RestException(400, 'Source can not be empty');
666 }
667 $sql_distinct_source = "SELECT DISTINCT source";
668 $sql_distinct_source .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
669 $sql_distinct_source .= " WHERE element LIKE 'facture'";
670 $sql_distinct_source .= " AND source is NOT NULL";
671 $sql_distinct_source .= " AND active != 0";
672 $source_result = $this->db->query($sql_distinct_source);
673 $source_array = array();
674
675 if ($source_result) {
676 $num = $this->db->num_rows($source_result);
677 $i = 0;
678 while ($i < $num) {
679 $obj = $this->db->fetch_object($source_result);
680 $source_kind = (string) $obj->source;
681 array_push($source_array, $source_kind);
682 dol_syslog("source_kind=".$source_kind);
683 $i++;
684 }
685 } else {
686 throw new RestException(503, 'Error when retrieving a list of invoice contact sources: '.$this->db->lasterror());
687 }
688 if (!in_array($source, (array) $source_array, true)) {
689 throw new RestException(400, 'Combo of Source='.$source.' and Type='.$type.' not found in dictionary with active invoice contact types');
690 }
691
692 // test type
693 if (empty($type)) {
694 throw new RestException(400, 'type can not be empty');
695 }
696 // variable called type here, but code in dictionary and database
697 $sql_distinct_type = "SELECT DISTINCT code";
698 $sql_distinct_type .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
699 $sql_distinct_type .= " WHERE element LIKE 'facture'";
700 $sql_distinct_type .= " AND source='".$this->db->escape($source)."'";
701 $sql_distinct_type .= " AND code is NOT NULL";
702 $sql_distinct_type .= " AND active != 0";
703 $type_result = $this->db->query($sql_distinct_type);
704 $type_array = array();
705
706 if ($type_result) {
707 $num = $this->db->num_rows($type_result);
708 $i = 0;
709 while ($i < $num) {
710 $obj = $this->db->fetch_object($type_result);
711 // variable called type here, but code in dictionary and database
712 $type_kind = (string) $obj->code;
713 array_push($type_array, $type_kind);
714 dol_syslog("type_kind=".$type_kind);
715 $i++;
716 }
717 } else {
718 throw new RestException(503, 'Error when retrieving a list of invoice contact types: '.$this->db->lasterror());
719 }
720 if (!in_array($type, (array) $type_array, true)) {
721 throw new RestException(400, 'Combo of Type='.$type.' and Source='.$source.' not found in dictionary with active invoice contact types');
722 }
723
724 // tests done, let's get it
725 $result = $this->invoice->fetch($id);
726 if (!$result) {
727 throw new RestException(404, 'Invoice not found');
728 }
729 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
730 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
731 }
732
733 $result = $this->invoice->add_contact($contactid, $type, $source, $notrigger);
734
735 if ($result == 0) {
736 throw new RestException(400, 'Already exists: Contact='.$contactid.' is already linked to the invoice='.$id.' as source='.$source.' and type='.$type);
737 } elseif ($result == -1) {
738 throw new RestException(400, 'Wrong contact='.$contactid);
739 } elseif ($result == -2) {
740 throw new RestException(400, 'Wrong type='.$type);
741 } elseif ($result == -3) {
742 throw new RestException(400, 'Not allowed contacts');
743 } elseif ($result == -4) {
744 throw new RestException(400, 'ErrorCommercialNotAllowedForThirdparty');
745 } elseif ($result == -5) {
746 throw new RestException(400, 'Trigger failed');
747 } elseif ($result == -6) {
748 throw new RestException(400, 'DB_ERROR_RECORD_ALREADY_EXISTS');
749 } elseif ($result == -7) {
750 throw new RestException(400, 'Some other error');
751 }
752
753 if (!$result) {
754 throw new RestException(500, 'Error when added the contact');
755 }
756
757 return array(
758 'success' => array(
759 'code' => 200,
760 'message' => 'Contact='.$contactid.' linked to the invoice='.$id.' as '.$source.' '.$type
761 )
762 );
763 }
764
780 public function getContacts($id, $type = '')
781 {
782 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
783 throw new RestException(403);
784 }
785
786 $result = $this->invoice->fetch($id);
787 if (!$result) {
788 throw new RestException(404, 'Invoice not found');
789 }
790
791 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
792 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
793 }
794
795 $contacts = $this->invoice->liste_contact(-1, 'external', 0, $type);
796 $socpeoples = $this->invoice->liste_contact(-1, 'internal', 0, $type);
797
798 $contacts = array_merge($contacts, $socpeoples);
799
800 return $contacts;
801 }
802
819 public function deleteContact($id, $contactid, $type)
820 {
821 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
822 throw new RestException(403);
823 }
824
825 $result = $this->invoice->fetch($id);
826
827 if (!$result) {
828 throw new RestException(404, 'Invoice not found');
829 }
830
831 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
832 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
833 }
834
835 $contacts = $this->invoice->liste_contact();
836
837 foreach ($contacts as $contact) {
838 if ($contact['id'] == $contactid && $contact['code'] == $type) {
839 $result = $this->invoice->delete_contact($contact['rowid']);
840
841 if (!$result) {
842 throw new RestException(500, 'Error when deleted the contact');
843 }
844 }
845 }
846
847 return $this->_cleanObjectDatas($this->invoice);
848 }
849
866 public function deleteLine($id, $lineid)
867 {
868 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
869 throw new RestException(403);
870 }
871 if (empty($lineid)) {
872 throw new RestException(400, 'Line ID is mandatory');
873 }
874
875 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
876 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
877 }
878
879 $result = $this->invoice->fetch($id);
880 if (!$result) {
881 throw new RestException(404, 'Invoice not found');
882 }
883 if ($this->invoice->status != 0) {
884 throw new RestException(403, 'Invoice not in Draft Status : '.$this->invoice->getLibStatut(1));
885 }
886
887 $updateRes = $this->invoice->deleteLine($lineid, $id);
888 if ($updateRes > 0) {
889 return $this->get($id);
890 } else {
891 throw new RestException(405, $this->invoice->error);
892 }
893 }
894
906 public function put($id, $request_data = null)
907 {
908 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
909 throw new RestException(403);
910 }
911 if ($id == 0) {
912 throw new RestException(400, 'No invoice with id=0 can exist');
913 }
914 $result = $this->invoice->fetch($id);
915 if (!$result) {
916 throw new RestException(404, 'Invoice not found');
917 }
918
919 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
920 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
921 }
922
923 foreach ($request_data as $field => $value) {
924 if ($field == 'id') {
925 continue;
926 }
927 if ($field === 'caller') {
928 // 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
929 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
930 continue;
931 }
932 if ($field == 'array_options' && is_array($value)) {
933 foreach ($value as $index => $val) {
934 $this->invoice->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->invoice);
935 }
936 continue;
937 }
938
939 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
940
941 // If cond reglement => update date lim reglement
942 if ($field == 'cond_reglement_id') {
943 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
944 }
945 }
946
947 // update bank account
948 if (!empty($this->invoice->fk_account)) {
949 if ($this->invoice->setBankAccount((int) $this->invoice->fk_account) == 0) {
950 throw new RestException(400, $this->invoice->error);
951 }
952 }
953
954 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
955 return $this->get($id);
956 } else {
957 throw new RestException(500, $this->invoice->error);
958 }
959 }
960
971 public function delete($id)
972 {
973 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
974 throw new RestException(403);
975 }
976 if ($id == 0) {
977 throw new RestException(400, 'No invoice with id=0 can exist');
978 }
979 $result = $this->invoice->fetch($id);
980 if (!$result) {
981 throw new RestException(404, 'Invoice not found');
982 }
983
984 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
985 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
986 }
987
988 $result = $this->invoice->delete(DolibarrApiAccess::$user);
989 if ($result < 0) {
990 throw new RestException(500, 'Error when deleting invoice');
991 } elseif ($result == 0) {
992 throw new RestException(403, 'Invoice not erasable');
993 }
994
995 return array(
996 'success' => array(
997 'code' => 200,
998 'message' => 'Invoice deleted'
999 )
1000 );
1001 }
1002
1030 public function postLine($id, $request_data = null)
1031 {
1032 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1033 throw new RestException(403);
1034 }
1035
1036 $result = $this->invoice->fetch($id);
1037 if (!$result) {
1038 throw new RestException(404, 'Invoice not found');
1039 }
1040
1041 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1042 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1043 }
1044
1045 $request_data = (object) $request_data;
1046
1047 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
1048 $request_data->label = sanitizeVal($request_data->label);
1049
1050 // Reset fk_parent_line for no child products and special product
1051 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
1052 $request_data->fk_parent_line = 0;
1053 }
1054
1055 // calculate pa_ht
1056 $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);
1057 $pa_ht = $marginInfos[0];
1058
1059 $updateRes = $this->invoice->addline(
1060 $request_data->desc,
1061 $request_data->subprice,
1062 $request_data->qty,
1063 $request_data->tva_tx,
1064 $request_data->localtax1_tx,
1065 $request_data->localtax2_tx,
1066 $request_data->fk_product,
1067 $request_data->remise_percent,
1068 $request_data->date_start,
1069 $request_data->date_end,
1070 $request_data->fk_code_ventilation,
1071 $request_data->info_bits,
1072 $request_data->fk_remise_except,
1073 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
1074 $request_data->subprice,
1075 $request_data->product_type,
1076 $request_data->rang,
1077 $request_data->special_code,
1078 $request_data->origin,
1079 $request_data->origin_id,
1080 $request_data->fk_parent_line,
1081 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
1082 $pa_ht,
1083 $request_data->label,
1084 $request_data->array_options,
1085 $request_data->situation_percent,
1086 $request_data->fk_prev_id,
1087 $request_data->fk_unit,
1088 0,
1089 $request_data->ref_ext
1090 );
1091
1092 if ($updateRes < 0) {
1093 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
1094 }
1095
1096 return $updateRes;
1097 }
1098
1119 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
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->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
1134 if ($result < 0) {
1135 throw new RestException(500, 'Error : '.$this->invoice->error);
1136 }
1137
1138 $result = $this->invoice->fetch($id);
1139 if (!$result) {
1140 throw new RestException(404, 'Invoice not found');
1141 }
1142
1143 // test already done
1144 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1145 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1146 // }
1147
1148 return $this->_cleanObjectDatas($this->invoice);
1149 }
1150
1151
1152
1169 public function settodraft($id, $idwarehouse = -1)
1170 {
1171 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1172 throw new RestException(403);
1173 }
1174 $result = $this->invoice->fetch($id);
1175 if (!$result) {
1176 throw new RestException(404, 'Invoice not found');
1177 }
1178
1179 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1180 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1181 }
1182
1183 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
1184 if ($result == 0) {
1185 throw new RestException(304, 'Nothing done.');
1186 }
1187 if ($result < 0) {
1188 throw new RestException(500, 'Error : '.$this->invoice->error);
1189 }
1190
1191 $result = $this->invoice->fetch($id);
1192 if (!$result) {
1193 throw new RestException(404, 'Invoice not found');
1194 }
1195
1196 return $this->_cleanObjectDatas($this->invoice);
1197 }
1198
1199
1219 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1220 {
1221 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1222 throw new RestException(403);
1223 }
1224 $result = $this->invoice->fetch($id);
1225 if (!$result) {
1226 throw new RestException(404, 'Invoice not found');
1227 }
1228
1229 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1230 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1231 }
1232
1233 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
1234 if ($result == 0) {
1235 throw new RestException(304, 'Error nothing done. May be object is already validated');
1236 }
1237 if ($result < 0) {
1238 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
1239 }
1240
1241 $result = $this->invoice->fetch($id);
1242 if (!$result) {
1243 throw new RestException(404, 'Invoice not found');
1244 }
1245
1246 // test already done
1247 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1248 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1249 // }
1250
1251 // copy from order
1252 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1253 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', (string) $this->invoice->ref);
1254
1255 return $this->_cleanObjectDatas($this->invoice);
1256 }
1257
1275 public function settopaid($id, $close_code = '', $close_note = '')
1276 {
1277 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1278 throw new RestException(403);
1279 }
1280 $result = $this->invoice->fetch($id);
1281 if (!$result) {
1282 throw new RestException(404, 'Invoice not found');
1283 }
1284
1285 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1286 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1287 }
1288
1289 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1290 if ($result == 0) {
1291 throw new RestException(304, 'Error nothing done. May be object is already validated');
1292 }
1293 if ($result < 0) {
1294 throw new RestException(500, 'Error : '.$this->invoice->error);
1295 }
1296
1297
1298 $result = $this->invoice->fetch($id);
1299 if (!$result) {
1300 throw new RestException(404, 'Invoice not found');
1301 }
1302
1303 // test already done
1304 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1305 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1306 // }
1307
1308 return $this->_cleanObjectDatas($this->invoice);
1309 }
1310
1311
1327 public function settounpaid($id)
1328 {
1329 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1330 throw new RestException(403);
1331 }
1332 $result = $this->invoice->fetch($id);
1333 if (!$result) {
1334 throw new RestException(404, 'Invoice not found');
1335 }
1336
1337 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1338 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1339 }
1340
1341 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1342 if ($result == 0) {
1343 throw new RestException(304, 'Nothing done');
1344 }
1345 if ($result < 0) {
1346 throw new RestException(500, 'Error : '.$this->invoice->error);
1347 }
1348
1349
1350 $result = $this->invoice->fetch($id);
1351 if (!$result) {
1352 throw new RestException(404, 'Invoice not found');
1353 }
1354
1355 // test already done
1356 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1357 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1358 // }
1359
1360 return $this->_cleanObjectDatas($this->invoice);
1361 }
1362
1373 public function getDiscount($id)
1374 {
1375 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1376
1377 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1378 throw new RestException(403);
1379 }
1380
1381 $result = $this->invoice->fetch($id);
1382 if (!$result) {
1383 throw new RestException(404, 'Invoice not found');
1384 }
1385
1386 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1387 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1388 }
1389
1390 $discountcheck = new DiscountAbsolute($this->db);
1391 $result = $discountcheck->fetch(0, $this->invoice->id);
1392
1393 if ($result == 0) {
1394 throw new RestException(404, 'Discount not found');
1395 }
1396 if ($result < 0) {
1397 throw new RestException(500, $discountcheck->error);
1398 }
1399
1400 return parent::_cleanObjectDatas($discountcheck);
1401 }
1402
1419 {
1420 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1421
1422 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1423 throw new RestException(403);
1424 }
1425
1426 $result = $this->invoice->fetch($id);
1427 if (!$result) {
1428 throw new RestException(404, 'Invoice not found');
1429 }
1430
1431 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1432 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1433 }
1434
1435 if ($this->invoice->paye) { // TODO Replace by a test on status
1436 throw new RestException(500, 'Alreay paid');
1437 }
1438
1439 $this->invoice->fetch($id);
1440 $this->invoice->fetch_thirdparty();
1441
1442 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1443 $discountcheck = new DiscountAbsolute($this->db);
1444 $result = $discountcheck->fetch(0, $this->invoice->id);
1445
1446 $canconvert = 0;
1447 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1448 $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)
1449 }
1450 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1451 $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)
1452 }
1453 if ($canconvert) {
1454 $this->db->begin();
1455
1456 $amount_ht = $amount_tva = $amount_ttc = array();
1457 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1458 '
1459 @phan-var-force array<string,float> $amount_ht
1460 @phan-var-force array<string,float> $amount_tva
1461 @phan-var-force array<string,float> $amount_ttc
1462 @phan-var-force array<string,float> $multicurrency_amount_ht
1463 @phan-var-force array<string,float> $multicurrency_amount_tva
1464 @phan-var-force array<string,float> $multicurrency_amount_ttc
1465 ';
1466
1467 // Loop on each vat rate
1468 $i = 0;
1469 foreach ($this->invoice->lines as $line) {
1470 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1471 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1472 $amount_ht[$line->tva_tx] = 0.0;
1473 $amount_tva[$line->tva_tx] = 0.0;
1474 $amount_ttc[$line->tva_tx] = 0.0;
1475 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1476 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1477 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1478 }
1479 // no need to create discount if amount is null
1480 $amount_ht[$line->tva_tx] += $line->total_ht;
1481 $amount_tva[$line->tva_tx] += $line->total_tva;
1482 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1483 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1484 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1485 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1486 $i++;
1487 }
1488 }
1489
1490 // Insert one discount by VAT rate category
1491 $discount = new DiscountAbsolute($this->db);
1492 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1493 $discount->description = '(CREDIT_NOTE)';
1494 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1495 $discount->description = '(DEPOSIT)';
1496 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1497 $discount->description = '(EXCESS RECEIVED)';
1498 } else {
1499 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1500 }
1501
1502 $discount->fk_soc = $this->invoice->socid;
1503 $discount->socid = $this->invoice->socid;
1504 $discount->fk_facture_source = $this->invoice->id;
1505
1506 $error = 0;
1507
1508 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1509 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1510
1511 // Total payments
1512 $sql = 'SELECT SUM(pf.amount) as total_payments';
1513 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1514 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1515 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1516 $sql .= ' AND pf.fk_paiement = p.rowid';
1517 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1518 $resql = $this->db->query($sql);
1519 if (!$resql) {
1520 dol_print_error($this->db);
1521 }
1522
1523 $res = $this->db->fetch_object($resql);
1524 $total_payments = $res->total_payments;
1525
1526 // Total credit note and deposit
1527 $total_creditnote_and_deposit = 0;
1528 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1529 $sql .= " re.description, re.fk_facture_source";
1530 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1531 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1532 $resql = $this->db->query($sql);
1533 if (!empty($resql)) {
1534 while ($obj = $this->db->fetch_object($resql)) {
1535 $total_creditnote_and_deposit += $obj->amount_ttc;
1536 }
1537 } else {
1538 dol_print_error($this->db);
1539 }
1540
1541 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1542 $discount->total_ht = $discount->total_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1543 $discount->amount_tva = 0;
1544 $discount->total_tva = 0;
1545 $discount->tva_tx = 0;
1546
1547 $result = $discount->create(DolibarrApiAccess::$user);
1548 if ($result < 0) {
1549 $error++;
1550 }
1551 }
1552 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1553 foreach ($amount_ht as $tva_tx => $xxx) {
1554 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1555 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1556 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1557 $discount->total_ht = abs($amount_ht[$tva_tx]);
1558 $discount->total_tva = abs($amount_tva[$tva_tx]);
1559 $discount->total_ttc = abs($amount_ttc[$tva_tx]);
1560 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1561 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1562 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1563 $discount->multicurrency_total_ht = abs($multicurrency_amount_ht[$tva_tx]);
1564 $discount->multicurrency_total_tva = abs($multicurrency_amount_tva[$tva_tx]);
1565 $discount->multicurrency_total_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1566 $discount->tva_tx = abs((float) $tva_tx);
1567
1568 $result = $discount->create(DolibarrApiAccess::$user);
1569 if ($result < 0) {
1570 $error++;
1571 break;
1572 }
1573 }
1574 }
1575
1576 if (empty($error)) {
1577 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1578 // Set the invoice as paid
1579 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1580 if ($result >= 0) {
1581 $this->db->commit();
1582 } else {
1583 $this->db->rollback();
1584 throw new RestException(500, 'Could not set paid');
1585 }
1586 } else {
1587 $this->db->commit();
1588 }
1589 } else {
1590 $this->db->rollback();
1591 throw new RestException(500, 'Discount creation error');
1592 }
1593 }
1594
1595 return $this->_cleanObjectDatas($this->invoice);
1596 }
1597
1616 public function useDiscount($id, $discountid)
1617 {
1618 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1619 throw new RestException(403);
1620 }
1621 if (empty($id)) {
1622 throw new RestException(400, 'Invoice ID is mandatory');
1623 }
1624 if (empty($discountid)) {
1625 throw new RestException(400, 'Discount ID is mandatory');
1626 }
1627
1628 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1629 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1630 }
1631
1632 $result = $this->invoice->fetch($id);
1633 if (!$result) {
1634 throw new RestException(404, 'Invoice not found');
1635 }
1636
1637 $result = $this->invoice->insert_discount($discountid);
1638 if ($result < 0) {
1639 throw new RestException(405, $this->invoice->error);
1640 }
1641
1642 return $result;
1643 }
1644
1663 public function useCreditNote($id, $discountid)
1664 {
1665 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1666
1667 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1668 throw new RestException(403);
1669 }
1670 if (empty($id)) {
1671 throw new RestException(400, 'Invoice ID is mandatory');
1672 }
1673 if (empty($discountid)) {
1674 throw new RestException(400, 'Credit ID is mandatory');
1675 }
1676
1677 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1678 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1679 }
1680 $discount = new DiscountAbsolute($this->db);
1681 $result = $discount->fetch($discountid);
1682 if (!$result) {
1683 throw new RestException(404, 'Credit not found');
1684 }
1685
1686 $result = $discount->link_to_invoice(0, $id);
1687 if ($result < 0) {
1688 throw new RestException(405, $discount->error);
1689 }
1690
1691 return $result;
1692 }
1693
1711 public function getPayments($id)
1712 {
1713 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1714 throw new RestException(403);
1715 }
1716 if (empty($id)) {
1717 throw new RestException(400, 'Invoice ID is mandatory');
1718 }
1719
1720 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1721 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1722 }
1723
1724 $result = $this->invoice->fetch($id);
1725 if (!$result) {
1726 throw new RestException(404, 'Invoice not found');
1727 }
1728
1729 $result = $this->invoice->getListOfPayments();
1730 if (!is_array($result) && $result < 0) {
1731 throw new RestException(405, $this->invoice->error);
1732 }
1733
1734 return $result;
1735 }
1736
1737
1761 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1762 {
1763 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1764
1765 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
1766 throw new RestException(403);
1767 }
1768 if (empty($id)) {
1769 throw new RestException(400, 'Invoice ID is mandatory');
1770 }
1771
1772 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1773 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1774 }
1775
1776 if (isModEnabled("bank")) {
1777 if (empty($accountid)) {
1778 throw new RestException(400, 'Account ID is mandatory');
1779 }
1780 }
1781
1782 if (empty($paymentid)) {
1783 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1784 }
1785
1786
1787 $result = $this->invoice->fetch($id);
1788 if (!$result) {
1789 throw new RestException(404, 'Invoice not found');
1790 }
1791
1792 // Calculate amount to pay
1793 $totalpaid = $this->invoice->getSommePaiement();
1794 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1795 $totaldeposits = $this->invoice->getSumDepositsUsed();
1796
1797 $this->db->begin();
1798
1799 $amounts = array();
1800 $multicurrency_amounts = array();
1801
1802 // Clean parameters amount if payment is for a credit note
1803 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1804 $resteapayer = price2num($this->invoice->total_ttc + $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1805 $amounts[$id] = (float) price2num(-1 * abs((float) $resteapayer), 'MT');
1806 // Multicurrency
1807 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1808 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1809 } else {
1810 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1811 $amounts[$id] = (float) $resteapayer;
1812 // Multicurrency
1813 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1814 $multicurrency_amounts[$id] = (float) $newvalue;
1815 }
1816
1817 // Creation of payment line
1818 $paymentobj = new Paiement($this->db);
1819 if (is_numeric($datepaye)) {
1820 $paymentobj->datepaye = $datepaye;
1821 } else {
1822 $paymentobj->datepaye = dol_stringtotime($datepaye);
1823 }
1824 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1825 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1826 $paymentobj->paiementid = $paymentid;
1827 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1828 $paymentobj->num_payment = $num_payment;
1829 $paymentobj->note_private = $comment;
1830
1831 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1832 if ($payment_id < 0) {
1833 $this->db->rollback();
1834 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1835 }
1836
1837 if (isModEnabled("bank")) {
1838 $label = '(CustomerInvoicePayment)';
1839
1840 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1841 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1842 }
1843 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1844 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1845 }
1846 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1847 if ($result < 0) {
1848 $this->db->rollback();
1849 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1850 }
1851 }
1852
1853 $this->db->commit();
1854
1855 return $payment_id;
1856 }
1857
1888 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1889 {
1890 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1891
1892 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
1893 throw new RestException(403);
1894 }
1895 foreach ($arrayofamounts as $id => $amount) {
1896 if (empty($id)) {
1897 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1898 }
1899 if (!DolibarrApi::_checkAccessToResource('facture', (int) $id)) {
1900 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1901 }
1902 }
1903
1904 if (isModEnabled("bank")) {
1905 if (empty($accountid)) {
1906 throw new RestException(400, 'Account ID is mandatory');
1907 }
1908 }
1909 if (empty($paymentid)) {
1910 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1911 }
1912
1913 $this->db->begin();
1914
1915 $amounts = array();
1916 $multicurrency_amounts = array();
1917
1918 // Loop on each invoice to pay
1919 foreach ($arrayofamounts as $id => $amountarray) {
1920 $id = (int) $id; // Ensure $id is seen as int, required by function calls and array indexes.
1921 $result = $this->invoice->fetch($id);
1922 if (!$result) {
1923 $this->db->rollback();
1924 throw new RestException(404, 'Invoice ID '.$id.' not found');
1925 }
1926
1927 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1928 $this->db->rollback();
1929 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1930 }
1931
1932 $is_multicurrency = 0;
1933 $total_ttc = $this->invoice->total_ttc;
1934
1935 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1936 $is_multicurrency = 1;
1937 $total_ttc = $this->invoice->multicurrency_total_ttc;
1938 }
1939
1940 // Calculate amount to pay
1941 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1942 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1943 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1944 $remainstopay = $amount = (float) price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1945
1946 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1947 $amount = (float) price2num($amountarray["amount"], 'MT');
1948 }
1949
1950 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1951 $amount = (float) price2num($amountarray["multicurrency_amount"], 'MT');
1952 }
1953
1954 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
1955 $this->db->rollback();
1956 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1957 }
1958
1959 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1960 $amount = (float) price2num(-1 * abs((float) $amount), 'MT');
1961 }
1962
1963 if ($is_multicurrency) {
1964 $amounts[$id] = null;
1965 // Multicurrency
1966 $multicurrency_amounts[$id] = (float) $amount;
1967 } else {
1968 $amounts[$id] = (float) $amount;
1969 // Multicurrency
1970 $multicurrency_amounts[$id] = null;
1971 }
1972 }
1973
1974 // Creation of payment line
1975 $paymentobj = new Paiement($this->db);
1976 if (is_numeric($datepaye)) {
1977 $paymentobj->datepaye = $datepaye;
1978 } else {
1979 $paymentobj->datepaye = dol_stringtotime($datepaye);
1980 }
1981 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1982 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1983 $paymentobj->paiementid = $paymentid;
1984 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1985 $paymentobj->num_payment = $num_payment;
1986 $paymentobj->note_private = $comment;
1987 $paymentobj->ref_ext = $ref_ext;
1988 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1989 if ($payment_id < 0) {
1990 $this->db->rollback();
1991 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1992 }
1993 if (isModEnabled("bank")) {
1994 $label = '(CustomerInvoicePayment)';
1995 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1996 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1997 }
1998 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1999 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
2000 }
2001 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
2002 if ($result < 0) {
2003 $this->db->rollback();
2004 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
2005 }
2006 }
2007
2008 $this->db->commit();
2009
2010 return $payment_id;
2011 }
2012
2031 public function putPayment($id, $num_payment = '')
2032 {
2033 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2034
2035 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
2036 throw new RestException(403);
2037 }
2038 if (empty($id)) {
2039 throw new RestException(400, 'Payment ID is mandatory');
2040 }
2041
2042 $paymentobj = new Paiement($this->db);
2043 $result = $paymentobj->fetch($id);
2044
2045 if (!$result) {
2046 throw new RestException(404, 'Payment not found');
2047 }
2048
2049 // Check all invoices of the payment to see if the user has permission on them for the object level permission test
2050 $tmparray = $paymentobj->getBillsArray();
2051 foreach ($tmparray as $tmpinvoiceid) {
2052 if (!DolibarrApi::_checkAccessToResource('facture', $tmpinvoiceid)) {
2053 throw new RestException(403, 'Payment is on invoices that are not all allowed for login '.DolibarrApiAccess::$user->login);
2054 }
2055 }
2056
2057 if (!empty($num_payment)) {
2058 $result = $paymentobj->update_num($num_payment);
2059 if ($result < 0) {
2060 throw new RestException(500, 'Error when updating the payment num');
2061 }
2062 }
2063
2064 return [
2065 'success' => [
2066 'code' => 200,
2067 'message' => 'Payment updated'
2068 ]
2069 ];
2070 }
2071
2072 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2082 protected function _cleanObjectDatas($object)
2083 {
2084 // phpcs:enable
2085 $object = parent::_cleanObjectDatas($object);
2086
2087 unset($object->note);
2088 unset($object->address);
2089 unset($object->barcode_type);
2090 unset($object->barcode_type_code);
2091 unset($object->barcode_type_label);
2092 unset($object->barcode_type_coder);
2093 unset($object->canvas);
2094
2095 return $object;
2096 }
2097
2106 private function _validate($data)
2107 {
2108 if ($data === null) {
2109 $data = array();
2110 }
2111 $invoice = array();
2112 foreach (Invoices::$FIELDS as $field) {
2113 if (!isset($data[$field])) {
2114 throw new RestException(400, "$field field missing");
2115 }
2116 $invoice[$field] = $data[$field];
2117 }
2118 return $invoice;
2119 }
2120
2121
2137 public function getTemplateInvoice($id, $contact_list = 1)
2138 {
2139 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
2140 }
2141
2142
2170 public function indexTemplateInvoices($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
2171 {
2172 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2173 throw new RestException(403);
2174 }
2175
2176 $obj_ret = array();
2177
2178 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
2179 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
2180
2181
2182 // If the internal user must only see his customers, force searching by him
2183 $search_sale = 0;
2184 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
2185 $search_sale = DolibarrApiAccess::$user->id;
2186 }
2187
2188 $sql = "SELECT t.rowid";
2189 $sql .= " FROM ".MAIN_DB_PREFIX."facture_rec AS t";
2190 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
2191 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_rec_extrafields AS ef ON (ef.fk_object = t.rowid)";
2192 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
2193 if ($socids) {
2194 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
2195 }
2196
2197 // Search on sale representative
2198 if ($search_sale && $search_sale != '-1') {
2199 if ($search_sale == -2) {
2200 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux AS sc WHERE sc.fk_soc = t.fk_soc)";
2201 } elseif ($search_sale > 0) {
2202 $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).")";
2203 }
2204 }
2205
2206 // Filter by status
2207 if ($status == 'active') {
2208 $sql .= " AND t.suspended = 0 AND t.frequency IS NOT NULL";
2209 }
2210 if ($status == 'suspended') {
2211 $sql .= " AND t.suspended = 1 AND t.frequency IS NOT NULL";
2212 }
2213 if ($status == 'draft') {
2214 $sql .= " AND t.frequency IS NULL";
2215 }
2216 // add sql filters
2217 if ($sqlfilters) {
2218 $errormessage = '';
2219 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
2220 if ($errormessage) {
2221 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
2222 }
2223 }
2224
2225 //this query will return total template invoices with the filters given
2226 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
2227
2228 $sql .= $this->db->order($sortfield, $sortorder);
2229 if ($limit) {
2230 if ($page < 0) {
2231 $page = 0;
2232 }
2233 $offset = $limit * $page;
2234
2235 $sql .= $this->db->plimit($limit + 1, $offset);
2236 }
2237
2238 $result = $this->db->query($sql);
2239 if ($result) {
2240 $i = 0;
2241 $num = $this->db->num_rows($result);
2242 $min = min($num, ($limit <= 0 ? $num : $limit));
2243 while ($i < $min) {
2244 $obj = $this->db->fetch_object($result);
2245 $factureRec = new FactureRec($this->db);
2246 if ($factureRec->fetch($obj->rowid) > 0) {
2247 if ($loadlinkedobjects) {
2248 // retrieve linked objects
2249 $factureRec->fetchObjectLinked();
2250 }
2251
2252 if (!$withLines) {
2253 unset($factureRec->lines);
2254 }
2255
2256 $obj_ret[] = $this->_filterObjectProperties($this->_cleanTemplateObjectDatas($factureRec), $properties);
2257 }
2258 $i++;
2259 }
2260 } else {
2261 throw new RestException(503, 'Error when retrieving recurring invoice templates: '.$this->db->lasterror());
2262 }
2263
2264 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
2265 if ($pagination_data) {
2266 $totalsResult = $this->db->query($sqlTotals);
2267 $total = $this->db->fetch_object($totalsResult)->total;
2268
2269 $tmp = $obj_ret;
2270 $obj_ret = array();
2271
2272 $obj_ret['data'] = $tmp;
2273 $obj_ret['pagination'] = array(
2274 'total' => (int) $total,
2275 'page' => $page,
2276 'page_count' => ceil((int) $total / $limit),
2277 'limit' => $limit
2278 );
2279 }
2280
2281 return $obj_ret;
2282 }
2283
2297 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
2298 {
2299 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2300 throw new RestException(403);
2301 }
2302
2303 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
2304 if (!$result) {
2305 throw new RestException(404, 'Template invoice not found');
2306 }
2307
2308 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
2309 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2310 }
2311
2312 // Add external contacts ids
2313 if ($contact_list > -1) {
2314 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
2315 if (is_array($tmparray)) {
2316 $this->template_invoice->contacts_ids = $tmparray;
2317 }
2318 }
2319
2320 $this->template_invoice->fetchObjectLinked();
2321 return $this->_cleanTemplateObjectDatas($this->template_invoice);
2322 }
2323
2324
2325 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2333 {
2334 // phpcs:enable
2335 $object = parent::_cleanObjectDatas($object);
2336
2337 unset($object->note);
2338 unset($object->address);
2339 unset($object->barcode_type);
2340 unset($object->barcode_type_code);
2341 unset($object->barcode_type_label);
2342 unset($object->barcode_type_coder);
2343 unset($object->canvas);
2344
2345 return $object;
2346 }
2347}
$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:451
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.