dolibarr 25.0.0-alpha
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';
27require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
28
29
37class Invoices extends DolibarrApi
38{
42 public static $FIELDS = array(
43 'socid',
44 );
45
49 private $invoice;
50
54 private $template_invoice;
55
56
60 public function __construct()
61 {
62 global $db;
63 $this->db = $db;
64 $this->invoice = new Facture($this->db);
65 $this->template_invoice = new FactureRec($this->db);
66 }
67
83 public function get($id, $contact_list = 1, $properties = '', $withLines = true)
84 {
85 $invoice = $this->_fetch($id, '', '', $contact_list);
86
87 if (!$withLines) {
88 unset($invoice->lines);
89 }
90
91 return $this->_filterObjectProperties($invoice, $properties);
92 }
93
109 public function getByRef($ref, $contact_list = 1)
110 {
111 return $this->_fetch(0, $ref, '', $contact_list);
112 }
113
129 public function getByRefExt($ref_ext, $contact_list = 1)
130 {
131 return $this->_fetch(0, '', $ref_ext, $contact_list);
132 }
133
147 private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
148 {
149 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
150 throw new RestException(403);
151 }
152 if (empty($id) && empty($ref) && empty($ref_ext)) {
153 throw new RestException(400, 'No invoice can be found with no criteria');
154 }
155 $result = $this->invoice->fetch($id, $ref, $ref_ext);
156 if (!$result) {
157 throw new RestException(404, 'Invoice not found');
158 }
159
160 // Get payment details
161 $this->invoice->totalpaid = $this->invoice->getSommePaiement();
162 $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
163 $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed();
164 $this->invoice->remaintopay = price2num($this->invoice->total_ttc - $this->invoice->totalpaid - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits, 'MT');
165
166 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
167 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
168 }
169
170 // Retrieve credit note ids
171 $this->invoice->getListIdAvoirFromInvoice();
172
173 // Add external contacts ids
174 if ($contact_list > -1) {
175 $tmparray = $this->invoice->liste_contact(-1, 'external', $contact_list);
176 if (is_array($tmparray)) {
177 $this->invoice->contacts_ids = $tmparray;
178 }
179 $tmparray = $this->invoice->liste_contact(-1, 'internal', $contact_list);
180 if (is_array($tmparray)) {
181 $this->invoice->contacts_ids = $tmparray;
182 }
183 }
184
185 $this->invoice->fetchObjectLinked();
186
187 // Add online_payment_url, copied from order
188 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
189 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', (string) $this->invoice->ref);
190
191 return $this->_cleanObjectDatas($this->invoice);
192 }
193
219 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
220 {
221 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
222 throw new RestException(403);
223 }
224
225 $obj_ret = array();
226
227 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
228 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
229
230 // If the internal user must only see his customers, force searching by him
231 $search_sale = 0;
232 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
233 $search_sale = DolibarrApiAccess::$user->id;
234 }
235
236 $sql = "SELECT t.rowid";
237 $sql .= " FROM ".MAIN_DB_PREFIX."facture AS t";
238 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
239 $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
240 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
241 if ($socids) {
242 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
243 }
244 // Search on sale representative
245 if ($search_sale && $search_sale != '-1') {
246 if ($search_sale == -2) {
247 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
248 } elseif ($search_sale > 0) {
249 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
250 }
251 }
252 // An unknown value used to be ignored, so the whole list came back as if it were the filtered one
253 if ((string) $status !== '' && !in_array($status, array('draft', 'unpaid', 'paid', 'cancelled'), true)) {
254 throw new RestException(400, "Bad value for parameter status. Expected one of: draft, unpaid, paid, cancelled");
255 }
256 // Filter by status
257 if ($status == 'draft') {
258 $sql .= " AND t.fk_statut IN (0)";
259 }
260 if ($status == 'unpaid') {
261 $sql .= " AND t.fk_statut IN (1)";
262 }
263 if ($status == 'paid') {
264 $sql .= " AND t.fk_statut IN (2)";
265 }
266 if ($status == 'cancelled') {
267 $sql .= " AND t.fk_statut IN (3)";
268 }
269 // Add sql filters
270 if ($sqlfilters) {
271 $errormessage = '';
272 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
273 if ($errormessage) {
274 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
275 }
276 }
277
278 //this query will return total invoices with the filters given
279 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
280
281 $sql .= $this->db->order($sortfield, $sortorder);
282 if ($limit) {
283 if ($page < 0) {
284 $page = 0;
285 }
286 $offset = $limit * $page;
287
288 $sql .= $this->db->plimit($limit + 1, $offset);
289 }
290
291 $result = $this->db->query($sql);
292 if ($result) {
293 $i = 0;
294 $num = $this->db->num_rows($result);
295 $min = min($num, ($limit <= 0 ? $num : $limit));
296 while ($i < $min) {
297 $obj = $this->db->fetch_object($result);
298 $invoice_static = new Facture($this->db);
299 if ($invoice_static->fetch($obj->rowid) > 0) {
300 // Get payment details
301 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
302 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
303 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
304 $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
305
306 // Retrieve credit note ids
307 $invoice_static->getListIdAvoirFromInvoice();
308
309 // Add external contacts ids
310 $tmparray = $invoice_static->liste_contact(-1, 'external', 1);
311 if (is_array($tmparray)) {
312 $invoice_static->contacts_ids = $tmparray;
313 }
314
315 if ($loadlinkedobjects) {
316 // retrieve linked objects
317 $invoice_static->fetchObjectLinked();
318 }
319
320 if (!$withLines) {
321 unset($invoice_static->lines);
322 }
323
324 // Add online_payment_url, copied from order
325 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
326 $invoice_static->online_payment_url = getOnlinePaymentUrl(0, 'invoice', (string) $invoice_static->ref);
327
328 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
329 }
330 $i++;
331 }
332 } else {
333 throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror());
334 }
335
336 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
337 if ($pagination_data) {
338 $totalsResult = $this->db->query($sqlTotals);
339 $total = $this->db->fetch_object($totalsResult)->total;
340
341 $tmp = $obj_ret;
342 $obj_ret = [];
343
344 $obj_ret['data'] = $tmp;
345 $obj_ret['pagination'] = [
346 'total' => (int) $total,
347 'page' => $page, //count starts from 0
348 'page_count' => ceil((int) $total / $limit),
349 'limit' => $limit
350 ];
351 }
352
353 return $obj_ret;
354 }
355
366 public function post($request_data = null)
367 {
368 global $conf;
369 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
370 throw new RestException(403, "Insufficiant rights");
371 }
372
373 if (!is_array($request_data)) {
374 $request_data = array();
375 }
376
377 // Check mandatory fields (not using output, only possible exception is important)
378 $this->_validate($request_data);
379
380 // Check thirdparty validity
381 $socid = (int) $request_data['socid'];
382 $thirdpartytmp = new Societe($this->db);
383 $thirdparty_result = $thirdpartytmp->fetch($socid);
384 if ($thirdparty_result < 1) {
385 throw new RestException(404, 'Thirdparty with id='.$socid.' not found or not allowed');
386 }
387 if (!DolibarrApi::_checkAccessToResource('societe', $thirdpartytmp->id)) {
388 throw new RestException(404, 'Thirdparty with id='.$thirdpartytmp->id.' not found or not allowed');
389 }
390
391 foreach ($request_data as $field => $value) {
392 if ($field === 'caller') {
393 // 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
394 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
395 continue;
396 }
397 if ($field == 'id') {
398 throw new RestException(400, 'Creating with id field is forbidden');
399 }
400 if ($field == 'entity' && ((int) $value) != ((int) $conf->entity)) {
401 throw new RestException(403, 'Creating with entity='.((int) $value).' MUST be the same entity='.((int) $conf->entity).' as your API user/key belongs to');
402 }
403
404 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
405 }
406 if (!array_key_exists('date', $request_data)) {
407 $this->invoice->date = dol_now();
408 }
409 /* We keep lines as an array
410 if (isset($request_data["lines"])) {
411 $lines = array();
412 foreach ($request_data["lines"] as $line) {
413 array_push($lines, (object) $line);
414 }
415 $this->invoice->lines = $lines;
416 }*/
417
418 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) {
419 throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
420 }
421 return ((int) $this->invoice->id);
422 }
423
440 public function createInvoiceFromOrder($orderid)
441 {
442 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
443
444 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
445 throw new RestException(403);
446 }
447 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
448 throw new RestException(403);
449 }
450 if (empty($orderid)) {
451 throw new RestException(400, 'Order ID is mandatory');
452 }
453 if (!DolibarrApi::_checkAccessToResource('commande', $orderid)) {
454 throw new RestException(403, 'Access not allowed on order for login '.DolibarrApiAccess::$user->login);
455 }
456
457 $order = new Commande($this->db);
458 $result = $order->fetch($orderid);
459 if (!$result) {
460 throw new RestException(404, 'Order not found');
461 }
462
463 // Refuse orders that cannot be billed, to mirror the GUI (order card "CreateBill" button and list mass action):
464 // this excludes draft and canceled orders, as well as orders already classified as billed.
465 if ($order->status <= Commande::STATUS_DRAFT || !empty($order->billed)) {
466 throw new RestException(405, 'Order '.$order->ref.' is not eligible for invoicing: its status does not allow creating an invoice');
467 }
468
469 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
470 if ($result < 0) {
471 throw new RestException(405, $this->invoice->errorsToString());
472 }
473 $this->invoice->fetchObjectLinked();
474 return $this->_cleanObjectDatas($this->invoice);
475 }
476
492 public function createInvoiceFromContract($contractid)
493 {
494 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
495
496 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
497 throw new RestException(403);
498 }
499 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
500 throw new RestException(403);
501 }
502 if (empty($contractid)) {
503 throw new RestException(400, 'Contract ID is mandatory');
504 }
505
506 $contract = new Contrat($this->db);
507 $result = $contract->fetch($contractid);
508 if (!$result) {
509 throw new RestException(404, 'Contract not found');
510 }
511 if (!DolibarrApi::_checkAccessToResource('contrat', $contract->id)) {
512 throw new RestException(403, 'Access to contract '.$contract->id.' not allowed for login '.DolibarrApiAccess::$user->login);
513 }
514
515 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
516 if ($result < 0) {
517 throw new RestException(405, $this->invoice->errorsToString());
518 }
519 $this->invoice->fetchObjectLinked();
520 return $this->_cleanObjectDatas($this->invoice);
521 }
522
535 public function getLines($id)
536 {
537 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
538 throw new RestException(403);
539 }
540
541 $result = $this->invoice->fetch($id);
542 if (!$result) {
543 throw new RestException(404, 'Invoice not found');
544 }
545
546 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
547 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
548 }
549 $this->invoice->getLinesArray();
550 $result = array();
551 foreach ($this->invoice->lines as $line) {
552 array_push($result, $this->_cleanObjectDatas($line));
553 }
554 return $result;
555 }
556
575 public function putLine($id, $lineid, $request_data = null)
576 {
577 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
578 throw new RestException(403);
579 }
580
581 $result = $this->invoice->fetch($id);
582 if (!$result) {
583 throw new RestException(404, 'Invoice not found');
584 }
585
586 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
587 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
588 }
589
590 $request_data = (object) $request_data;
591
592 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
593 $request_data->label = sanitizeVal($request_data->label);
594
595 $invoiceline = new FactureLigne($this->db);
596 $result = $invoiceline->fetch($lineid);
597 if (!$result) {
598 throw new RestException(404, 'Invoice line not found');
599 }
600
601 if ($invoiceline->fk_facture != $id) {
602 throw new RestException(403, 'Line does not belong to this invoice');
603 }
604
605 $updateRes = $this->invoice->updateline(
606 $lineid,
607 $request_data->desc,
608 $request_data->subprice,
609 $request_data->qty,
610 $request_data->remise_percent,
611 $request_data->date_start,
612 $request_data->date_end,
613 $request_data->tva_tx,
614 $request_data->localtax1_tx,
615 $request_data->localtax2_tx,
616 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
617 $request_data->info_bits,
618 $request_data->product_type,
619 $request_data->fk_parent_line,
620 0,
621 $request_data->fk_fournprice,
622 $request_data->pa_ht,
623 $request_data->label,
624 $request_data->special_code,
625 $request_data->array_options,
626 $request_data->situation_percent,
627 $request_data->fk_unit,
628 $request_data->multicurrency_subprice,
629 0,
630 $request_data->ref_ext,
631 $request_data->rang
632 );
633
634 if ($updateRes > 0) {
635 $result = $this->get($id);
636 unset($result->line);
637 return $this->_cleanObjectDatas($result);
638 } else {
639 throw new RestException(304, $this->invoice->errorsToString());
640 }
641 }
642
662 public function postContact($id, $contactid, $type, $source = 'external', $notrigger = 0)
663 {
664 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
665 throw new RestException(403);
666 }
667
668 // test source
669 if (empty($source)) {
670 throw new RestException(400, 'Source can not be empty');
671 }
672 $sql_distinct_source = "SELECT DISTINCT source";
673 $sql_distinct_source .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
674 $sql_distinct_source .= " WHERE element LIKE 'facture'";
675 $sql_distinct_source .= " AND source is NOT NULL";
676 $sql_distinct_source .= " AND active != 0";
677 $source_result = $this->db->query($sql_distinct_source);
678 $source_array = array();
679
680 if ($source_result) {
681 $num = $this->db->num_rows($source_result);
682 $i = 0;
683 while ($i < $num) {
684 $obj = $this->db->fetch_object($source_result);
685 $source_kind = (string) $obj->source;
686 array_push($source_array, $source_kind);
687 dol_syslog("source_kind=".$source_kind);
688 $i++;
689 }
690 } else {
691 throw new RestException(503, 'Error when retrieving a list of invoice contact sources: '.$this->db->lasterror());
692 }
693 if (!in_array($source, (array) $source_array, true)) {
694 throw new RestException(400, 'Combo of Source='.$source.' and Type='.$type.' not found in dictionary with active invoice contact types');
695 }
696
697 // test type
698 if (empty($type)) {
699 throw new RestException(400, 'type can not be empty');
700 }
701 // variable called type here, but code in dictionary and database
702 $sql_distinct_type = "SELECT DISTINCT code";
703 $sql_distinct_type .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
704 $sql_distinct_type .= " WHERE element LIKE 'facture'";
705 $sql_distinct_type .= " AND source='".$this->db->escape($source)."'";
706 $sql_distinct_type .= " AND code is NOT NULL";
707 $sql_distinct_type .= " AND active != 0";
708 $type_result = $this->db->query($sql_distinct_type);
709 $type_array = array();
710
711 if ($type_result) {
712 $num = $this->db->num_rows($type_result);
713 $i = 0;
714 while ($i < $num) {
715 $obj = $this->db->fetch_object($type_result);
716 // variable called type here, but code in dictionary and database
717 $type_kind = (string) $obj->code;
718 array_push($type_array, $type_kind);
719 dol_syslog("type_kind=".$type_kind);
720 $i++;
721 }
722 } else {
723 throw new RestException(503, 'Error when retrieving a list of invoice contact types: '.$this->db->lasterror());
724 }
725 if (!in_array($type, (array) $type_array, true)) {
726 throw new RestException(400, 'Combo of Type='.$type.' and Source='.$source.' not found in dictionary with active invoice contact types');
727 }
728
729 // tests done, let's get it
730 $result = $this->invoice->fetch($id);
731 if (!$result) {
732 throw new RestException(404, 'Invoice not found');
733 }
734 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
735 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
736 }
737
738 $result = $this->invoice->add_contact($contactid, $type, $source, $notrigger);
739
740 if ($result == 0) {
741 throw new RestException(400, 'Already exists: Contact='.$contactid.' is already linked to the invoice='.$id.' as source='.$source.' and type='.$type);
742 } elseif ($result == -1) {
743 throw new RestException(400, 'Wrong contact='.$contactid);
744 } elseif ($result == -2) {
745 throw new RestException(400, 'Wrong type='.$type);
746 } elseif ($result == -3) {
747 throw new RestException(400, 'Not allowed contacts');
748 } elseif ($result == -4) {
749 throw new RestException(400, 'ErrorCommercialNotAllowedForThirdparty');
750 } elseif ($result == -5) {
751 throw new RestException(400, 'Trigger failed');
752 } elseif ($result == -6) {
753 throw new RestException(400, 'DB_ERROR_RECORD_ALREADY_EXISTS');
754 } elseif ($result == -7) {
755 throw new RestException(400, 'Some other error');
756 }
757
758 if (!$result) {
759 throw new RestException(500, 'Error when added the contact');
760 }
761
762 return array(
763 'success' => array(
764 'code' => 200,
765 'message' => 'Contact='.$contactid.' linked to the invoice='.$id.' as '.$source.' '.$type
766 )
767 );
768 }
769
785 public function getContacts($id, $type = '')
786 {
787 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
788 throw new RestException(403);
789 }
790
791 $result = $this->invoice->fetch($id);
792 if (!$result) {
793 throw new RestException(404, 'Invoice not found');
794 }
795
796 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
797 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
798 }
799
800 $contacts = $this->invoice->liste_contact(-1, 'external', 0, $type);
801 $socpeoples = $this->invoice->liste_contact(-1, 'internal', 0, $type);
802
803 $contacts = array_merge($contacts, $socpeoples);
804
805 return $contacts;
806 }
807
824 public function deleteContact($id, $contactid, $type)
825 {
826 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
827 throw new RestException(403);
828 }
829
830 $result = $this->invoice->fetch($id);
831
832 if (!$result) {
833 throw new RestException(404, 'Invoice not found');
834 }
835
836 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
837 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
838 }
839
840 $contacts = $this->invoice->liste_contact();
841
842 foreach ($contacts as $contact) {
843 if ($contact['id'] == $contactid && $contact['code'] == $type) {
844 $result = $this->invoice->delete_contact($contact['rowid']);
845
846 if (!$result) {
847 throw new RestException(500, 'Error when deleted the contact');
848 }
849 }
850 }
851
852 return $this->_cleanObjectDatas($this->invoice);
853 }
854
871 public function deleteLine($id, $lineid)
872 {
873 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
874 throw new RestException(403);
875 }
876 if (empty($lineid)) {
877 throw new RestException(400, 'Line ID is mandatory');
878 }
879
880 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
881 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
882 }
883
884 $result = $this->invoice->fetch($id);
885 if (!$result) {
886 throw new RestException(404, 'Invoice not found');
887 }
888 if ($this->invoice->status != 0) {
889 throw new RestException(403, 'Invoice not in Draft Status : '.$this->invoice->getLibStatut(1));
890 }
891
892 $updateRes = $this->invoice->deleteLine($lineid, $id);
893 if ($updateRes > 0) {
894 return $this->get($id);
895 } else {
896 throw new RestException(405, $this->invoice->errorsToString());
897 }
898 }
899
911 public function put($id, $request_data = null)
912 {
913 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
914 throw new RestException(403);
915 }
916 if ($id == 0) {
917 throw new RestException(400, 'No invoice with id=0 can exist');
918 }
919 $result = $this->invoice->fetch($id);
920 if (!$result) {
921 throw new RestException(404, 'Invoice not found');
922 }
923
924 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
925 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
926 }
927
928 foreach ($request_data as $field => $value) {
929 if ($field == 'id') {
930 continue;
931 }
932 if ($field === 'caller') {
933 // 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
934 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
935 continue;
936 }
937 if ($field == 'array_options' && is_array($value)) {
938 foreach ($value as $index => $val) {
939 $this->invoice->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->invoice);
940 }
941 continue;
942 }
943
944 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
945
946 // If cond reglement => update date lim reglement
947 if ($field == 'cond_reglement_id') {
948 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
949 }
950 }
951
952 // update bank account
953 if (!empty($this->invoice->fk_account)) {
954 if ($this->invoice->setBankAccount((int) $this->invoice->fk_account) == 0) {
955 throw new RestException(400, $this->invoice->errorsToString());
956 }
957 }
958
959 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
960 return $this->get($id);
961 } else {
962 throw new RestException(500, $this->invoice->errorsToString());
963 }
964 }
965
976 public function delete($id)
977 {
978 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
979 throw new RestException(403);
980 }
981 if ($id == 0) {
982 throw new RestException(400, 'No invoice with id=0 can exist');
983 }
984 $result = $this->invoice->fetch($id);
985 if (!$result) {
986 throw new RestException(404, 'Invoice not found');
987 }
988
989 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
990 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
991 }
992
993 $result = $this->invoice->delete(DolibarrApiAccess::$user);
994 if ($result < 0) {
995 throw new RestException(500, 'Error when deleting invoice');
996 } elseif ($result == 0) {
997 throw new RestException(403, 'Invoice not erasable');
998 }
999
1000 return array(
1001 'success' => array(
1002 'code' => 200,
1003 'message' => 'Invoice deleted'
1004 )
1005 );
1006 }
1007
1035 public function postLine($id, $request_data = null)
1036 {
1037 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1038 throw new RestException(403);
1039 }
1040
1041 $result = $this->invoice->fetch($id);
1042 if (!$result) {
1043 throw new RestException(404, 'Invoice not found');
1044 }
1045
1046 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1047 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1048 }
1049
1050 $request_data = (object) $request_data;
1051
1052 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
1053 $request_data->label = sanitizeVal($request_data->label);
1054
1055 // Reset fk_parent_line for no child products and special product
1056 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
1057 $request_data->fk_parent_line = 0;
1058 }
1059
1060 // calculate pa_ht
1061 $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);
1062 $pa_ht = $marginInfos[0];
1063
1064 $updateRes = $this->invoice->addline(
1065 $request_data->desc,
1066 $request_data->subprice,
1067 $request_data->qty,
1068 $request_data->tva_tx,
1069 $request_data->localtax1_tx,
1070 $request_data->localtax2_tx,
1071 $request_data->fk_product,
1072 $request_data->remise_percent,
1073 $request_data->date_start,
1074 $request_data->date_end,
1075 $request_data->fk_code_ventilation,
1076 $request_data->info_bits,
1077 $request_data->fk_remise_except,
1078 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
1079 $request_data->subprice,
1080 $request_data->product_type,
1081 $request_data->rang,
1082 $request_data->special_code,
1083 $request_data->origin,
1084 $request_data->origin_id,
1085 $request_data->fk_parent_line,
1086 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
1087 $pa_ht,
1088 $request_data->label,
1089 $request_data->array_options,
1090 $request_data->situation_percent,
1091 $request_data->fk_prev_id,
1092 $request_data->fk_unit,
1093 0,
1094 $request_data->ref_ext
1095 );
1096
1097 if ($updateRes < 0) {
1098 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->errorsToString());
1099 }
1100
1101 return $updateRes;
1102 }
1103
1124 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
1125 {
1126 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1127 throw new RestException(403);
1128 }
1129 $result = $this->invoice->fetch($id);
1130 if (!$result) {
1131 throw new RestException(404, 'Invoice not found');
1132 }
1133
1134 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1135 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1136 }
1137
1138 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
1139 if ($result < 0) {
1140 throw new RestException(500, 'Error : '.$this->invoice->errorsToString());
1141 }
1142
1143 $result = $this->invoice->fetch($id);
1144 if (!$result) {
1145 throw new RestException(404, 'Invoice not found');
1146 }
1147
1148 // test already done
1149 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1150 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1151 // }
1152
1153 return $this->_cleanObjectDatas($this->invoice);
1154 }
1155
1156
1157
1174 public function settodraft($id, $idwarehouse = -1)
1175 {
1176 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1177 throw new RestException(403);
1178 }
1179 $result = $this->invoice->fetch($id);
1180 if (!$result) {
1181 throw new RestException(404, 'Invoice not found');
1182 }
1183
1184 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1185 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1186 }
1187
1188 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
1189 if ($result == 0) {
1190 throw new RestException(304, 'Nothing done.');
1191 }
1192 if ($result < 0) {
1193 throw new RestException(500, 'Error : '.$this->invoice->errorsToString());
1194 }
1195
1196 $result = $this->invoice->fetch($id);
1197 if (!$result) {
1198 throw new RestException(404, 'Invoice not found');
1199 }
1200
1201 return $this->_cleanObjectDatas($this->invoice);
1202 }
1203
1204
1224 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1225 {
1226 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1227 throw new RestException(403);
1228 }
1229 $result = $this->invoice->fetch($id);
1230 if (!$result) {
1231 throw new RestException(404, 'Invoice not found');
1232 }
1233
1234 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1235 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1236 }
1237
1238 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
1239 if ($result == 0) {
1240 throw new RestException(304, 'Error nothing done. May be object is already validated');
1241 }
1242 if ($result < 0) {
1243 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->errorsToString());
1244 }
1245
1246 $result = $this->invoice->fetch($id);
1247 if (!$result) {
1248 throw new RestException(404, 'Invoice not found');
1249 }
1250
1251 // test already done
1252 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1253 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1254 // }
1255
1256 // copy from order
1257 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1258 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', (string) $this->invoice->ref);
1259
1260 return $this->_cleanObjectDatas($this->invoice);
1261 }
1262
1280 public function settopaid($id, $close_code = '', $close_note = '')
1281 {
1282 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1283 throw new RestException(403);
1284 }
1285 $result = $this->invoice->fetch($id);
1286 if (!$result) {
1287 throw new RestException(404, 'Invoice not found');
1288 }
1289
1290 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1291 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1292 }
1293
1294 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1295 if ($result == 0) {
1296 throw new RestException(304, 'Error nothing done. May be object is already validated');
1297 }
1298 if ($result < 0) {
1299 throw new RestException(500, 'Error : '.$this->invoice->errorsToString());
1300 }
1301
1302
1303 $result = $this->invoice->fetch($id);
1304 if (!$result) {
1305 throw new RestException(404, 'Invoice not found');
1306 }
1307
1308 // test already done
1309 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1310 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1311 // }
1312
1313 return $this->_cleanObjectDatas($this->invoice);
1314 }
1315
1316
1332 public function settounpaid($id)
1333 {
1334 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1335 throw new RestException(403);
1336 }
1337 $result = $this->invoice->fetch($id);
1338 if (!$result) {
1339 throw new RestException(404, 'Invoice not found');
1340 }
1341
1342 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1343 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1344 }
1345
1346 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1347 if ($result == 0) {
1348 throw new RestException(304, 'Nothing done');
1349 }
1350 if ($result < 0) {
1351 throw new RestException(500, 'Error : '.$this->invoice->errorsToString());
1352 }
1353
1354
1355 $result = $this->invoice->fetch($id);
1356 if (!$result) {
1357 throw new RestException(404, 'Invoice not found');
1358 }
1359
1360 // test already done
1361 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1362 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1363 // }
1364
1365 return $this->_cleanObjectDatas($this->invoice);
1366 }
1367
1378 public function getDiscount($id)
1379 {
1380 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1381
1382 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1383 throw new RestException(403);
1384 }
1385
1386 $result = $this->invoice->fetch($id);
1387 if (!$result) {
1388 throw new RestException(404, 'Invoice not found');
1389 }
1390
1391 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1392 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1393 }
1394
1395 $discountcheck = new DiscountAbsolute($this->db);
1396 $result = $discountcheck->fetch(0, $this->invoice->id);
1397
1398 if ($result == 0) {
1399 throw new RestException(404, 'Discount not found');
1400 }
1401 if ($result < 0) {
1402 throw new RestException(500, $discountcheck->errorsToString());
1403 }
1404
1405 return parent::_cleanObjectDatas($discountcheck);
1406 }
1407
1424 {
1425 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1426
1427 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1428 throw new RestException(403);
1429 }
1430
1431 $result = $this->invoice->fetch($id);
1432 if (!$result) {
1433 throw new RestException(404, 'Invoice not found');
1434 }
1435
1436 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1437 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1438 }
1439
1440 if ($this->invoice->paye) { // TODO Replace by a test on status
1441 throw new RestException(500, 'Alreay paid');
1442 }
1443
1444 $this->invoice->fetch($id);
1445 $this->invoice->fetch_thirdparty();
1446
1447 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1448 $discountcheck = new DiscountAbsolute($this->db);
1449 $result = $discountcheck->fetch(0, $this->invoice->id);
1450
1451 $canconvert = 0;
1452 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1453 $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)
1454 }
1455 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1456 $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)
1457 }
1458 if ($canconvert) {
1459 $this->db->begin();
1460
1461 $amount_ht = $amount_tva = $amount_ttc = array();
1462 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1463 '
1464 @phan-var-force array<string,float> $amount_ht
1465 @phan-var-force array<string,float> $amount_tva
1466 @phan-var-force array<string,float> $amount_ttc
1467 @phan-var-force array<string,float> $multicurrency_amount_ht
1468 @phan-var-force array<string,float> $multicurrency_amount_tva
1469 @phan-var-force array<string,float> $multicurrency_amount_ttc
1470 ';
1471
1472 // Loop on each vat rate
1473 $i = 0;
1474 foreach ($this->invoice->lines as $line) {
1475 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1476 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1477 $amount_ht[$line->tva_tx] = 0.0;
1478 $amount_tva[$line->tva_tx] = 0.0;
1479 $amount_ttc[$line->tva_tx] = 0.0;
1480 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1481 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1482 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1483 }
1484 // no need to create discount if amount is null
1485 $amount_ht[$line->tva_tx] += $line->total_ht;
1486 $amount_tva[$line->tva_tx] += $line->total_tva;
1487 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1488 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1489 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1490 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1491 $i++;
1492 }
1493 }
1494
1495 // Insert one discount by VAT rate category
1496 $discount = new DiscountAbsolute($this->db);
1497 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1498 $discount->description = '(CREDIT_NOTE)';
1499 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1500 $discount->description = '(DEPOSIT)';
1501 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1502 $discount->description = '(EXCESS RECEIVED)';
1503 } else {
1504 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1505 }
1506
1507 $discount->fk_soc = $this->invoice->socid;
1508 $discount->socid = $this->invoice->socid;
1509 $discount->fk_facture_source = $this->invoice->id;
1510
1511 $error = 0;
1512
1513 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1514 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1515
1516 // Total payments
1517 $sql = 'SELECT SUM(pf.amount) as total_payments';
1518 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1519 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1520 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1521 $sql .= ' AND pf.fk_paiement = p.rowid';
1522 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1523 $resql = $this->db->query($sql);
1524 if (!$resql) {
1525 dol_print_error($this->db);
1526 }
1527
1528 $res = $this->db->fetch_object($resql);
1529 $total_payments = $res->total_payments;
1530
1531 // Total credit note and deposit
1532 $total_creditnote_and_deposit = 0;
1533 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1534 $sql .= " re.description, re.fk_facture_source";
1535 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1536 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1537 $resql = $this->db->query($sql);
1538 if (!empty($resql)) {
1539 while ($obj = $this->db->fetch_object($resql)) {
1540 $total_creditnote_and_deposit += $obj->amount_ttc;
1541 }
1542 } else {
1543 dol_print_error($this->db);
1544 }
1545
1546 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1547 $discount->total_ht = $discount->total_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1548 $discount->amount_tva = 0;
1549 $discount->total_tva = 0;
1550 $discount->tva_tx = 0;
1551
1552 $result = $discount->create(DolibarrApiAccess::$user);
1553 if ($result < 0) {
1554 $error++;
1555 }
1556 }
1557 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1558 foreach ($amount_ht as $tva_tx => $xxx) {
1559 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1560 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1561 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1562 $discount->total_ht = abs($amount_ht[$tva_tx]);
1563 $discount->total_tva = abs($amount_tva[$tva_tx]);
1564 $discount->total_ttc = abs($amount_ttc[$tva_tx]);
1565 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1566 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1567 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1568 $discount->multicurrency_total_ht = abs($multicurrency_amount_ht[$tva_tx]);
1569 $discount->multicurrency_total_tva = abs($multicurrency_amount_tva[$tva_tx]);
1570 $discount->multicurrency_total_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1571 $discount->tva_tx = abs((float) $tva_tx);
1572
1573 $result = $discount->create(DolibarrApiAccess::$user);
1574 if ($result < 0) {
1575 $error++;
1576 break;
1577 }
1578 }
1579 }
1580
1581 if (empty($error)) {
1582 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1583 // Set the invoice as paid
1584 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1585 if ($result >= 0) {
1586 $this->db->commit();
1587 } else {
1588 $this->db->rollback();
1589 throw new RestException(500, 'Could not set paid');
1590 }
1591 } else {
1592 $this->db->commit();
1593 }
1594 } else {
1595 $this->db->rollback();
1596 throw new RestException(500, 'Discount creation error');
1597 }
1598 }
1599
1600 return $this->_cleanObjectDatas($this->invoice);
1601 }
1602
1620 {
1621 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1622
1623 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1624 throw new RestException(403);
1625 }
1626
1627
1628 $result = $this->invoice->fetch($id);
1629 if (!$result) {
1630 throw new RestException(404, 'Invoice not found');
1631 }
1632
1633 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1634 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1635 }
1636
1637
1638 $discountcheck = new DiscountAbsolute($this->db);
1639 $result = $discountcheck->fetch(0, $this->invoice->id);
1640
1641 if ($result == 0) {
1642 throw new RestException(404, 'Discount not found');
1643 }
1644 if ($result < 0) {
1645 throw new RestException(500, $discountcheck->errorsToString());
1646 }
1647
1648 if (!empty($discountcheck->fk_facture) || !empty($discountcheck->fk_facture_line)) {
1649 throw new RestException(409, 'Credit used');
1650 }
1651
1652 $this->db->begin();
1653
1654 $result = $discountcheck->delete(DolibarrApiAccess::$user);
1655 if ($result <= 0) {
1656 $this->db->rollback();
1657 throw new RestException(500, 'Discount deletion error');
1658 }
1659
1660 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1661 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1662 if ($result <= 0) {
1663 $this->db->rollback();
1664 throw new RestException(500, 'Could not set unpaid');
1665 }
1666 }
1667
1668 $this->db->commit();
1669
1670 return $this->_cleanObjectDatas($this->invoice);
1671 }
1672
1691 public function useDiscount($id, $discountid)
1692 {
1693 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1694 throw new RestException(403);
1695 }
1696 if (empty($id)) {
1697 throw new RestException(400, 'Invoice ID is mandatory');
1698 }
1699 if (empty($discountid)) {
1700 throw new RestException(400, 'Discount ID is mandatory');
1701 }
1702
1703 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1704 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1705 }
1706
1707 $result = $this->invoice->fetch($id);
1708 if (!$result) {
1709 throw new RestException(404, 'Invoice not found');
1710 }
1711
1712 $result = $this->invoice->insert_discount($discountid);
1713 if ($result < 0) {
1714 throw new RestException(405, $this->invoice->errorsToString());
1715 }
1716
1717 return $result;
1718 }
1719
1738 public function useCreditNote($id, $discountid)
1739 {
1740 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1741
1742 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1743 throw new RestException(403);
1744 }
1745 if (empty($id)) {
1746 throw new RestException(400, 'Invoice ID is mandatory');
1747 }
1748 if (empty($discountid)) {
1749 throw new RestException(400, 'Credit ID is mandatory');
1750 }
1751
1752 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1753 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1754 }
1755 $discount = new DiscountAbsolute($this->db);
1756 $result = $discount->fetch($discountid);
1757 if (!$result) {
1758 throw new RestException(404, 'Credit not found');
1759 }
1760
1761 $result = $discount->link_to_invoice(0, $id);
1762 if ($result < 0) {
1763 throw new RestException(405, $discount->errorsToString());
1764 }
1765
1766 return $result;
1767 }
1768
1786 public function getPayments($id)
1787 {
1788 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1789 throw new RestException(403);
1790 }
1791 if (empty($id)) {
1792 throw new RestException(400, 'Invoice ID is mandatory');
1793 }
1794
1795 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1796 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1797 }
1798
1799 $result = $this->invoice->fetch($id);
1800 if (!$result) {
1801 throw new RestException(404, 'Invoice not found');
1802 }
1803
1804 $result = $this->invoice->getListOfPayments();
1805 if ($this->invoice->errorsToString() !== '') {
1806 throw new RestException(405, $this->invoice->errorsToString());
1807 }
1808
1809 return $result;
1810 }
1811
1812
1836 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1837 {
1838 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1839
1840 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
1841 throw new RestException(403);
1842 }
1843 if (empty($id)) {
1844 throw new RestException(400, 'Invoice ID is mandatory');
1845 }
1846
1847 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1848 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1849 }
1850
1851 if (isModEnabled("bank")) {
1852 if (empty($accountid)) {
1853 throw new RestException(400, 'Account ID is mandatory');
1854 }
1855 }
1856
1857 if (empty($paymentid)) {
1858 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1859 }
1860
1861
1862 $result = $this->invoice->fetch($id);
1863 if (!$result) {
1864 throw new RestException(404, 'Invoice not found');
1865 }
1866
1867 // Calculate amount to pay
1868 $totalpaid = $this->invoice->getSommePaiement();
1869 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1870 $totaldeposits = $this->invoice->getSumDepositsUsed();
1871
1872 $this->db->begin();
1873
1874 $amounts = array();
1875 $multicurrency_amounts = array();
1876
1877 // Clean parameters amount if payment is for a credit note
1878 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1879 $resteapayer = price2num($this->invoice->total_ttc + $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1880 $amounts[$id] = (float) price2num(-1 * abs((float) $resteapayer), 'MT');
1881 // Multicurrency
1882 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1883 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1884 } else {
1885 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1886 $amounts[$id] = (float) $resteapayer;
1887 // Multicurrency
1888 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1889 $multicurrency_amounts[$id] = (float) $newvalue;
1890 }
1891
1892 // Creation of payment line
1893 $paymentobj = new Paiement($this->db);
1894 if (is_numeric($datepaye)) {
1895 $paymentobj->datepaye = $datepaye;
1896 } else {
1897 $paymentobj->datepaye = dol_stringtotime($datepaye);
1898 }
1899 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1900 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1901 $paymentobj->paiementid = $paymentid;
1902 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1903 $paymentobj->num_payment = $num_payment;
1904 $paymentobj->note_private = $comment;
1905
1906 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1907 if ($payment_id < 0) {
1908 $this->db->rollback();
1909 throw new RestException(400, 'Payment error : '.$paymentobj->errorsToString());
1910 }
1911
1912 if (isModEnabled("bank")) {
1913 $label = '(CustomerInvoicePayment)';
1914
1915 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1916 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1917 }
1918 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1919 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1920 }
1921 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1922 if ($result < 0) {
1923 $this->db->rollback();
1924 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->errorsToString());
1925 }
1926 }
1927
1928 $this->db->commit();
1929
1930 return $payment_id;
1931 }
1932
1963 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1964 {
1965 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1966
1967 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
1968 throw new RestException(403);
1969 }
1970 foreach ($arrayofamounts as $id => $amount) {
1971 if (empty($id)) {
1972 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1973 }
1974 if (!DolibarrApi::_checkAccessToResource('facture', (int) $id)) {
1975 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1976 }
1977 }
1978
1979 if (isModEnabled("bank")) {
1980 if (empty($accountid)) {
1981 throw new RestException(400, 'Account ID is mandatory');
1982 }
1983 }
1984 if (empty($paymentid)) {
1985 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1986 }
1987
1988 $this->db->begin();
1989
1990 $amounts = array();
1991 $multicurrency_amounts = array();
1992
1993 // Loop on each invoice to pay
1994 foreach ($arrayofamounts as $id => $amountarray) {
1995 $id = (int) $id; // Ensure $id is seen as int, required by function calls and array indexes.
1996 $result = $this->invoice->fetch($id);
1997 if (!$result) {
1998 $this->db->rollback();
1999 throw new RestException(404, 'Invoice ID '.$id.' not found');
2000 }
2001
2002 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
2003 $this->db->rollback();
2004 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
2005 }
2006
2007 $is_multicurrency = 0;
2008 $total_ttc = $this->invoice->total_ttc;
2009
2010 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
2011 $is_multicurrency = 1;
2012 $total_ttc = $this->invoice->multicurrency_total_ttc;
2013 }
2014
2015 // Calculate amount to pay
2016 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
2017 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
2018 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
2019 $remainstopay = $amount = (float) price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
2020
2021 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
2022 $amount = (float) price2num($amountarray["amount"], 'MT');
2023 }
2024
2025 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
2026 $amount = (float) price2num($amountarray["multicurrency_amount"], 'MT');
2027 }
2028
2029 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
2030 $this->db->rollback();
2031 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
2032 }
2033
2034 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
2035 $amount = (float) price2num(-1 * abs((float) $amount), 'MT');
2036 }
2037
2038 if ($is_multicurrency) {
2039 $amounts[$id] = null;
2040 // Multicurrency
2041 $multicurrency_amounts[$id] = (float) $amount;
2042 } else {
2043 $amounts[$id] = (float) $amount;
2044 // Multicurrency
2045 $multicurrency_amounts[$id] = null;
2046 }
2047 }
2048
2049 // Creation of payment line
2050 $paymentobj = new Paiement($this->db);
2051 if (is_numeric($datepaye)) {
2052 $paymentobj->datepaye = $datepaye;
2053 } else {
2054 $paymentobj->datepaye = dol_stringtotime($datepaye);
2055 }
2056 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
2057 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
2058 $paymentobj->paiementid = $paymentid;
2059 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
2060 $paymentobj->num_payment = $num_payment;
2061 $paymentobj->note_private = $comment;
2062 $paymentobj->ref_ext = $ref_ext;
2063 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
2064 if ($payment_id < 0) {
2065 $this->db->rollback();
2066 throw new RestException(400, 'Payment error : '.$paymentobj->errorsToString());
2067 }
2068 if (isModEnabled("bank")) {
2069 $label = '(CustomerInvoicePayment)';
2070 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
2071 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
2072 }
2073 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
2074 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
2075 }
2076 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
2077 if ($result < 0) {
2078 $this->db->rollback();
2079 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->errorsToString());
2080 }
2081 }
2082
2083 $this->db->commit();
2084
2085 return $payment_id;
2086 }
2087
2106 public function putPayment($id, $num_payment = '')
2107 {
2108 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2109
2110 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
2111 throw new RestException(403);
2112 }
2113 if (empty($id)) {
2114 throw new RestException(400, 'Payment ID is mandatory');
2115 }
2116
2117 $paymentobj = new Paiement($this->db);
2118 $result = $paymentobj->fetch($id);
2119
2120 if (!$result) {
2121 throw new RestException(404, 'Payment not found');
2122 }
2123
2124 // Check all invoices of the payment to see if the user has permission on them for the object level permission test
2125 $tmparray = $paymentobj->getBillsArray();
2126 foreach ($tmparray as $tmpinvoiceid) {
2127 if (!DolibarrApi::_checkAccessToResource('facture', $tmpinvoiceid)) {
2128 throw new RestException(403, 'Payment is on invoices that are not all allowed for login '.DolibarrApiAccess::$user->login);
2129 }
2130 }
2131
2132 if (!empty($num_payment)) {
2133 $result = $paymentobj->update_num($num_payment);
2134 if ($result < 0) {
2135 throw new RestException(500, 'Error when updating the payment num');
2136 }
2137 }
2138
2139 return [
2140 'success' => [
2141 'code' => 200,
2142 'message' => 'Payment updated'
2143 ]
2144 ];
2145 }
2146
2147 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2157 protected function _cleanObjectDatas($object)
2158 {
2159 // phpcs:enable
2160 $object = parent::_cleanObjectDatas($object);
2161
2162 unset($object->note);
2163 unset($object->address);
2164 unset($object->barcode_type);
2165 unset($object->barcode_type_code);
2166 unset($object->barcode_type_label);
2167 unset($object->barcode_type_coder);
2168 unset($object->canvas);
2169
2170 return $object;
2171 }
2172
2181 private function _validate($data)
2182 {
2183 if ($data === null) {
2184 $data = array();
2185 }
2186 $invoice = array();
2187 foreach (Invoices::$FIELDS as $field) {
2188 if (!isset($data[$field])) {
2189 throw new RestException(400, "$field field missing");
2190 }
2191 $invoice[$field] = $data[$field];
2192 }
2193 return $invoice;
2194 }
2195
2196
2212 public function getTemplateInvoice($id, $contact_list = 1)
2213 {
2214 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
2215 }
2216
2217
2245 public function indexTemplateInvoices($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
2246 {
2247 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2248 throw new RestException(403);
2249 }
2250
2251 $obj_ret = array();
2252
2253 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
2254 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
2255
2256
2257 // If the internal user must only see his customers, force searching by him
2258 $search_sale = 0;
2259 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
2260 $search_sale = DolibarrApiAccess::$user->id;
2261 }
2262
2263 $sql = "SELECT t.rowid";
2264 $sql .= " FROM ".MAIN_DB_PREFIX."facture_rec AS t";
2265 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
2266 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_rec_extrafields AS ef ON (ef.fk_object = t.rowid)";
2267 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
2268 if ($socids) {
2269 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
2270 }
2271
2272 // Search on sale representative
2273 if ($search_sale && $search_sale != '-1') {
2274 if ($search_sale == -2) {
2275 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux AS sc WHERE sc.fk_soc = t.fk_soc)";
2276 } elseif ($search_sale > 0) {
2277 $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).")";
2278 }
2279 }
2280
2281 // An unknown value used to be ignored, so the whole list came back as if it were the filtered one
2282 if ((string) $status !== '' && !in_array($status, array('draft', 'active', 'suspended'), true)) {
2283 throw new RestException(400, "Bad value for parameter status. Expected one of: draft, active, suspended");
2284 }
2285 // Filter by status
2286 if ($status == 'active') {
2287 $sql .= " AND t.suspended = 0 AND t.frequency IS NOT NULL";
2288 }
2289 if ($status == 'suspended') {
2290 $sql .= " AND t.suspended = 1 AND t.frequency IS NOT NULL";
2291 }
2292 if ($status == 'draft') {
2293 $sql .= " AND t.frequency IS NULL";
2294 }
2295 // add sql filters
2296 if ($sqlfilters) {
2297 $errormessage = '';
2298 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
2299 if ($errormessage) {
2300 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
2301 }
2302 }
2303
2304 //this query will return total template invoices with the filters given
2305 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
2306
2307 $sql .= $this->db->order($sortfield, $sortorder);
2308 if ($limit) {
2309 if ($page < 0) {
2310 $page = 0;
2311 }
2312 $offset = $limit * $page;
2313
2314 $sql .= $this->db->plimit($limit + 1, $offset);
2315 }
2316
2317 $result = $this->db->query($sql);
2318 if ($result) {
2319 $i = 0;
2320 $num = $this->db->num_rows($result);
2321 $min = min($num, ($limit <= 0 ? $num : $limit));
2322 while ($i < $min) {
2323 $obj = $this->db->fetch_object($result);
2324 $factureRec = new FactureRec($this->db);
2325 if ($factureRec->fetch($obj->rowid) > 0) {
2326 if ($loadlinkedobjects) {
2327 // retrieve linked objects
2328 $factureRec->fetchObjectLinked();
2329 }
2330
2331 if (!$withLines) {
2332 unset($factureRec->lines);
2333 }
2334
2335 $obj_ret[] = $this->_filterObjectProperties($this->_cleanTemplateObjectDatas($factureRec), $properties);
2336 }
2337 $i++;
2338 }
2339 } else {
2340 throw new RestException(503, 'Error when retrieving recurring invoice templates: '.$this->db->lasterror());
2341 }
2342
2343 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
2344 if ($pagination_data) {
2345 $totalsResult = $this->db->query($sqlTotals);
2346 $total = $this->db->fetch_object($totalsResult)->total;
2347
2348 $tmp = $obj_ret;
2349 $obj_ret = array();
2350
2351 $obj_ret['data'] = $tmp;
2352 $obj_ret['pagination'] = array(
2353 'total' => (int) $total,
2354 'page' => $page,
2355 'page_count' => ceil((int) $total / $limit),
2356 'limit' => $limit
2357 );
2358 }
2359
2360 return $obj_ret;
2361 }
2362
2376 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
2377 {
2378 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2379 throw new RestException(403);
2380 }
2381
2382 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
2383 if (!$result) {
2384 throw new RestException(404, 'Template invoice not found');
2385 }
2386
2387 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
2388 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2389 }
2390
2391 // Add external contacts ids
2392 if ($contact_list > -1) {
2393 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
2394 if (is_array($tmparray)) {
2395 $this->template_invoice->contacts_ids = $tmparray;
2396 }
2397 }
2398
2399 $this->template_invoice->fetchObjectLinked();
2400 return $this->_cleanTemplateObjectDatas($this->template_invoice);
2401 }
2402
2403
2404 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2412 {
2413 // phpcs:enable
2414 $object = parent::_cleanObjectDatas($object);
2415
2416 unset($object->note);
2417 unset($object->address);
2418 unset($object->barcode_type);
2419 unset($object->barcode_type_code);
2420 unset($object->barcode_type_label);
2421 unset($object->barcode_type_coder);
2422 unset($object->canvas);
2423
2424 return $object;
2425 }
2426}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
unmarkAsCreditAvailable($id)
Remove a discount (credit available) for a credit note or a deposit.
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, $processnotimeasnoon=0)
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:452
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, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.