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->error);
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
508 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
509 if ($result < 0) {
510 throw new RestException(405, $this->invoice->error);
511 }
512 $this->invoice->fetchObjectLinked();
513 return $this->_cleanObjectDatas($this->invoice);
514 }
515
528 public function getLines($id)
529 {
530 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
531 throw new RestException(403);
532 }
533
534 $result = $this->invoice->fetch($id);
535 if (!$result) {
536 throw new RestException(404, 'Invoice not found');
537 }
538
539 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
540 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
541 }
542 $this->invoice->getLinesArray();
543 $result = array();
544 foreach ($this->invoice->lines as $line) {
545 array_push($result, $this->_cleanObjectDatas($line));
546 }
547 return $result;
548 }
549
568 public function putLine($id, $lineid, $request_data = null)
569 {
570 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
571 throw new RestException(403);
572 }
573
574 $result = $this->invoice->fetch($id);
575 if (!$result) {
576 throw new RestException(404, 'Invoice not found');
577 }
578
579 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
580 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
581 }
582
583 $request_data = (object) $request_data;
584
585 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
586 $request_data->label = sanitizeVal($request_data->label);
587
588 $updateRes = $this->invoice->updateline(
589 $lineid,
590 $request_data->desc,
591 $request_data->subprice,
592 $request_data->qty,
593 $request_data->remise_percent,
594 $request_data->date_start,
595 $request_data->date_end,
596 $request_data->tva_tx,
597 $request_data->localtax1_tx,
598 $request_data->localtax2_tx,
599 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
600 $request_data->info_bits,
601 $request_data->product_type,
602 $request_data->fk_parent_line,
603 0,
604 $request_data->fk_fournprice,
605 $request_data->pa_ht,
606 $request_data->label,
607 $request_data->special_code,
608 $request_data->array_options,
609 $request_data->situation_percent,
610 $request_data->fk_unit,
611 $request_data->multicurrency_subprice,
612 0,
613 $request_data->ref_ext,
614 $request_data->rang
615 );
616
617 if ($updateRes > 0) {
618 $result = $this->get($id);
619 unset($result->line);
620 return $this->_cleanObjectDatas($result);
621 } else {
622 throw new RestException(304, $this->invoice->error);
623 }
624 }
625
645 public function postContact($id, $contactid, $type, $source = 'external', $notrigger = 0)
646 {
647 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
648 throw new RestException(403);
649 }
650
651 // test source
652 if (empty($source)) {
653 throw new RestException(400, 'Source can not be empty');
654 }
655 $sql_distinct_source = "SELECT DISTINCT source";
656 $sql_distinct_source .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
657 $sql_distinct_source .= " WHERE element LIKE 'facture'";
658 $sql_distinct_source .= " AND source is NOT NULL";
659 $sql_distinct_source .= " AND active != 0";
660 $source_result = $this->db->query($sql_distinct_source);
661 $source_array = array();
662
663 if ($source_result) {
664 $num = $this->db->num_rows($source_result);
665 $i = 0;
666 while ($i < $num) {
667 $obj = $this->db->fetch_object($source_result);
668 $source_kind = (string) $obj->source;
669 array_push($source_array, $source_kind);
670 dol_syslog("source_kind=".$source_kind);
671 $i++;
672 }
673 } else {
674 throw new RestException(503, 'Error when retrieving a list of invoice contact sources: '.$this->db->lasterror());
675 }
676 if (!in_array($source, (array) $source_array, true)) {
677 throw new RestException(400, 'Combo of Source='.$source.' and Type='.$type.' not found in dictionary with active invoice contact types');
678 }
679
680 // test type
681 if (empty($type)) {
682 throw new RestException(400, 'type can not be empty');
683 }
684 // variable called type here, but code in dictionary and database
685 $sql_distinct_type = "SELECT DISTINCT code";
686 $sql_distinct_type .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
687 $sql_distinct_type .= " WHERE element LIKE 'facture'";
688 $sql_distinct_type .= " AND source='".$this->db->escape($source)."'";
689 $sql_distinct_type .= " AND code is NOT NULL";
690 $sql_distinct_type .= " AND active != 0";
691 $type_result = $this->db->query($sql_distinct_type);
692 $type_array = array();
693
694 if ($type_result) {
695 $num = $this->db->num_rows($type_result);
696 $i = 0;
697 while ($i < $num) {
698 $obj = $this->db->fetch_object($type_result);
699 // variable called type here, but code in dictionary and database
700 $type_kind = (string) $obj->code;
701 array_push($type_array, $type_kind);
702 dol_syslog("type_kind=".$type_kind);
703 $i++;
704 }
705 } else {
706 throw new RestException(503, 'Error when retrieving a list of invoice contact types: '.$this->db->lasterror());
707 }
708 if (!in_array($type, (array) $type_array, true)) {
709 throw new RestException(400, 'Combo of Type='.$type.' and Source='.$source.' not found in dictionary with active invoice contact types');
710 }
711
712 // tests done, let's get it
713 $result = $this->invoice->fetch($id);
714 if (!$result) {
715 throw new RestException(404, 'Invoice not found');
716 }
717 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
718 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
719 }
720
721 $result = $this->invoice->add_contact($contactid, $type, $source, $notrigger);
722
723 if ($result == 0) {
724 throw new RestException(400, 'Already exists: Contact='.$contactid.' is already linked to the invoice='.$id.' as source='.$source.' and type='.$type);
725 } elseif ($result == -1) {
726 throw new RestException(400, 'Wrong contact='.$contactid);
727 } elseif ($result == -2) {
728 throw new RestException(400, 'Wrong type='.$type);
729 } elseif ($result == -3) {
730 throw new RestException(400, 'Not allowed contacts');
731 } elseif ($result == -4) {
732 throw new RestException(400, 'ErrorCommercialNotAllowedForThirdparty');
733 } elseif ($result == -5) {
734 throw new RestException(400, 'Trigger failed');
735 } elseif ($result == -6) {
736 throw new RestException(400, 'DB_ERROR_RECORD_ALREADY_EXISTS');
737 } elseif ($result == -7) {
738 throw new RestException(400, 'Some other error');
739 }
740
741 if (!$result) {
742 throw new RestException(500, 'Error when added the contact');
743 }
744
745 return array(
746 'success' => array(
747 'code' => 200,
748 'message' => 'Contact='.$contactid.' linked to the invoice='.$id.' as '.$source.' '.$type
749 )
750 );
751 }
752
768 public function getContacts($id, $type = '')
769 {
770 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
771 throw new RestException(403);
772 }
773
774 $result = $this->invoice->fetch($id);
775 if (!$result) {
776 throw new RestException(404, 'Invoice not found');
777 }
778
779 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
780 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
781 }
782
783 $contacts = $this->invoice->liste_contact(-1, 'external', 0, $type);
784 $socpeoples = $this->invoice->liste_contact(-1, 'internal', 0, $type);
785
786 $contacts = array_merge($contacts, $socpeoples);
787
788 return $contacts;
789 }
790
807 public function deleteContact($id, $contactid, $type)
808 {
809 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
810 throw new RestException(403);
811 }
812
813 $result = $this->invoice->fetch($id);
814
815 if (!$result) {
816 throw new RestException(404, 'Invoice not found');
817 }
818
819 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
820 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
821 }
822
823 $contacts = $this->invoice->liste_contact();
824
825 foreach ($contacts as $contact) {
826 if ($contact['id'] == $contactid && $contact['code'] == $type) {
827 $result = $this->invoice->delete_contact($contact['rowid']);
828
829 if (!$result) {
830 throw new RestException(500, 'Error when deleted the contact');
831 }
832 }
833 }
834
835 return $this->_cleanObjectDatas($this->invoice);
836 }
837
854 public function deleteLine($id, $lineid)
855 {
856 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
857 throw new RestException(403);
858 }
859 if (empty($lineid)) {
860 throw new RestException(400, 'Line ID is mandatory');
861 }
862
863 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
864 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
865 }
866
867 $result = $this->invoice->fetch($id);
868 if (!$result) {
869 throw new RestException(404, 'Invoice not found');
870 }
871 if ($this->invoice->status != 0) {
872 throw new RestException(403, 'Invoice not in Draft Status : '.$this->invoice->getLibStatut(1));
873 }
874
875 $updateRes = $this->invoice->deleteLine($lineid, $id);
876 if ($updateRes > 0) {
877 return $this->get($id);
878 } else {
879 throw new RestException(405, $this->invoice->error);
880 }
881 }
882
894 public function put($id, $request_data = null)
895 {
896 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
897 throw new RestException(403);
898 }
899 if ($id == 0) {
900 throw new RestException(400, 'No invoice with id=0 can exist');
901 }
902 $result = $this->invoice->fetch($id);
903 if (!$result) {
904 throw new RestException(404, 'Invoice not found');
905 }
906
907 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
908 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
909 }
910
911 foreach ($request_data as $field => $value) {
912 if ($field == 'id') {
913 continue;
914 }
915 if ($field === 'caller') {
916 // 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
917 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
918 continue;
919 }
920 if ($field == 'array_options' && is_array($value)) {
921 foreach ($value as $index => $val) {
922 $this->invoice->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->invoice);
923 }
924 continue;
925 }
926
927 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
928
929 // If cond reglement => update date lim reglement
930 if ($field == 'cond_reglement_id') {
931 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
932 }
933 }
934
935 // update bank account
936 if (!empty($this->invoice->fk_account)) {
937 if ($this->invoice->setBankAccount((int) $this->invoice->fk_account) == 0) {
938 throw new RestException(400, $this->invoice->error);
939 }
940 }
941
942 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
943 return $this->get($id);
944 } else {
945 throw new RestException(500, $this->invoice->error);
946 }
947 }
948
959 public function delete($id)
960 {
961 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
962 throw new RestException(403);
963 }
964 if ($id == 0) {
965 throw new RestException(400, 'No invoice with id=0 can exist');
966 }
967 $result = $this->invoice->fetch($id);
968 if (!$result) {
969 throw new RestException(404, 'Invoice not found');
970 }
971
972 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
973 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
974 }
975
976 $result = $this->invoice->delete(DolibarrApiAccess::$user);
977 if ($result < 0) {
978 throw new RestException(500, 'Error when deleting invoice');
979 } elseif ($result == 0) {
980 throw new RestException(403, 'Invoice not erasable');
981 }
982
983 return array(
984 'success' => array(
985 'code' => 200,
986 'message' => 'Invoice deleted'
987 )
988 );
989 }
990
1018 public function postLine($id, $request_data = null)
1019 {
1020 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1021 throw new RestException(403);
1022 }
1023
1024 $result = $this->invoice->fetch($id);
1025 if (!$result) {
1026 throw new RestException(404, 'Invoice not found');
1027 }
1028
1029 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1030 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1031 }
1032
1033 $request_data = (object) $request_data;
1034
1035 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
1036 $request_data->label = sanitizeVal($request_data->label);
1037
1038 // Reset fk_parent_line for no child products and special product
1039 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
1040 $request_data->fk_parent_line = 0;
1041 }
1042
1043 // calculate pa_ht
1044 $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);
1045 $pa_ht = $marginInfos[0];
1046
1047 $updateRes = $this->invoice->addline(
1048 $request_data->desc,
1049 $request_data->subprice,
1050 $request_data->qty,
1051 $request_data->tva_tx,
1052 $request_data->localtax1_tx,
1053 $request_data->localtax2_tx,
1054 $request_data->fk_product,
1055 $request_data->remise_percent,
1056 $request_data->date_start,
1057 $request_data->date_end,
1058 $request_data->fk_code_ventilation,
1059 $request_data->info_bits,
1060 $request_data->fk_remise_except,
1061 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
1062 $request_data->subprice,
1063 $request_data->product_type,
1064 $request_data->rang,
1065 $request_data->special_code,
1066 $request_data->origin,
1067 $request_data->origin_id,
1068 $request_data->fk_parent_line,
1069 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
1070 $pa_ht,
1071 $request_data->label,
1072 $request_data->array_options,
1073 $request_data->situation_percent,
1074 $request_data->fk_prev_id,
1075 $request_data->fk_unit,
1076 0,
1077 $request_data->ref_ext
1078 );
1079
1080 if ($updateRes < 0) {
1081 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
1082 }
1083
1084 return $updateRes;
1085 }
1086
1107 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
1108 {
1109 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1110 throw new RestException(403);
1111 }
1112 $result = $this->invoice->fetch($id);
1113 if (!$result) {
1114 throw new RestException(404, 'Invoice not found');
1115 }
1116
1117 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1118 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1119 }
1120
1121 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
1122 if ($result < 0) {
1123 throw new RestException(500, 'Error : '.$this->invoice->error);
1124 }
1125
1126 $result = $this->invoice->fetch($id);
1127 if (!$result) {
1128 throw new RestException(404, 'Invoice not found');
1129 }
1130
1131 // test already done
1132 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1133 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1134 // }
1135
1136 return $this->_cleanObjectDatas($this->invoice);
1137 }
1138
1139
1140
1157 public function settodraft($id, $idwarehouse = -1)
1158 {
1159 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1160 throw new RestException(403);
1161 }
1162 $result = $this->invoice->fetch($id);
1163 if (!$result) {
1164 throw new RestException(404, 'Invoice not found');
1165 }
1166
1167 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1168 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1169 }
1170
1171 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
1172 if ($result == 0) {
1173 throw new RestException(304, 'Nothing done.');
1174 }
1175 if ($result < 0) {
1176 throw new RestException(500, 'Error : '.$this->invoice->error);
1177 }
1178
1179 $result = $this->invoice->fetch($id);
1180 if (!$result) {
1181 throw new RestException(404, 'Invoice not found');
1182 }
1183
1184 return $this->_cleanObjectDatas($this->invoice);
1185 }
1186
1187
1207 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1208 {
1209 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1210 throw new RestException(403);
1211 }
1212 $result = $this->invoice->fetch($id);
1213 if (!$result) {
1214 throw new RestException(404, 'Invoice not found');
1215 }
1216
1217 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1218 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1219 }
1220
1221 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
1222 if ($result == 0) {
1223 throw new RestException(304, 'Error nothing done. May be object is already validated');
1224 }
1225 if ($result < 0) {
1226 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
1227 }
1228
1229 $result = $this->invoice->fetch($id);
1230 if (!$result) {
1231 throw new RestException(404, 'Invoice not found');
1232 }
1233
1234 // test already done
1235 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1236 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1237 // }
1238
1239 // copy from order
1240 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1241 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', (string) $this->invoice->ref);
1242
1243 return $this->_cleanObjectDatas($this->invoice);
1244 }
1245
1263 public function settopaid($id, $close_code = '', $close_note = '')
1264 {
1265 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1266 throw new RestException(403);
1267 }
1268 $result = $this->invoice->fetch($id);
1269 if (!$result) {
1270 throw new RestException(404, 'Invoice not found');
1271 }
1272
1273 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1274 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1275 }
1276
1277 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1278 if ($result == 0) {
1279 throw new RestException(304, 'Error nothing done. May be object is already validated');
1280 }
1281 if ($result < 0) {
1282 throw new RestException(500, 'Error : '.$this->invoice->error);
1283 }
1284
1285
1286 $result = $this->invoice->fetch($id);
1287 if (!$result) {
1288 throw new RestException(404, 'Invoice not found');
1289 }
1290
1291 // test already done
1292 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1293 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1294 // }
1295
1296 return $this->_cleanObjectDatas($this->invoice);
1297 }
1298
1299
1315 public function settounpaid($id)
1316 {
1317 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1318 throw new RestException(403);
1319 }
1320 $result = $this->invoice->fetch($id);
1321 if (!$result) {
1322 throw new RestException(404, 'Invoice not found');
1323 }
1324
1325 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1326 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1327 }
1328
1329 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1330 if ($result == 0) {
1331 throw new RestException(304, 'Nothing done');
1332 }
1333 if ($result < 0) {
1334 throw new RestException(500, 'Error : '.$this->invoice->error);
1335 }
1336
1337
1338 $result = $this->invoice->fetch($id);
1339 if (!$result) {
1340 throw new RestException(404, 'Invoice not found');
1341 }
1342
1343 // test already done
1344 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1345 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1346 // }
1347
1348 return $this->_cleanObjectDatas($this->invoice);
1349 }
1350
1361 public function getDiscount($id)
1362 {
1363 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1364
1365 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1366 throw new RestException(403);
1367 }
1368
1369 $result = $this->invoice->fetch($id);
1370 if (!$result) {
1371 throw new RestException(404, 'Invoice not found');
1372 }
1373
1374 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1375 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1376 }
1377
1378 $discountcheck = new DiscountAbsolute($this->db);
1379 $result = $discountcheck->fetch(0, $this->invoice->id);
1380
1381 if ($result == 0) {
1382 throw new RestException(404, 'Discount not found');
1383 }
1384 if ($result < 0) {
1385 throw new RestException(500, $discountcheck->error);
1386 }
1387
1388 return parent::_cleanObjectDatas($discountcheck);
1389 }
1390
1407 {
1408 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1409
1410 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1411 throw new RestException(403);
1412 }
1413
1414 $result = $this->invoice->fetch($id);
1415 if (!$result) {
1416 throw new RestException(404, 'Invoice not found');
1417 }
1418
1419 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1420 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1421 }
1422
1423 if ($this->invoice->paye) { // TODO Replace by a test on status
1424 throw new RestException(500, 'Alreay paid');
1425 }
1426
1427 $this->invoice->fetch($id);
1428 $this->invoice->fetch_thirdparty();
1429
1430 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1431 $discountcheck = new DiscountAbsolute($this->db);
1432 $result = $discountcheck->fetch(0, $this->invoice->id);
1433
1434 $canconvert = 0;
1435 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1436 $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)
1437 }
1438 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1439 $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)
1440 }
1441 if ($canconvert) {
1442 $this->db->begin();
1443
1444 $amount_ht = $amount_tva = $amount_ttc = array();
1445 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1446 '
1447 @phan-var-force array<string,float> $amount_ht
1448 @phan-var-force array<string,float> $amount_tva
1449 @phan-var-force array<string,float> $amount_ttc
1450 @phan-var-force array<string,float> $multicurrency_amount_ht
1451 @phan-var-force array<string,float> $multicurrency_amount_tva
1452 @phan-var-force array<string,float> $multicurrency_amount_ttc
1453 ';
1454
1455 // Loop on each vat rate
1456 $i = 0;
1457 foreach ($this->invoice->lines as $line) {
1458 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1459 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1460 $amount_ht[$line->tva_tx] = 0.0;
1461 $amount_tva[$line->tva_tx] = 0.0;
1462 $amount_ttc[$line->tva_tx] = 0.0;
1463 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1464 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1465 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1466 }
1467 // no need to create discount if amount is null
1468 $amount_ht[$line->tva_tx] += $line->total_ht;
1469 $amount_tva[$line->tva_tx] += $line->total_tva;
1470 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1471 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1472 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1473 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1474 $i++;
1475 }
1476 }
1477
1478 // Insert one discount by VAT rate category
1479 $discount = new DiscountAbsolute($this->db);
1480 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1481 $discount->description = '(CREDIT_NOTE)';
1482 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1483 $discount->description = '(DEPOSIT)';
1484 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1485 $discount->description = '(EXCESS RECEIVED)';
1486 } else {
1487 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1488 }
1489
1490 $discount->fk_soc = $this->invoice->socid;
1491 $discount->socid = $this->invoice->socid;
1492 $discount->fk_facture_source = $this->invoice->id;
1493
1494 $error = 0;
1495
1496 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1497 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1498
1499 // Total payments
1500 $sql = 'SELECT SUM(pf.amount) as total_payments';
1501 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1502 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1503 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1504 $sql .= ' AND pf.fk_paiement = p.rowid';
1505 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1506 $resql = $this->db->query($sql);
1507 if (!$resql) {
1508 dol_print_error($this->db);
1509 }
1510
1511 $res = $this->db->fetch_object($resql);
1512 $total_payments = $res->total_payments;
1513
1514 // Total credit note and deposit
1515 $total_creditnote_and_deposit = 0;
1516 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1517 $sql .= " re.description, re.fk_facture_source";
1518 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1519 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1520 $resql = $this->db->query($sql);
1521 if (!empty($resql)) {
1522 while ($obj = $this->db->fetch_object($resql)) {
1523 $total_creditnote_and_deposit += $obj->amount_ttc;
1524 }
1525 } else {
1526 dol_print_error($this->db);
1527 }
1528
1529 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1530 $discount->total_ht = $discount->total_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1531 $discount->amount_tva = 0;
1532 $discount->total_tva = 0;
1533 $discount->tva_tx = 0;
1534
1535 $result = $discount->create(DolibarrApiAccess::$user);
1536 if ($result < 0) {
1537 $error++;
1538 }
1539 }
1540 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1541 foreach ($amount_ht as $tva_tx => $xxx) {
1542 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1543 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1544 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1545 $discount->total_ht = abs($amount_ht[$tva_tx]);
1546 $discount->total_tva = abs($amount_tva[$tva_tx]);
1547 $discount->total_ttc = abs($amount_ttc[$tva_tx]);
1548 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1549 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1550 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1551 $discount->multicurrency_total_ht = abs($multicurrency_amount_ht[$tva_tx]);
1552 $discount->multicurrency_total_tva = abs($multicurrency_amount_tva[$tva_tx]);
1553 $discount->multicurrency_total_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1554 $discount->tva_tx = abs((float) $tva_tx);
1555
1556 $result = $discount->create(DolibarrApiAccess::$user);
1557 if ($result < 0) {
1558 $error++;
1559 break;
1560 }
1561 }
1562 }
1563
1564 if (empty($error)) {
1565 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1566 // Set the invoice as paid
1567 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1568 if ($result >= 0) {
1569 $this->db->commit();
1570 } else {
1571 $this->db->rollback();
1572 throw new RestException(500, 'Could not set paid');
1573 }
1574 } else {
1575 $this->db->commit();
1576 }
1577 } else {
1578 $this->db->rollback();
1579 throw new RestException(500, 'Discount creation error');
1580 }
1581 }
1582
1583 return $this->_cleanObjectDatas($this->invoice);
1584 }
1585
1604 public function useDiscount($id, $discountid)
1605 {
1606 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1607 throw new RestException(403);
1608 }
1609 if (empty($id)) {
1610 throw new RestException(400, 'Invoice ID is mandatory');
1611 }
1612 if (empty($discountid)) {
1613 throw new RestException(400, 'Discount ID is mandatory');
1614 }
1615
1616 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1617 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1618 }
1619
1620 $result = $this->invoice->fetch($id);
1621 if (!$result) {
1622 throw new RestException(404, 'Invoice not found');
1623 }
1624
1625 $result = $this->invoice->insert_discount($discountid);
1626 if ($result < 0) {
1627 throw new RestException(405, $this->invoice->error);
1628 }
1629
1630 return $result;
1631 }
1632
1651 public function useCreditNote($id, $discountid)
1652 {
1653 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1654
1655 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1656 throw new RestException(403);
1657 }
1658 if (empty($id)) {
1659 throw new RestException(400, 'Invoice ID is mandatory');
1660 }
1661 if (empty($discountid)) {
1662 throw new RestException(400, 'Credit ID is mandatory');
1663 }
1664
1665 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1666 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1667 }
1668 $discount = new DiscountAbsolute($this->db);
1669 $result = $discount->fetch($discountid);
1670 if (!$result) {
1671 throw new RestException(404, 'Credit not found');
1672 }
1673
1674 $result = $discount->link_to_invoice(0, $id);
1675 if ($result < 0) {
1676 throw new RestException(405, $discount->error);
1677 }
1678
1679 return $result;
1680 }
1681
1699 public function getPayments($id)
1700 {
1701 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1702 throw new RestException(403);
1703 }
1704 if (empty($id)) {
1705 throw new RestException(400, 'Invoice ID is mandatory');
1706 }
1707
1708 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1709 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1710 }
1711
1712 $result = $this->invoice->fetch($id);
1713 if (!$result) {
1714 throw new RestException(404, 'Invoice not found');
1715 }
1716
1717 $result = $this->invoice->getListOfPayments();
1718 if (!is_array($result) && $result < 0) {
1719 throw new RestException(405, $this->invoice->error);
1720 }
1721
1722 return $result;
1723 }
1724
1725
1749 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1750 {
1751 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1752
1753 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
1754 throw new RestException(403);
1755 }
1756 if (empty($id)) {
1757 throw new RestException(400, 'Invoice ID is mandatory');
1758 }
1759
1760 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1761 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1762 }
1763
1764 if (isModEnabled("bank")) {
1765 if (empty($accountid)) {
1766 throw new RestException(400, 'Account ID is mandatory');
1767 }
1768 }
1769
1770 if (empty($paymentid)) {
1771 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1772 }
1773
1774
1775 $result = $this->invoice->fetch($id);
1776 if (!$result) {
1777 throw new RestException(404, 'Invoice not found');
1778 }
1779
1780 // Calculate amount to pay
1781 $totalpaid = $this->invoice->getSommePaiement();
1782 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1783 $totaldeposits = $this->invoice->getSumDepositsUsed();
1784
1785 $this->db->begin();
1786
1787 $amounts = array();
1788 $multicurrency_amounts = array();
1789
1790 // Clean parameters amount if payment is for a credit note
1791 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1792 $resteapayer = price2num($this->invoice->total_ttc + $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1793 $amounts[$id] = (float) price2num(-1 * abs((float) $resteapayer), 'MT');
1794 // Multicurrency
1795 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1796 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1797 } else {
1798 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1799 $amounts[$id] = (float) $resteapayer;
1800 // Multicurrency
1801 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1802 $multicurrency_amounts[$id] = (float) $newvalue;
1803 }
1804
1805 // Creation of payment line
1806 $paymentobj = new Paiement($this->db);
1807 if (is_numeric($datepaye)) {
1808 $paymentobj->datepaye = $datepaye;
1809 } else {
1810 $paymentobj->datepaye = dol_stringtotime($datepaye);
1811 }
1812 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1813 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1814 $paymentobj->paiementid = $paymentid;
1815 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1816 $paymentobj->num_payment = $num_payment;
1817 $paymentobj->note_private = $comment;
1818
1819 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1820 if ($payment_id < 0) {
1821 $this->db->rollback();
1822 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1823 }
1824
1825 if (isModEnabled("bank")) {
1826 $label = '(CustomerInvoicePayment)';
1827
1828 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1829 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1830 }
1831 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1832 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1833 }
1834 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1835 if ($result < 0) {
1836 $this->db->rollback();
1837 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1838 }
1839 }
1840
1841 $this->db->commit();
1842
1843 return $payment_id;
1844 }
1845
1876 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1877 {
1878 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1879
1880 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
1881 throw new RestException(403);
1882 }
1883 foreach ($arrayofamounts as $id => $amount) {
1884 if (empty($id)) {
1885 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1886 }
1887 if (!DolibarrApi::_checkAccessToResource('facture', (int) $id)) {
1888 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1889 }
1890 }
1891
1892 if (isModEnabled("bank")) {
1893 if (empty($accountid)) {
1894 throw new RestException(400, 'Account ID is mandatory');
1895 }
1896 }
1897 if (empty($paymentid)) {
1898 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1899 }
1900
1901 $this->db->begin();
1902
1903 $amounts = array();
1904 $multicurrency_amounts = array();
1905
1906 // Loop on each invoice to pay
1907 foreach ($arrayofamounts as $id => $amountarray) {
1908 $id = (int) $id; // Ensure $id is seen as int, required by function calls and array indexes.
1909 $result = $this->invoice->fetch($id);
1910 if (!$result) {
1911 $this->db->rollback();
1912 throw new RestException(404, 'Invoice ID '.$id.' not found');
1913 }
1914
1915 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1916 $this->db->rollback();
1917 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1918 }
1919
1920 $is_multicurrency = 0;
1921 $total_ttc = $this->invoice->total_ttc;
1922
1923 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1924 $is_multicurrency = 1;
1925 $total_ttc = $this->invoice->multicurrency_total_ttc;
1926 }
1927
1928 // Calculate amount to pay
1929 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1930 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1931 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1932 $remainstopay = $amount = (float) price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1933
1934 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1935 $amount = (float) price2num($amountarray["amount"], 'MT');
1936 }
1937
1938 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1939 $amount = (float) price2num($amountarray["multicurrency_amount"], 'MT');
1940 }
1941
1942 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
1943 $this->db->rollback();
1944 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1945 }
1946
1947 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1948 $amount = (float) price2num(-1 * abs((float) $amount), 'MT');
1949 }
1950
1951 if ($is_multicurrency) {
1952 $amounts[$id] = null;
1953 // Multicurrency
1954 $multicurrency_amounts[$id] = (float) $amount;
1955 } else {
1956 $amounts[$id] = (float) $amount;
1957 // Multicurrency
1958 $multicurrency_amounts[$id] = null;
1959 }
1960 }
1961
1962 // Creation of payment line
1963 $paymentobj = new Paiement($this->db);
1964 if (is_numeric($datepaye)) {
1965 $paymentobj->datepaye = $datepaye;
1966 } else {
1967 $paymentobj->datepaye = dol_stringtotime($datepaye);
1968 }
1969 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1970 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1971 $paymentobj->paiementid = $paymentid;
1972 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1973 $paymentobj->num_payment = $num_payment;
1974 $paymentobj->note_private = $comment;
1975 $paymentobj->ref_ext = $ref_ext;
1976 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1977 if ($payment_id < 0) {
1978 $this->db->rollback();
1979 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1980 }
1981 if (isModEnabled("bank")) {
1982 $label = '(CustomerInvoicePayment)';
1983 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1984 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1985 }
1986 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1987 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1988 }
1989 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1990 if ($result < 0) {
1991 $this->db->rollback();
1992 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1993 }
1994 }
1995
1996 $this->db->commit();
1997
1998 return $payment_id;
1999 }
2000
2019 public function putPayment($id, $num_payment = '')
2020 {
2021 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2022
2023 if (!DolibarrApiAccess::$user->hasRight('facture', 'paiement')) {
2024 throw new RestException(403);
2025 }
2026 if (empty($id)) {
2027 throw new RestException(400, 'Payment ID is mandatory');
2028 }
2029
2030 $paymentobj = new Paiement($this->db);
2031 $result = $paymentobj->fetch($id);
2032
2033 if (!$result) {
2034 throw new RestException(404, 'Payment not found');
2035 }
2036
2037 // Check all invoices of the payment to see if the user has permission on them for the object level permission test
2038 $tmparray = $paymentobj->getBillsArray();
2039 foreach ($tmparray as $tmpinvoiceid) {
2040 if (!DolibarrApi::_checkAccessToResource('facture', $tmpinvoiceid)) {
2041 throw new RestException(403, 'Payment is on invoices that are not all allowed for login '.DolibarrApiAccess::$user->login);
2042 }
2043 }
2044
2045 if (!empty($num_payment)) {
2046 $result = $paymentobj->update_num($num_payment);
2047 if ($result < 0) {
2048 throw new RestException(500, 'Error when updating the payment num');
2049 }
2050 }
2051
2052 return [
2053 'success' => [
2054 'code' => 200,
2055 'message' => 'Payment updated'
2056 ]
2057 ];
2058 }
2059
2060 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2070 protected function _cleanObjectDatas($object)
2071 {
2072 // phpcs:enable
2073 $object = parent::_cleanObjectDatas($object);
2074
2075 unset($object->note);
2076 unset($object->address);
2077 unset($object->barcode_type);
2078 unset($object->barcode_type_code);
2079 unset($object->barcode_type_label);
2080 unset($object->barcode_type_coder);
2081 unset($object->canvas);
2082
2083 return $object;
2084 }
2085
2094 private function _validate($data)
2095 {
2096 if ($data === null) {
2097 $data = array();
2098 }
2099 $invoice = array();
2100 foreach (Invoices::$FIELDS as $field) {
2101 if (!isset($data[$field])) {
2102 throw new RestException(400, "$field field missing");
2103 }
2104 $invoice[$field] = $data[$field];
2105 }
2106 return $invoice;
2107 }
2108
2109
2125 public function getTemplateInvoice($id, $contact_list = 1)
2126 {
2127 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
2128 }
2129
2130
2158 public function indexTemplateInvoices($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
2159 {
2160 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2161 throw new RestException(403);
2162 }
2163
2164 $obj_ret = array();
2165
2166 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
2167 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
2168
2169
2170 // If the internal user must only see his customers, force searching by him
2171 $search_sale = 0;
2172 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
2173 $search_sale = DolibarrApiAccess::$user->id;
2174 }
2175
2176 $sql = "SELECT t.rowid";
2177 $sql .= " FROM ".MAIN_DB_PREFIX."facture_rec AS t";
2178 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
2179 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_rec_extrafields AS ef ON (ef.fk_object = t.rowid)";
2180 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
2181 if ($socids) {
2182 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
2183 }
2184
2185 // Search on sale representative
2186 if ($search_sale && $search_sale != '-1') {
2187 if ($search_sale == -2) {
2188 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux AS sc WHERE sc.fk_soc = t.fk_soc)";
2189 } elseif ($search_sale > 0) {
2190 $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).")";
2191 }
2192 }
2193
2194 // Filter by status
2195 if ($status == 'active') {
2196 $sql .= " AND t.suspended = 0 AND t.frequency IS NOT NULL";
2197 }
2198 if ($status == 'suspended') {
2199 $sql .= " AND t.suspended = 1 AND t.frequency IS NOT NULL";
2200 }
2201 if ($status == 'draft') {
2202 $sql .= " AND t.frequency IS NULL";
2203 }
2204 // add sql filters
2205 if ($sqlfilters) {
2206 $errormessage = '';
2207 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
2208 if ($errormessage) {
2209 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
2210 }
2211 }
2212
2213 //this query will return total template invoices with the filters given
2214 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
2215
2216 $sql .= $this->db->order($sortfield, $sortorder);
2217 if ($limit) {
2218 if ($page < 0) {
2219 $page = 0;
2220 }
2221 $offset = $limit * $page;
2222
2223 $sql .= $this->db->plimit($limit + 1, $offset);
2224 }
2225
2226 $result = $this->db->query($sql);
2227 if ($result) {
2228 $i = 0;
2229 $num = $this->db->num_rows($result);
2230 $min = min($num, ($limit <= 0 ? $num : $limit));
2231 while ($i < $min) {
2232 $obj = $this->db->fetch_object($result);
2233 $factureRec = new FactureRec($this->db);
2234 if ($factureRec->fetch($obj->rowid) > 0) {
2235 if ($loadlinkedobjects) {
2236 // retrieve linked objects
2237 $factureRec->fetchObjectLinked();
2238 }
2239
2240 if (!$withLines) {
2241 unset($factureRec->lines);
2242 }
2243
2244 $obj_ret[] = $this->_filterObjectProperties($this->_cleanTemplateObjectDatas($factureRec), $properties);
2245 }
2246 $i++;
2247 }
2248 } else {
2249 throw new RestException(503, 'Error when retrieving recurring invoice templates: '.$this->db->lasterror());
2250 }
2251
2252 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
2253 if ($pagination_data) {
2254 $totalsResult = $this->db->query($sqlTotals);
2255 $total = $this->db->fetch_object($totalsResult)->total;
2256
2257 $tmp = $obj_ret;
2258 $obj_ret = array();
2259
2260 $obj_ret['data'] = $tmp;
2261 $obj_ret['pagination'] = array(
2262 'total' => (int) $total,
2263 'page' => $page,
2264 'page_count' => ceil((int) $total / $limit),
2265 'limit' => $limit
2266 );
2267 }
2268
2269 return $obj_ret;
2270 }
2271
2285 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
2286 {
2287 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2288 throw new RestException(403);
2289 }
2290
2291 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
2292 if (!$result) {
2293 throw new RestException(404, 'Template invoice not found');
2294 }
2295
2296 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
2297 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2298 }
2299
2300 // Add external contacts ids
2301 if ($contact_list > -1) {
2302 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
2303 if (is_array($tmparray)) {
2304 $this->template_invoice->contacts_ids = $tmparray;
2305 }
2306 }
2307
2308 $this->template_invoice->fetchObjectLinked();
2309 return $this->_cleanTemplateObjectDatas($this->template_invoice);
2310 }
2311
2312
2313 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2321 {
2322 // phpcs:enable
2323 $object = parent::_cleanObjectDatas($object);
2324
2325 unset($object->note);
2326 unset($object->address);
2327 unset($object->barcode_type);
2328 unset($object->barcode_type_code);
2329 unset($object->barcode_type_label);
2330 unset($object->barcode_type_coder);
2331 unset($object->canvas);
2332
2333 return $object;
2334 }
2335}
$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 templates.
putPayment($id, $num_payment='')
Update a payment.
addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0)
Adds a contact to an invoice.
indexTemplateInvoices($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false, $loadlinkedobjects=0, $withLines=true)
List template invoices.
createInvoiceFromOrder($orderid)
Create an invoice using an existing order.
markAsCreditAvailable($id)
Create a discount (credit available) for a credit note or a deposit.
getDiscount($id)
Get discount from invoice.
__construct()
Constructor.
put($id, $request_data=null)
Update invoice.
validate($id, $force_number='', $idwarehouse=0, $notrigger=0)
Validate an invoice.
getContacts($id, $type='')
Get contacts of given invoice.
getByRefExt($ref_ext, $contact_list=1)
Get properties of an invoice object by ref_ext.
_fetch($id, $ref='', $ref_ext='', $contact_list=1)
Get properties of an invoice object.
getByRef($ref, $contact_list=1)
Get properties of an invoice object by ref.
getPayments($id)
Get list of payments of a given invoice.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
post($request_data=null)
Create invoice object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false, $loadlinkedobjects=0, $withLines=true)
List invoices.
useDiscount($id, $discountid)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount.
settounpaid($id)
Sets an invoice as unpaid.
getTemplateInvoice($id, $contact_list=1)
Get properties of a template invoice object.
putLine($id, $lineid, $request_data=null)
Update a line to a given invoice.
getLines($id)
Get lines of an invoice.
useCreditNote($id, $discountid)
Add an available credit note discount to payments of an existing invoice.
createInvoiceFromContract($contractid)
Create an invoice using a contract.
addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='', $ref_ext='', $accepthigherpayment=false)
Add a payment to pay partially or completely one or several invoices.
postContact($id, $contactid, $type, $source='external', $notrigger=0)
Add a contact type of given invoice.
_cleanTemplateObjectDatas($object)
Clean sensible object datas.
deleteContact($id, $contactid, $type)
Delete a contact type of given invoice.
postLine($id, $request_data=null)
Add a line to a given invoice.
_fetchTemplateInvoice($id, $ref='', $ref_ext='', $contact_list=1)
Get properties of an invoice object.
_validate($data)
Validate fields before create or update object.
addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='')
Add payment line to a specific invoice with the remain to pay as amount.
settopaid($id, $close_code='', $close_note='')
Sets an invoice as paid.
settodraft($id, $idwarehouse=-1)
Sets an invoice as draft.
deleteLine($id, $lineid)
Deletes a line of a given invoice.
Class to manage payments of customer invoices.
Class to manage third parties objects (customers, suppliers, prospects...)
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:436
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_now($mode='gmt')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
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.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.