dolibarr 23.0.4
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-2025 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2025 Charlene Benke <charlene@patas-monkey.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23use Luracast\Restler\RestException;
24
25require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
26require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
27
28
35class Invoices extends DolibarrApi
36{
40 public static $FIELDS = array(
41 'socid',
42 );
43
47 private $invoice;
48
52 private $template_invoice;
53
54
58 public function __construct()
59 {
60 global $db;
61 $this->db = $db;
62 $this->invoice = new Facture($this->db);
63 $this->template_invoice = new FactureRec($this->db);
64 }
65
79 public function get($id, $contact_list = 1, $properties = '', $withLines = true)
80 {
81 $invoice = $this->_fetch($id, '', '', $contact_list);
82
83 if (!$withLines) {
84 unset($invoice->lines);
85 }
86
87 return $this->_filterObjectProperties($invoice, $properties);
88 }
89
103 public function getByRef($ref, $contact_list = 1)
104 {
105 return $this->_fetch(0, $ref, '', $contact_list);
106 }
107
121 public function getByRefExt($ref_ext, $contact_list = 1)
122 {
123 return $this->_fetch(0, '', $ref_ext, $contact_list);
124 }
125
139 private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
140 {
141 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
142 throw new RestException(403);
143 }
144 if (empty($id) && empty($ref)&& empty($ref_ext)) {
145 throw new RestException(400, 'No invoice can be found with no criteria');
146 }
147 $result = $this->invoice->fetch($id, $ref, $ref_ext);
148 if (!$result) {
149 throw new RestException(404, 'Invoice not found');
150 }
151
152 // Get payment details
153 $this->invoice->totalpaid = $this->invoice->getSommePaiement();
154 $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
155 $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed();
156 $this->invoice->remaintopay = price2num($this->invoice->total_ttc - $this->invoice->totalpaid - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits, 'MT');
157
158 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
159 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
160 }
161
162 // Retrieve credit note ids
163 $this->invoice->getListIdAvoirFromInvoice();
164
165 // Add external contacts ids
166 if ($contact_list > -1) {
167 $tmparray = $this->invoice->liste_contact(-1, 'external', $contact_list);
168 if (is_array($tmparray)) {
169 $this->invoice->contacts_ids = $tmparray;
170 }
171 $tmparray = $this->invoice->liste_contact(-1, 'internal', $contact_list);
172 if (is_array($tmparray)) {
173 $this->invoice->contacts_ids = $tmparray;
174 }
175 }
176
177 $this->invoice->fetchObjectLinked();
178
179 // Add online_payment_url, copied from order
180 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
181 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $this->invoice->ref);
182
183 return $this->_cleanObjectDatas($this->invoice);
184 }
185
209 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
210 {
211 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
212 throw new RestException(403);
213 }
214
215 $obj_ret = array();
216
217 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
218 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
219
220 // If the internal user must only see his customers, force searching by him
221 $search_sale = 0;
222 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
223 $search_sale = DolibarrApiAccess::$user->id;
224 }
225
226 $sql = "SELECT t.rowid";
227 $sql .= " FROM ".MAIN_DB_PREFIX."facture AS t";
228 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
229 $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
230 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
231 if ($socids) {
232 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
233 }
234 // Search on sale representative
235 if ($search_sale && $search_sale != '-1') {
236 if ($search_sale == -2) {
237 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
238 } elseif ($search_sale > 0) {
239 $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).")";
240 }
241 }
242 // Filter by status
243 if ($status == 'draft') {
244 $sql .= " AND t.fk_statut IN (0)";
245 }
246 if ($status == 'unpaid') {
247 $sql .= " AND t.fk_statut IN (1)";
248 }
249 if ($status == 'paid') {
250 $sql .= " AND t.fk_statut IN (2)";
251 }
252 if ($status == 'cancelled') {
253 $sql .= " AND t.fk_statut IN (3)";
254 }
255 // Add sql filters
256 if ($sqlfilters) {
257 $errormessage = '';
258 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
259 if ($errormessage) {
260 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
261 }
262 }
263
264 //this query will return total invoices with the filters given
265 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
266
267 $sql .= $this->db->order($sortfield, $sortorder);
268 if ($limit) {
269 if ($page < 0) {
270 $page = 0;
271 }
272 $offset = $limit * $page;
273
274 $sql .= $this->db->plimit($limit + 1, $offset);
275 }
276
277 $result = $this->db->query($sql);
278 if ($result) {
279 $i = 0;
280 $num = $this->db->num_rows($result);
281 $min = min($num, ($limit <= 0 ? $num : $limit));
282 while ($i < $min) {
283 $obj = $this->db->fetch_object($result);
284 $invoice_static = new Facture($this->db);
285 if ($invoice_static->fetch($obj->rowid) > 0) {
286 // Get payment details
287 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
288 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
289 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
290 $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT');
291
292 // Retrieve credit note ids
293 $invoice_static->getListIdAvoirFromInvoice();
294
295 // Add external contacts ids
296 $tmparray = $invoice_static->liste_contact(-1, 'external', 1);
297 if (is_array($tmparray)) {
298 $invoice_static->contacts_ids = $tmparray;
299 }
300
301 if ($loadlinkedobjects) {
302 // retrieve linked objects
303 $invoice_static->fetchObjectLinked();
304 }
305
306 if (!$withLines) {
307 unset($invoice_static->lines);
308 }
309
310 // Add online_payment_url, copied from order
311 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
312 $invoice_static->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $invoice_static->ref);
313
314 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($invoice_static), $properties);
315 }
316 $i++;
317 }
318 } else {
319 throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror());
320 }
321
322 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
323 if ($pagination_data) {
324 $totalsResult = $this->db->query($sqlTotals);
325 $total = $this->db->fetch_object($totalsResult)->total;
326
327 $tmp = $obj_ret;
328 $obj_ret = [];
329
330 $obj_ret['data'] = $tmp;
331 $obj_ret['pagination'] = [
332 'total' => (int) $total,
333 'page' => $page, //count starts from 0
334 'page_count' => ceil((int) $total / $limit),
335 'limit' => $limit
336 ];
337 }
338
339 return $obj_ret;
340 }
341
350 public function post($request_data = null)
351 {
352 global $conf;
353 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
354 throw new RestException(403, "Insufficiant rights");
355 }
356
357 if (!is_array($request_data)) {
358 $request_data = array();
359 }
360
361 // Check mandatory fields (not using output, only possible exception is important)
362 $this->_validate($request_data);
363
364 // Check thirdparty validity
365 $socid = (int) $request_data['socid'];
366 $thirdpartytmp = new Societe($this->db);
367 $thirdparty_result = $thirdpartytmp->fetch($socid);
368 if ($thirdparty_result < 1) {
369 throw new RestException(404, 'Thirdparty with id='.$socid.' not found or not allowed');
370 }
371 if (!DolibarrApi::_checkAccessToResource('societe', $thirdpartytmp->id)) {
372 throw new RestException(404, 'Thirdparty with id='.$thirdpartytmp->id.' not found or not allowed');
373 }
374
375 foreach ($request_data as $field => $value) {
376 if ($field === 'caller') {
377 // 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
378 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
379 continue;
380 }
381 if ($field == 'id') {
382 throw new RestException(400, 'Creating with id field is forbidden');
383 }
384 if ($field == 'entity' && ((int) $value) != ((int) $conf->entity)) {
385 throw new RestException(403, 'Creating with entity='.((int) $value).' MUST be the same entity='.((int) $conf->entity).' as your API user/key belongs to');
386 }
387
388 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
389 }
390 if (!array_key_exists('date', $request_data)) {
391 $this->invoice->date = dol_now();
392 }
393 /* We keep lines as an array
394 if (isset($request_data["lines"])) {
395 $lines = array();
396 foreach ($request_data["lines"] as $line) {
397 array_push($lines, (object) $line);
398 }
399 $this->invoice->lines = $lines;
400 }*/
401
402 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) {
403 throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
404 }
405 return ((int) $this->invoice->id);
406 }
407
422 public function createInvoiceFromOrder($orderid)
423 {
424 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
425
426 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
427 throw new RestException(403);
428 }
429 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
430 throw new RestException(403);
431 }
432 if (empty($orderid)) {
433 throw new RestException(400, 'Order ID is mandatory');
434 }
435 if (!DolibarrApi::_checkAccessToResource('commande', $orderid)) {
436 throw new RestException(403, 'Access not allowed on order for login '.DolibarrApiAccess::$user->login);
437 }
438
439 $order = new Commande($this->db);
440 $result = $order->fetch($orderid);
441 if (!$result) {
442 throw new RestException(404, 'Order not found');
443 }
444
445 // Refuse orders that cannot be billed, to mirror the GUI (order card "CreateBill" button and list mass action):
446 // this excludes draft and canceled orders, as well as orders already classified as billed.
447 if ($order->status <= Commande::STATUS_DRAFT || !empty($order->billed)) {
448 throw new RestException(405, 'Order '.$order->ref.' is not eligible for invoicing: its status does not allow creating an invoice');
449 }
450
451 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
452 if ($result < 0) {
453 throw new RestException(405, $this->invoice->error);
454 }
455 $this->invoice->fetchObjectLinked();
456 return $this->_cleanObjectDatas($this->invoice);
457 }
458
472 public function createInvoiceFromContract($contractid)
473 {
474 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
475
476 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
477 throw new RestException(403);
478 }
479 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
480 throw new RestException(403);
481 }
482 if (empty($contractid)) {
483 throw new RestException(400, 'Contract ID is mandatory');
484 }
485
486 $contract = new Contrat($this->db);
487 $result = $contract->fetch($contractid);
488 if (!$result) {
489 throw new RestException(404, 'Contract not found');
490 }
491 if (!DolibarrApi::_checkAccessToResource('contrat', $contract->id)) {
492 throw new RestException(403, 'Access to contract '.$contract->id.' not allowed for login '.DolibarrApiAccess::$user->login);
493 }
494
495 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
496 if ($result < 0) {
497 throw new RestException(405, $this->invoice->error);
498 }
499 $this->invoice->fetchObjectLinked();
500 return $this->_cleanObjectDatas($this->invoice);
501 }
502
513 public function getLines($id)
514 {
515 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
516 throw new RestException(403);
517 }
518
519 $result = $this->invoice->fetch($id);
520 if (!$result) {
521 throw new RestException(404, 'Invoice not found');
522 }
523
524 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
525 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
526 }
527 $this->invoice->getLinesArray();
528 $result = array();
529 foreach ($this->invoice->lines as $line) {
530 array_push($result, $this->_cleanObjectDatas($line));
531 }
532 return $result;
533 }
534
551 public function putLine($id, $lineid, $request_data = null)
552 {
553 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
554 throw new RestException(403);
555 }
556
557 $result = $this->invoice->fetch($id);
558 if (!$result) {
559 throw new RestException(404, 'Invoice not found');
560 }
561
562 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
563 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
564 }
565
566 $request_data = (object) $request_data;
567
568 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
569 $request_data->label = sanitizeVal($request_data->label);
570
571 $invoiceline = new FactureLigne($this->db);
572 $result = $invoiceline->fetch($lineid);
573 if (!$result) {
574 throw new RestException(404, 'Invoice line not found');
575 }
576
577 if ($invoiceline->fk_facture != $id) {
578 throw new RestException(403, 'Line does not belong to this invoice');
579 }
580
581 $updateRes = $this->invoice->updateline(
582 $lineid,
583 $request_data->desc,
584 $request_data->subprice,
585 $request_data->qty,
586 $request_data->remise_percent,
587 $request_data->date_start,
588 $request_data->date_end,
589 $request_data->tva_tx,
590 $request_data->localtax1_tx,
591 $request_data->localtax2_tx,
592 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
593 $request_data->info_bits,
594 $request_data->product_type,
595 $request_data->fk_parent_line,
596 0,
597 $request_data->fk_fournprice,
598 $request_data->pa_ht,
599 $request_data->label,
600 $request_data->special_code,
601 $request_data->array_options,
602 $request_data->situation_percent,
603 $request_data->fk_unit,
604 $request_data->multicurrency_subprice,
605 0,
606 $request_data->ref_ext,
607 $request_data->rang
608 );
609
610 if ($updateRes > 0) {
611 $result = $this->get($id);
612 unset($result->line);
613 return $this->_cleanObjectDatas($result);
614 } else {
615 throw new RestException(304, $this->invoice->error);
616 }
617 }
618
636 public function postContact($id, $contactid, $type, $source = 'external', $notrigger = 0)
637 {
638 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
639 throw new RestException(403);
640 }
641
642 // test source
643 if (empty($source)) {
644 throw new RestException(400, 'Source can not be empty');
645 }
646 $sql_distinct_source = "SELECT DISTINCT source";
647 $sql_distinct_source .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
648 $sql_distinct_source .= " WHERE element LIKE 'facture'";
649 $sql_distinct_source .= " AND source is NOT NULL";
650 $sql_distinct_source .= " AND active != 0";
651 $source_result = $this->db->query($sql_distinct_source);
652 $source_array = array();
653
654 if ($source_result) {
655 $num = $this->db->num_rows($source_result);
656 $i = 0;
657 while ($i < $num) {
658 $obj = $this->db->fetch_object($source_result);
659 $source_kind = (string) $obj->source;
660 array_push($source_array, $source_kind);
661 dol_syslog("source_kind=".$source_kind);
662 $i++;
663 }
664 } else {
665 throw new RestException(503, 'Error when retrieving a list of invoice contact sources: '.$this->db->lasterror());
666 }
667 if (!in_array($source, (array) $source_array, true)) {
668 throw new RestException(400, 'Combo of Source='.$source.' and Type='.$type.' not found in dictionary with active invoice contact types');
669 }
670
671 // test type
672 if (empty($type)) {
673 throw new RestException(400, 'type can not be empty');
674 }
675 // variable called type here, but code in dictionary and database
676 $sql_distinct_type = "SELECT DISTINCT code";
677 $sql_distinct_type .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
678 $sql_distinct_type .= " WHERE element LIKE 'facture'";
679 $sql_distinct_type .= " AND source='".$this->db->escape($source)."'";
680 $sql_distinct_type .= " AND code is NOT NULL";
681 $sql_distinct_type .= " AND active != 0";
682 $type_result = $this->db->query($sql_distinct_type);
683 $type_array = array();
684
685 if ($type_result) {
686 $num = $this->db->num_rows($type_result);
687 $i = 0;
688 while ($i < $num) {
689 $obj = $this->db->fetch_object($type_result);
690 // variable called type here, but code in dictionary and database
691 $type_kind = (string) $obj->code;
692 array_push($type_array, $type_kind);
693 dol_syslog("type_kind=".$type_kind);
694 $i++;
695 }
696 } else {
697 throw new RestException(503, 'Error when retrieving a list of invoice contact types: '.$this->db->lasterror());
698 }
699 if (!in_array($type, (array) $type_array, true)) {
700 throw new RestException(400, 'Combo of Type='.$type.' and Source='.$source.' not found in dictionary with active invoice contact types');
701 }
702
703 // tests done, let's get it
704 $result = $this->invoice->fetch($id);
705 if (!$result) {
706 throw new RestException(404, 'Invoice not found');
707 }
708 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
709 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
710 }
711
712 $result = $this->invoice->add_contact($contactid, $type, $source, $notrigger);
713
714 if ($result == 0) {
715 throw new RestException(400, 'Already exists: Contact='.$contactid.' is already linked to the invoice='.$id.' as source='.$source.' and type='.$type);
716 } elseif ($result == -1) {
717 throw new RestException(400, 'Wrong contact='.$contactid);
718 } elseif ($result == -2) {
719 throw new RestException(400, 'Wrong type='.$type);
720 } elseif ($result == -3) {
721 throw new RestException(400, 'Not allowed contacts');
722 } elseif ($result == -4) {
723 throw new RestException(400, 'ErrorCommercialNotAllowedForThirdparty');
724 } elseif ($result == -5) {
725 throw new RestException(400, 'Trigger failed');
726 } elseif ($result == -6) {
727 throw new RestException(400, 'DB_ERROR_RECORD_ALREADY_EXISTS');
728 } elseif ($result == -7) {
729 throw new RestException(400, 'Some other error');
730 }
731
732 if (!$result) {
733 throw new RestException(500, 'Error when added the contact');
734 }
735
736 return array(
737 'success' => array(
738 'code' => 200,
739 'message' => 'Contact='.$contactid.' linked to the invoice='.$id.' as '.$source.' '.$type
740 )
741 );
742 }
743
757 public function getContacts($id, $type = '')
758 {
759 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
760 throw new RestException(403);
761 }
762
763 $result = $this->invoice->fetch($id);
764 if (!$result) {
765 throw new RestException(404, 'Invoice not found');
766 }
767
768 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
769 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
770 }
771
772 $contacts = $this->invoice->liste_contact(-1, 'external', 0, $type);
773 $socpeoples = $this->invoice->liste_contact(-1, 'internal', 0, $type);
774
775 $contacts = array_merge($contacts, $socpeoples);
776
777 return $contacts;
778 }
779
794 public function deleteContact($id, $contactid, $type)
795 {
796 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
797 throw new RestException(403);
798 }
799
800 $result = $this->invoice->fetch($id);
801
802 if (!$result) {
803 throw new RestException(404, 'Invoice not found');
804 }
805
806 if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) {
807 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
808 }
809
810 $contacts = $this->invoice->liste_contact();
811
812 foreach ($contacts as $contact) {
813 if ($contact['id'] == $contactid && $contact['code'] == $type) {
814 $result = $this->invoice->delete_contact($contact['rowid']);
815
816 if (!$result) {
817 throw new RestException(500, 'Error when deleted the contact');
818 }
819 }
820 }
821
822 return $this->_cleanObjectDatas($this->invoice);
823 }
824
839 public function deleteLine($id, $lineid)
840 {
841 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
842 throw new RestException(403);
843 }
844 if (empty($lineid)) {
845 throw new RestException(400, 'Line ID is mandatory');
846 }
847
848 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
849 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
850 }
851
852 $result = $this->invoice->fetch($id);
853 if (!$result) {
854 throw new RestException(404, 'Invoice not found');
855 }
856 if ($this->invoice->status != 0) {
857 throw new RestException(403, 'Invoice not in Draft Status : '.$this->invoice->getLibStatut(1));
858 }
859
860 $updateRes = $this->invoice->deleteLine($lineid, $id);
861 if ($updateRes > 0) {
862 return $this->get($id);
863 } else {
864 throw new RestException(405, $this->invoice->error);
865 }
866 }
867
877 public function put($id, $request_data = null)
878 {
879 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
880 throw new RestException(403);
881 }
882 if ($id == 0) {
883 throw new RestException(400, 'No invoice with id=0 can exist');
884 }
885 $result = $this->invoice->fetch($id);
886 if (!$result) {
887 throw new RestException(404, 'Invoice not found');
888 }
889
890 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
891 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
892 }
893
894 foreach ($request_data as $field => $value) {
895 if ($field == 'id') {
896 continue;
897 }
898 if ($field === 'caller') {
899 // 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
900 $this->invoice->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
901 continue;
902 }
903 if ($field == 'array_options' && is_array($value)) {
904 foreach ($value as $index => $val) {
905 $this->invoice->array_options[$index] = $this->_checkValForAPI($field, $val, $this->invoice);
906 }
907 continue;
908 }
909
910 $this->invoice->$field = $this->_checkValForAPI($field, $value, $this->invoice);
911
912 // If cond reglement => update date lim reglement
913 if ($field == 'cond_reglement_id') {
914 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
915 }
916 }
917
918 // update bank account
919 if (!empty($this->invoice->fk_account)) {
920 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
921 throw new RestException(400, $this->invoice->error);
922 }
923 }
924
925 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
926 return $this->get($id);
927 } else {
928 throw new RestException(500, $this->invoice->error);
929 }
930 }
931
940 public function delete($id)
941 {
942 if (!DolibarrApiAccess::$user->hasRight('facture', 'supprimer')) {
943 throw new RestException(403);
944 }
945 if ($id == 0) {
946 throw new RestException(400, 'No invoice with id=0 can exist');
947 }
948 $result = $this->invoice->fetch($id);
949 if (!$result) {
950 throw new RestException(404, 'Invoice not found');
951 }
952
953 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
954 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
955 }
956
957 $result = $this->invoice->delete(DolibarrApiAccess::$user);
958 if ($result < 0) {
959 throw new RestException(500, 'Error when deleting invoice');
960 } elseif ($result == 0) {
961 throw new RestException(403, 'Invoice not erasable');
962 }
963
964 return array(
965 'success' => array(
966 'code' => 200,
967 'message' => 'Invoice deleted'
968 )
969 );
970 }
971
997 public function postLine($id, $request_data = null)
998 {
999 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1000 throw new RestException(403);
1001 }
1002
1003 $result = $this->invoice->fetch($id);
1004 if (!$result) {
1005 throw new RestException(404, 'Invoice not found');
1006 }
1007
1008 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1009 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1010 }
1011
1012 $request_data = (object) $request_data;
1013
1014 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
1015 $request_data->label = sanitizeVal($request_data->label);
1016
1017 // Reset fk_parent_line for no child products and special product
1018 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
1019 $request_data->fk_parent_line = 0;
1020 }
1021
1022 // calculate pa_ht
1023 $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);
1024 $pa_ht = $marginInfos[0];
1025
1026 $updateRes = $this->invoice->addline(
1027 $request_data->desc,
1028 $request_data->subprice,
1029 $request_data->qty,
1030 $request_data->tva_tx,
1031 $request_data->localtax1_tx,
1032 $request_data->localtax2_tx,
1033 $request_data->fk_product,
1034 $request_data->remise_percent,
1035 $request_data->date_start,
1036 $request_data->date_end,
1037 $request_data->fk_code_ventilation,
1038 $request_data->info_bits,
1039 $request_data->fk_remise_except,
1040 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
1041 $request_data->subprice,
1042 $request_data->product_type,
1043 $request_data->rang,
1044 $request_data->special_code,
1045 $request_data->origin,
1046 $request_data->origin_id,
1047 $request_data->fk_parent_line,
1048 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
1049 $pa_ht,
1050 $request_data->label,
1051 $request_data->array_options,
1052 $request_data->situation_percent,
1053 $request_data->fk_prev_id,
1054 $request_data->fk_unit,
1055 0,
1056 $request_data->ref_ext
1057 );
1058
1059 if ($updateRes < 0) {
1060 throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
1061 }
1062
1063 return $updateRes;
1064 }
1065
1084 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
1085 {
1086 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1087 throw new RestException(403);
1088 }
1089 $result = $this->invoice->fetch($id);
1090 if (!$result) {
1091 throw new RestException(404, 'Invoice not found');
1092 }
1093
1094 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1095 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1096 }
1097
1098 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
1099 if ($result < 0) {
1100 throw new RestException(500, 'Error : '.$this->invoice->error);
1101 }
1102
1103 $result = $this->invoice->fetch($id);
1104 if (!$result) {
1105 throw new RestException(404, 'Invoice not found');
1106 }
1107
1108 // test already done
1109 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1110 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1111 // }
1112
1113 return $this->_cleanObjectDatas($this->invoice);
1114 }
1115
1116
1117
1132 public function settodraft($id, $idwarehouse = -1)
1133 {
1134 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1135 throw new RestException(403);
1136 }
1137 $result = $this->invoice->fetch($id);
1138 if (!$result) {
1139 throw new RestException(404, 'Invoice not found');
1140 }
1141
1142 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1143 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1144 }
1145
1146 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
1147 if ($result == 0) {
1148 throw new RestException(304, 'Nothing done.');
1149 }
1150 if ($result < 0) {
1151 throw new RestException(500, 'Error : '.$this->invoice->error);
1152 }
1153
1154 $result = $this->invoice->fetch($id);
1155 if (!$result) {
1156 throw new RestException(404, 'Invoice not found');
1157 }
1158
1159 return $this->_cleanObjectDatas($this->invoice);
1160 }
1161
1162
1180 public function validate($id, $force_number = '', $idwarehouse = 0, $notrigger = 0)
1181 {
1182 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1183 throw new RestException(403);
1184 }
1185 $result = $this->invoice->fetch($id);
1186 if (!$result) {
1187 throw new RestException(404, 'Invoice not found');
1188 }
1189
1190 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1191 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1192 }
1193
1194 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
1195 if ($result == 0) {
1196 throw new RestException(304, 'Error nothing done. May be object is already validated');
1197 }
1198 if ($result < 0) {
1199 throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
1200 }
1201
1202 $result = $this->invoice->fetch($id);
1203 if (!$result) {
1204 throw new RestException(404, 'Invoice not found');
1205 }
1206
1207 // test already done
1208 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1209 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1210 // }
1211
1212 // copy from order
1213 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1214 $this->invoice->online_payment_url = getOnlinePaymentUrl(0, 'invoice', $this->invoice->ref);
1215
1216 return $this->_cleanObjectDatas($this->invoice);
1217 }
1218
1234 public function settopaid($id, $close_code = '', $close_note = '')
1235 {
1236 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1237 throw new RestException(403);
1238 }
1239 $result = $this->invoice->fetch($id);
1240 if (!$result) {
1241 throw new RestException(404, 'Invoice not found');
1242 }
1243
1244 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1245 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1246 }
1247
1248 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1249 if ($result == 0) {
1250 throw new RestException(304, 'Error nothing done. May be object is already validated');
1251 }
1252 if ($result < 0) {
1253 throw new RestException(500, 'Error : '.$this->invoice->error);
1254 }
1255
1256
1257 $result = $this->invoice->fetch($id);
1258 if (!$result) {
1259 throw new RestException(404, 'Invoice not found');
1260 }
1261
1262 // test already done
1263 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1264 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1265 // }
1266
1267 return $this->_cleanObjectDatas($this->invoice);
1268 }
1269
1270
1284 public function settounpaid($id)
1285 {
1286 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1287 throw new RestException(403);
1288 }
1289 $result = $this->invoice->fetch($id);
1290 if (!$result) {
1291 throw new RestException(404, 'Invoice not found');
1292 }
1293
1294 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1295 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1296 }
1297
1298 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1299 if ($result == 0) {
1300 throw new RestException(304, 'Nothing done');
1301 }
1302 if ($result < 0) {
1303 throw new RestException(500, 'Error : '.$this->invoice->error);
1304 }
1305
1306
1307 $result = $this->invoice->fetch($id);
1308 if (!$result) {
1309 throw new RestException(404, 'Invoice not found');
1310 }
1311
1312 // test already done
1313 // if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1314 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1315 // }
1316
1317 return $this->_cleanObjectDatas($this->invoice);
1318 }
1319
1328 public function getDiscount($id)
1329 {
1330 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1331
1332 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1333 throw new RestException(403);
1334 }
1335
1336 $result = $this->invoice->fetch($id);
1337 if (!$result) {
1338 throw new RestException(404, 'Invoice not found');
1339 }
1340
1341 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1342 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1343 }
1344
1345 $discountcheck = new DiscountAbsolute($this->db);
1346 $result = $discountcheck->fetch(0, $this->invoice->id);
1347
1348 if ($result == 0) {
1349 throw new RestException(404, 'Discount not found');
1350 }
1351 if ($result < 0) {
1352 throw new RestException(500, $discountcheck->error);
1353 }
1354
1355 return parent::_cleanObjectDatas($discountcheck);
1356 }
1357
1372 {
1373 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1374
1375 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1376 throw new RestException(403);
1377 }
1378
1379 $result = $this->invoice->fetch($id);
1380 if (!$result) {
1381 throw new RestException(404, 'Invoice not found');
1382 }
1383
1384 if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) {
1385 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1386 }
1387
1388 if ($this->invoice->paye) { // TODO Replace by a test on status
1389 throw new RestException(500, 'Alreay paid');
1390 }
1391
1392 $this->invoice->fetch($id);
1393 $this->invoice->fetch_thirdparty();
1394
1395 // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
1396 $discountcheck = new DiscountAbsolute($this->db);
1397 $result = $discountcheck->fetch(0, $this->invoice->id);
1398
1399 $canconvert = 0;
1400 if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
1401 $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)
1402 }
1403 if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) {
1404 $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)
1405 }
1406 if ($canconvert) {
1407 $this->db->begin();
1408
1409 $amount_ht = $amount_tva = $amount_ttc = array();
1410 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1411 '
1412 @phan-var-force array<string,float> $amount_ht
1413 @phan-var-force array<string,float> $amount_tva
1414 @phan-var-force array<string,float> $amount_ttc
1415 @phan-var-force array<string,float> $multicurrency_amount_ht
1416 @phan-var-force array<string,float> $multicurrency_amount_tva
1417 @phan-var-force array<string,float> $multicurrency_amount_ttc
1418 ';
1419
1420 // Loop on each vat rate
1421 $i = 0;
1422 foreach ($this->invoice->lines as $line) {
1423 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9
1424 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1425 $amount_ht[$line->tva_tx] = 0.0;
1426 $amount_tva[$line->tva_tx] = 0.0;
1427 $amount_ttc[$line->tva_tx] = 0.0;
1428 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1429 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1430 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1431 }
1432 // no need to create discount if amount is null
1433 $amount_ht[$line->tva_tx] += $line->total_ht;
1434 $amount_tva[$line->tva_tx] += $line->total_tva;
1435 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1436 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1437 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1438 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1439 $i++;
1440 }
1441 }
1442
1443 // Insert one discount by VAT rate category
1444 $discount = new DiscountAbsolute($this->db);
1445 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1446 $discount->description = '(CREDIT_NOTE)';
1447 } elseif ($this->invoice->type == Facture::TYPE_DEPOSIT) {
1448 $discount->description = '(DEPOSIT)';
1449 } elseif ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1450 $discount->description = '(EXCESS RECEIVED)';
1451 } else {
1452 throw new RestException(500, 'Cant convert to reduc an Invoice of this type');
1453 }
1454
1455 $discount->fk_soc = $this->invoice->socid;
1456 $discount->socid = $this->invoice->socid;
1457 $discount->fk_facture_source = $this->invoice->id;
1458
1459 $error = 0;
1460
1461 if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) {
1462 // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
1463
1464 // Total payments
1465 $sql = 'SELECT SUM(pf.amount) as total_payments';
1466 $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
1467 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
1468 $sql .= ' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1469 $sql .= ' AND pf.fk_paiement = p.rowid';
1470 $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
1471 $resql = $this->db->query($sql);
1472 if (!$resql) {
1473 dol_print_error($this->db);
1474 }
1475
1476 $res = $this->db->fetch_object($resql);
1477 $total_payments = $res->total_payments;
1478
1479 // Total credit note and deposit
1480 $total_creditnote_and_deposit = 0;
1481 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1482 $sql .= " re.description, re.fk_facture_source";
1483 $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1484 $sql .= " WHERE fk_facture = ".((int) $this->invoice->id);
1485 $resql = $this->db->query($sql);
1486 if (!empty($resql)) {
1487 while ($obj = $this->db->fetch_object($resql)) {
1488 $total_creditnote_and_deposit += $obj->amount_ttc;
1489 }
1490 } else {
1491 dol_print_error($this->db);
1492 }
1493
1494 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1495 $discount->total_ht = $discount->total_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1496 $discount->amount_tva = 0;
1497 $discount->total_tva = 0;
1498 $discount->tva_tx = 0;
1499
1500 $result = $discount->create(DolibarrApiAccess::$user);
1501 if ($result < 0) {
1502 $error++;
1503 }
1504 }
1505 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) {
1506 foreach ($amount_ht as $tva_tx => $xxx) {
1507 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1508 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1509 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1510 $discount->total_ht = abs($amount_ht[$tva_tx]);
1511 $discount->total_tva = abs($amount_tva[$tva_tx]);
1512 $discount->total_ttc = abs($amount_ttc[$tva_tx]);
1513 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1514 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1515 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1516 $discount->multicurrency_total_ht = abs($multicurrency_amount_ht[$tva_tx]);
1517 $discount->multicurrency_total_tva = abs($multicurrency_amount_tva[$tva_tx]);
1518 $discount->multicurrency_total_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1519 $discount->tva_tx = abs((float) $tva_tx);
1520
1521 $result = $discount->create(DolibarrApiAccess::$user);
1522 if ($result < 0) {
1523 $error++;
1524 break;
1525 }
1526 }
1527 }
1528
1529 if (empty($error)) {
1530 if ($this->invoice->type != Facture::TYPE_DEPOSIT) {
1531 // Set the invoice as paid
1532 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1533 if ($result >= 0) {
1534 $this->db->commit();
1535 } else {
1536 $this->db->rollback();
1537 throw new RestException(500, 'Could not set paid');
1538 }
1539 } else {
1540 $this->db->commit();
1541 }
1542 } else {
1543 $this->db->rollback();
1544 throw new RestException(500, 'Discount creation error');
1545 }
1546 }
1547
1548 return $this->_cleanObjectDatas($this->invoice);
1549 }
1550
1567 public function useDiscount($id, $discountid)
1568 {
1569 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1570 throw new RestException(403);
1571 }
1572 if (empty($id)) {
1573 throw new RestException(400, 'Invoice ID is mandatory');
1574 }
1575 if (empty($discountid)) {
1576 throw new RestException(400, 'Discount ID is mandatory');
1577 }
1578
1579 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1580 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1581 }
1582
1583 $result = $this->invoice->fetch($id);
1584 if (!$result) {
1585 throw new RestException(404, 'Invoice not found');
1586 }
1587
1588 $result = $this->invoice->insert_discount($discountid);
1589 if ($result < 0) {
1590 throw new RestException(405, $this->invoice->error);
1591 }
1592
1593 return $result;
1594 }
1595
1612 public function useCreditNote($id, $discountid)
1613 {
1614 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1615
1616 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1617 throw new RestException(403);
1618 }
1619 if (empty($id)) {
1620 throw new RestException(400, 'Invoice ID is mandatory');
1621 }
1622 if (empty($discountid)) {
1623 throw new RestException(400, 'Credit ID is mandatory');
1624 }
1625
1626 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1627 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1628 }
1629 $discount = new DiscountAbsolute($this->db);
1630 $result = $discount->fetch($discountid);
1631 if (!$result) {
1632 throw new RestException(404, 'Credit not found');
1633 }
1634
1635 $result = $discount->link_to_invoice(0, $id);
1636 if ($result < 0) {
1637 throw new RestException(405, $discount->error);
1638 }
1639
1640 return $result;
1641 }
1642
1658 public function getPayments($id)
1659 {
1660 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
1661 throw new RestException(403);
1662 }
1663 if (empty($id)) {
1664 throw new RestException(400, 'Invoice ID is mandatory');
1665 }
1666
1667 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1668 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1669 }
1670
1671 $result = $this->invoice->fetch($id);
1672 if (!$result) {
1673 throw new RestException(404, 'Invoice not found');
1674 }
1675
1676 $result = $this->invoice->getListOfPayments();
1677 if (!is_array($result) && $result < 0) {
1678 throw new RestException(405, $this->invoice->error);
1679 }
1680
1681 return $result;
1682 }
1683
1684
1706 public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
1707 {
1708 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1709
1710 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1711 throw new RestException(403);
1712 }
1713 if (empty($id)) {
1714 throw new RestException(400, 'Invoice ID is mandatory');
1715 }
1716
1717 if (!DolibarrApi::_checkAccessToResource('facture', $id)) {
1718 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1719 }
1720
1721 if (isModEnabled("bank")) {
1722 if (empty($accountid)) {
1723 throw new RestException(400, 'Account ID is mandatory');
1724 }
1725 }
1726
1727 if (empty($paymentid)) {
1728 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1729 }
1730
1731
1732 $result = $this->invoice->fetch($id);
1733 if (!$result) {
1734 throw new RestException(404, 'Invoice not found');
1735 }
1736
1737 // Calculate amount to pay
1738 $totalpaid = $this->invoice->getSommePaiement();
1739 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1740 $totaldeposits = $this->invoice->getSumDepositsUsed();
1741 $resteapayer = price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1742
1743 $this->db->begin();
1744
1745 $amounts = array();
1746 $multicurrency_amounts = array();
1747
1748 // Clean parameters amount if payment is for a credit note
1749 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1750 $resteapayer = price2num($resteapayer, 'MT');
1751 $amounts[$id] = (float) price2num(-1 * abs((float) $resteapayer), 'MT');
1752 // Multicurrency
1753 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1754 $multicurrency_amounts[$id] = (float) price2num(-1 * (float) $newvalue, 'MT');
1755 } else {
1756 $resteapayer = price2num($resteapayer, 'MT');
1757 $amounts[$id] = (float) $resteapayer;
1758 // Multicurrency
1759 $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
1760 $multicurrency_amounts[$id] = (float) $newvalue;
1761 }
1762
1763 // Creation of payment line
1764 $paymentobj = new Paiement($this->db);
1765 if (is_numeric($datepaye)) {
1766 $paymentobj->datepaye = $datepaye;
1767 } else {
1768 $paymentobj->datepaye = dol_stringtotime($datepaye);
1769 }
1770 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1771 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1772 $paymentobj->paiementid = $paymentid;
1773 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1774 $paymentobj->num_payment = $num_payment;
1775 $paymentobj->note_private = $comment;
1776
1777 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1778 if ($payment_id < 0) {
1779 $this->db->rollback();
1780 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1781 }
1782
1783 if (isModEnabled("bank")) {
1784 $label = '(CustomerInvoicePayment)';
1785
1786 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1787 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1788 }
1789 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1790 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1791 }
1792 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1793 if ($result < 0) {
1794 $this->db->rollback();
1795 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1796 }
1797 }
1798
1799 $this->db->commit();
1800
1801 return $payment_id;
1802 }
1803
1832 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false)
1833 {
1834 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1835
1836 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1837 throw new RestException(403);
1838 }
1839 foreach ($arrayofamounts as $id => $amount) {
1840 if (empty($id)) {
1841 throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1842 }
1843 if (!DolibarrApi::_checkAccessToResource('facture', (int) $id)) {
1844 throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login);
1845 }
1846 }
1847
1848 if (isModEnabled("bank")) {
1849 if (empty($accountid)) {
1850 throw new RestException(400, 'Account ID is mandatory');
1851 }
1852 }
1853 if (empty($paymentid)) {
1854 throw new RestException(400, 'Payment ID or Payment Code is mandatory');
1855 }
1856
1857 $this->db->begin();
1858
1859 $amounts = array();
1860 $multicurrency_amounts = array();
1861
1862 // Loop on each invoice to pay
1863 foreach ($arrayofamounts as $id => $amountarray) {
1864 $result = $this->invoice->fetch((int) $id);
1865 if (!$result) {
1866 $this->db->rollback();
1867 throw new RestException(404, 'Invoice ID '.$id.' not found');
1868 }
1869
1870 if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) {
1871 $this->db->rollback();
1872 throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')');
1873 }
1874
1875 $is_multicurrency = 0;
1876 $total_ttc = $this->invoice->total_ttc;
1877
1878 if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") {
1879 $is_multicurrency = 1;
1880 $total_ttc = $this->invoice->multicurrency_total_ttc;
1881 }
1882
1883 // Calculate amount to pay
1884 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1885 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1886 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1887 $remainstopay = $amount = (float) price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
1888
1889 if (!$is_multicurrency && $amountarray["amount"] != 'remain') {
1890 $amount = (float) price2num($amountarray["amount"], 'MT');
1891 }
1892
1893 if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') {
1894 $amount = (float) price2num($amountarray["multicurrency_amount"], 'MT');
1895 }
1896
1897 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
1898 $this->db->rollback();
1899 throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')');
1900 }
1901
1902 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1903 $amount = (float) price2num(-1 * abs((float) $amount), 'MT');
1904 }
1905
1906 if ($is_multicurrency) {
1907 $amounts[$id] = null;
1908 // Multicurrency
1909 $multicurrency_amounts[$id] = (float) $amount;
1910 } else {
1911 $amounts[$id] = (float) $amount;
1912 // Multicurrency
1913 $multicurrency_amounts[$id] = null;
1914 }
1915 }
1916
1917 // Creation of payment line
1918 $paymentobj = new Paiement($this->db);
1919 if (is_numeric($datepaye)) {
1920 $paymentobj->datepaye = $datepaye;
1921 } else {
1922 $paymentobj->datepaye = dol_stringtotime($datepaye);
1923 }
1924 $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id
1925 $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
1926 $paymentobj->paiementid = $paymentid;
1927 $paymentobj->paiementcode = (string) dol_getIdFromCode($this->db, (string) $paymentid, 'c_paiement', 'id', 'code', 1);
1928 $paymentobj->num_payment = $num_payment;
1929 $paymentobj->note_private = $comment;
1930 $paymentobj->ref_ext = $ref_ext;
1931 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
1932 if ($payment_id < 0) {
1933 $this->db->rollback();
1934 throw new RestException(400, 'Payment error : '.$paymentobj->error);
1935 }
1936 if (isModEnabled("bank")) {
1937 $label = '(CustomerInvoicePayment)';
1938 if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) {
1939 throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1940 }
1941 if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) {
1942 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1943 }
1944 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank);
1945 if ($result < 0) {
1946 $this->db->rollback();
1947 throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error);
1948 }
1949 }
1950
1951 $this->db->commit();
1952
1953 return $payment_id;
1954 }
1955
1972 public function putPayment($id, $num_payment = '')
1973 {
1974 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1975
1976 if (!DolibarrApiAccess::$user->hasRight('facture', 'creer')) {
1977 throw new RestException(403);
1978 }
1979 if (empty($id)) {
1980 throw new RestException(400, 'Payment ID is mandatory');
1981 }
1982
1983 $paymentobj = new Paiement($this->db);
1984 $result = $paymentobj->fetch($id);
1985
1986 if (!$result) {
1987 throw new RestException(404, 'Payment not found');
1988 }
1989
1990 if (!empty($num_payment)) {
1991 $result = $paymentobj->update_num($num_payment);
1992 if ($result < 0) {
1993 throw new RestException(500, 'Error when updating the payment num');
1994 }
1995 }
1996
1997 return [
1998 'success' => [
1999 'code' => 200,
2000 'message' => 'Payment updated'
2001 ]
2002 ];
2003 }
2004
2005 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2015 protected function _cleanObjectDatas($object)
2016 {
2017 // phpcs:enable
2018 $object = parent::_cleanObjectDatas($object);
2019
2020 unset($object->note);
2021 unset($object->address);
2022 unset($object->barcode_type);
2023 unset($object->barcode_type_code);
2024 unset($object->barcode_type_label);
2025 unset($object->barcode_type_coder);
2026 unset($object->canvas);
2027
2028 return $object;
2029 }
2030
2039 private function _validate($data)
2040 {
2041 if ($data === null) {
2042 $data = array();
2043 }
2044 $invoice = array();
2045 foreach (Invoices::$FIELDS as $field) {
2046 if (!isset($data[$field])) {
2047 throw new RestException(400, "$field field missing");
2048 }
2049 $invoice[$field] = $data[$field];
2050 }
2051 return $invoice;
2052 }
2053
2054
2068 public function getTemplateInvoice($id, $contact_list = 1)
2069 {
2070 return $this->_fetchTemplateInvoice($id, '', '', $contact_list);
2071 }
2072
2073
2099 public function indexTemplateInvoices($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0, $withLines = true)
2100 {
2101 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2102 throw new RestException(403);
2103 }
2104
2105 $obj_ret = array();
2106
2107 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
2108 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
2109
2110
2111 // If the internal user must only see his customers, force searching by him
2112 $search_sale = 0;
2113 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
2114 $search_sale = DolibarrApiAccess::$user->id;
2115 }
2116
2117 $sql = "SELECT t.rowid";
2118 $sql .= " FROM ".MAIN_DB_PREFIX."facture_rec AS t";
2119 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
2120 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture_rec_extrafields AS ef ON (ef.fk_object = t.rowid)";
2121 $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')';
2122 if ($socids) {
2123 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
2124 }
2125
2126 // Search on sale representative
2127 if ($search_sale && $search_sale != '-1') {
2128 if ($search_sale == -2) {
2129 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux AS sc WHERE sc.fk_soc = t.fk_soc)";
2130 } elseif ($search_sale > 0) {
2131 $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).")";
2132 }
2133 }
2134
2135 // Filter by status
2136 if ($status == 'active') {
2137 $sql .= " AND t.suspended = 0 AND t.frequency IS NOT NULL";
2138 }
2139 if ($status == 'suspended') {
2140 $sql .= " AND t.suspended = 1 AND t.frequency IS NOT NULL";
2141 }
2142 if ($status == 'draft') {
2143 $sql .= " AND t.frequency IS NULL";
2144 }
2145 // add sql filters
2146 if ($sqlfilters) {
2147 $errormessage = '';
2148 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
2149 if ($errormessage) {
2150 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
2151 }
2152 }
2153
2154 //this query will return total template invoices with the filters given
2155 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
2156
2157 $sql .= $this->db->order($sortfield, $sortorder);
2158 if ($limit) {
2159 if ($page < 0) {
2160 $page = 0;
2161 }
2162 $offset = $limit * $page;
2163
2164 $sql .= $this->db->plimit($limit + 1, $offset);
2165 }
2166
2167 $result = $this->db->query($sql);
2168 if ($result) {
2169 $i = 0;
2170 $num = $this->db->num_rows($result);
2171 $min = min($num, ($limit <= 0 ? $num : $limit));
2172 while ($i < $min) {
2173 $obj = $this->db->fetch_object($result);
2174 $factureRec = new FactureRec($this->db);
2175 if ($factureRec->fetch($obj->rowid) > 0) {
2176 if ($loadlinkedobjects) {
2177 // retrieve linked objects
2178 $factureRec->fetchObjectLinked();
2179 }
2180
2181 if (!$withLines) {
2182 unset($factureRec->lines);
2183 }
2184
2185 $obj_ret[] = $this->_filterObjectProperties($this->_cleanTemplateObjectDatas($factureRec), $properties);
2186 }
2187 $i++;
2188 }
2189 } else {
2190 throw new RestException(503, 'Error when retrieving recurring invoice templates: '.$this->db->lasterror());
2191 }
2192
2193 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
2194 if ($pagination_data) {
2195 $totalsResult = $this->db->query($sqlTotals);
2196 $total = $this->db->fetch_object($totalsResult)->total;
2197
2198 $tmp = $obj_ret;
2199 $obj_ret = array();
2200
2201 $obj_ret['data'] = $tmp;
2202 $obj_ret['pagination'] = array(
2203 'total' => (int) $total,
2204 'page' => $page,
2205 'page_count' => ceil((int) $total / $limit),
2206 'limit' => $limit
2207 );
2208 }
2209
2210 return $obj_ret;
2211 }
2212
2226 private function _fetchTemplateInvoice($id, $ref = '', $ref_ext = '', $contact_list = 1)
2227 {
2228 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
2229 throw new RestException(403);
2230 }
2231
2232 $result = $this->template_invoice->fetch($id, $ref, $ref_ext);
2233 if (!$result) {
2234 throw new RestException(404, 'Template invoice not found');
2235 }
2236
2237 if (!DolibarrApi::_checkAccessToResource('facturerec', $this->template_invoice->id)) {
2238 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
2239 }
2240
2241 // Add external contacts ids
2242 if ($contact_list > -1) {
2243 $tmparray = $this->template_invoice->liste_contact(-1, 'external', $contact_list);
2244 if (is_array($tmparray)) {
2245 $this->template_invoice->contacts_ids = $tmparray;
2246 }
2247 }
2248
2249 $this->template_invoice->fetchObjectLinked();
2250 return $this->_cleanTemplateObjectDatas($this->template_invoice);
2251 }
2252
2253
2254 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2262 {
2263 // phpcs:enable
2264 $object = parent::_cleanObjectDatas($object);
2265
2266 unset($object->note);
2267 unset($object->address);
2268 unset($object->barcode_type);
2269 unset($object->barcode_type_code);
2270 unset($object->barcode_type_label);
2271 unset($object->barcode_type_coder);
2272 unset($object->canvas);
2273
2274 return $object;
2275 }
2276}
$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:33
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:98
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoice lines.
Class to manage invoice templates.
putPayment($id, $num_payment='')
Update a payment.
addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0)
Adds a contact to an invoice.
indexTemplateInvoices($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false, $loadlinkedobjects=0, $withLines=true)
List template invoices.
createInvoiceFromOrder($orderid)
Create an invoice using an existing order.
markAsCreditAvailable($id)
Create a discount (credit available) for a credit note or a deposit.
getDiscount($id)
Get discount from invoice.
__construct()
Constructor.
put($id, $request_data=null)
Update invoice.
validate($id, $force_number='', $idwarehouse=0, $notrigger=0)
Validate an invoice.
getContacts($id, $type='')
Get contacts of given invoice.
getByRefExt($ref_ext, $contact_list=1)
Get properties of an invoice object by ref_ext.
_fetch($id, $ref='', $ref_ext='', $contact_list=1)
Get properties of an invoice object.
getByRef($ref, $contact_list=1)
Get properties of an invoice object by ref.
getPayments($id)
Get list of payments of a given invoice.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
post($request_data=null)
Create invoice object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false, $loadlinkedobjects=0, $withLines=true)
List invoices.
useDiscount($id, $discountid)
Add a discount line into an invoice (as an invoice line) using an existing absolute discount.
settounpaid($id)
Sets an invoice as unpaid.
getTemplateInvoice($id, $contact_list=1)
Get properties of a template invoice object.
putLine($id, $lineid, $request_data=null)
Update a line to a given invoice.
getLines($id)
Get lines of an invoice.
useCreditNote($id, $discountid)
Add an available credit note discount to payments of an existing invoice.
createInvoiceFromContract($contractid)
Create an invoice using a contract.
addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='', $ref_ext='', $accepthigherpayment=false)
Add a payment to pay partially or completely one or several invoices.
postContact($id, $contactid, $type, $source='external', $notrigger=0)
Add a contact type of given invoice.
_cleanTemplateObjectDatas($object)
Clean sensible object datas.
deleteContact($id, $contactid, $type)
Delete a contact type of given invoice.
postLine($id, $request_data=null)
Add a line to a given invoice.
_fetchTemplateInvoice($id, $ref='', $ref_ext='', $contact_list=1)
Get properties of an invoice object.
_validate($data)
Validate fields before create or update object.
addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment='', $comment='', $chqemetteur='', $chqbank='')
Add payment line to a specific invoice with the remain to pay as amount.
settopaid($id, $close_code='', $close_note='')
Sets an invoice as paid.
settodraft($id, $idwarehouse=-1)
Sets an invoice as draft.
deleteLine($id, $lineid)
Deletes a line of a given invoice.
Class to manage payments of customer invoices.
Class to manage third parties objects (customers, suppliers, prospects...)
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:449
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)
forgeSQLFromUniversalSearchCriteria
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.