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