22use Luracast\Restler\RestException;
24require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
25require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
39 public static $FIELDS = array(
51 private $template_invoice;
61 $this->invoice =
new Facture($this->db);
62 $this->template_invoice =
new FactureRec($this->db);
76 public function get(
$id, $contact_list = 1)
78 return $this->
_fetch(
$id,
'',
'', $contact_list);
94 public function getByRef($ref, $contact_list = 1)
96 return $this->
_fetch(0, $ref,
'', $contact_list);
114 return $this->
_fetch(0,
'', $ref_ext, $contact_list);
130 private function _fetch(
$id, $ref =
'', $ref_ext =
'', $contact_list = 1)
132 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'lire')) {
133 throw new RestException(403);
136 $result = $this->invoice->fetch(
$id, $ref, $ref_ext);
138 throw new RestException(404,
'Invoice not found');
142 $this->invoice->totalpaid = $this->invoice->getSommePaiement();
143 $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
144 $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed();
145 $this->invoice->remaintopay =
price2num($this->invoice->total_ttc - $this->invoice->totalpaid - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits,
'MT');
148 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
152 $this->invoice->getListIdAvoirFromInvoice();
155 if ($contact_list > -1) {
156 $tmparray = $this->invoice->liste_contact(-1,
'external', $contact_list);
157 if (is_array($tmparray)) {
158 $this->invoice->contacts_ids = $tmparray;
160 $tmparray = $this->invoice->liste_contact(-1,
'internal', $contact_list);
161 if (is_array($tmparray)) {
162 $this->invoice->contacts_ids = $tmparray;
166 $this->invoice->fetchObjectLinked();
169 require_once DOL_DOCUMENT_ROOT.
'/core/lib/payments.lib.php';
170 $this->invoice->online_payment_url = getOnlinePaymentUrl(0,
'invoice', $this->invoice->ref);
197 public function index($sortfield =
"t.rowid", $sortorder =
'ASC', $limit = 100, $page = 0, $thirdparty_ids =
'', $status =
'', $sqlfilters =
'', $properties =
'', $pagination_data =
false, $loadlinkedobjects = 0)
199 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'lire')) {
200 throw new RestException(403);
206 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
210 if (!DolibarrApiAccess::$user->hasRight(
'societe',
'client',
'voir') && !$socids) {
211 $search_sale = DolibarrApiAccess::$user->id;
214 $sql =
"SELECT t.rowid";
215 $sql .=
" FROM ".MAIN_DB_PREFIX.
"facture AS t";
216 $sql .=
" LEFT JOIN ".MAIN_DB_PREFIX.
"facture_extrafields AS ef ON (ef.fk_object = t.rowid)";
217 $sql .=
' WHERE t.entity IN ('.getEntity(
'invoice').
')';
219 $sql .=
" AND t.fk_soc IN (".$this->db->sanitize($socids).
")";
222 if ($search_sale && $search_sale !=
'-1') {
223 if ($search_sale == -2) {
224 $sql .=
" AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX.
"societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
225 } elseif ($search_sale > 0) {
226 $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).
")";
230 if ($status ==
'draft') {
231 $sql .=
" AND t.fk_statut IN (0)";
233 if ($status ==
'unpaid') {
234 $sql .=
" AND t.fk_statut IN (1)";
236 if ($status ==
'paid') {
237 $sql .=
" AND t.fk_statut IN (2)";
239 if ($status ==
'cancelled') {
240 $sql .=
" AND t.fk_statut IN (3)";
247 throw new RestException(400,
'Error when validating parameter sqlfilters -> '.$errormessage);
252 $sqlTotals = str_replace(
'SELECT t.rowid',
'SELECT count(t.rowid) as total', $sql);
254 $sql .= $this->db->order($sortfield, $sortorder);
259 $offset = $limit * $page;
261 $sql .= $this->db->plimit($limit + 1, $offset);
264 $result = $this->db->query($sql);
267 $num = $this->db->num_rows($result);
268 $min = min($num, ($limit <= 0 ? $num : $limit));
270 $obj = $this->db->fetch_object($result);
271 $invoice_static =
new Facture($this->db);
272 if ($invoice_static->fetch($obj->rowid) > 0) {
274 $invoice_static->totalpaid = $invoice_static->getSommePaiement();
275 $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed();
276 $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed();
277 $invoice_static->remaintopay =
price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits,
'MT');
280 $invoice_static->getListIdAvoirFromInvoice();
283 $tmparray = $invoice_static->liste_contact(-1,
'external', 1);
284 if (is_array($tmparray)) {
285 $invoice_static->contacts_ids = $tmparray;
288 if ($loadlinkedobjects) {
290 $invoice_static->fetchObjectLinked();
294 require_once DOL_DOCUMENT_ROOT.
'/core/lib/payments.lib.php';
295 $invoice_static->online_payment_url = getOnlinePaymentUrl(0,
'invoice', $invoice_static->ref);
302 throw new RestException(503,
'Error when retrieve invoice list : '.$this->db->lasterror());
306 if ($pagination_data) {
307 $totalsResult = $this->db->query($sqlTotals);
308 $total = $this->db->fetch_object($totalsResult)->total;
313 $obj_ret[
'data'] = $tmp;
314 $obj_ret[
'pagination'] = [
315 'total' => (int) $total,
317 'page_count' => ceil((
int) $total / $limit),
333 public function post($request_data =
null)
335 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
336 throw new RestException(403,
"Insuffisant rights");
339 if (!is_array($request_data)) {
340 $request_data = array();
346 foreach ($request_data as $field => $value) {
347 if ($field ===
'caller') {
349 $this->invoice->context[
'caller'] =
sanitizeVal($request_data[
'caller'],
'aZ09');
353 $this->invoice->$field = $this->
_checkValForAPI($field, $value, $this->invoice);
355 if (!array_key_exists(
'date', $request_data)) {
356 $this->invoice->date =
dol_now();
367 if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data[
"date_lim_reglement"]) ? 0 : $request_data[
"date_lim_reglement"])) < 0) {
368 throw new RestException(500,
"Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors));
370 return ((
int) $this->invoice->id);
389 require_once DOL_DOCUMENT_ROOT.
'/commande/class/commande.class.php';
391 if (!DolibarrApiAccess::$user->hasRight(
'commande',
'lire')) {
392 throw new RestException(403);
394 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
395 throw new RestException(403);
397 if (empty($orderid)) {
398 throw new RestException(400,
'Order ID is mandatory');
401 throw new RestException(403,
'Access not allowed on order for login '.DolibarrApiAccess::$user->login);
405 $result = $order->fetch($orderid);
407 throw new RestException(404,
'Order not found');
410 $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user);
412 throw new RestException(405, $this->invoice->error);
414 $this->invoice->fetchObjectLinked();
433 require_once DOL_DOCUMENT_ROOT.
'/contrat/class/contrat.class.php';
435 if (!DolibarrApiAccess::$user->hasRight(
'contrat',
'lire')) {
436 throw new RestException(403);
438 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
439 throw new RestException(403);
441 if (empty($contractid)) {
442 throw new RestException(400,
'Contract ID is mandatory');
445 $contract =
new Contrat($this->db);
446 $result = $contract->fetch($contractid);
448 throw new RestException(404,
'Contract not found');
451 $result = $this->invoice->createFromContract($contract, DolibarrApiAccess::$user);
453 throw new RestException(405, $this->invoice->error);
455 $this->invoice->fetchObjectLinked();
471 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'lire')) {
472 throw new RestException(403);
475 $result = $this->invoice->fetch(
$id);
477 throw new RestException(404,
'Invoice not found');
481 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
483 $this->invoice->getLinesArray();
485 foreach ($this->invoice->lines as $line) {
509 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
510 throw new RestException(403);
513 $result = $this->invoice->fetch(
$id);
515 throw new RestException(404,
'Invoice not found');
519 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
522 $request_data = (object) $request_data;
524 $request_data->desc =
sanitizeVal($request_data->desc,
'restricthtml');
525 $request_data->label =
sanitizeVal($request_data->label);
527 $updateRes = $this->invoice->updateline(
530 $request_data->subprice,
532 $request_data->remise_percent,
533 $request_data->date_start,
534 $request_data->date_end,
535 $request_data->tva_tx,
536 $request_data->localtax1_tx,
537 $request_data->localtax2_tx,
538 $request_data->price_base_type ? $request_data->price_base_type :
'HT',
539 $request_data->info_bits,
540 $request_data->product_type,
541 $request_data->fk_parent_line,
543 $request_data->fk_fournprice,
544 $request_data->pa_ht,
545 $request_data->label,
546 $request_data->special_code,
547 $request_data->array_options,
548 $request_data->situation_percent,
549 $request_data->fk_unit,
550 $request_data->multicurrency_subprice,
552 $request_data->ref_ext,
556 if ($updateRes > 0) {
557 $result = $this->
get(
$id);
558 unset($result->line);
561 throw new RestException(304, $this->invoice->error);
582 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
583 throw new RestException(403);
586 $result = $this->invoice->fetch(
$id);
589 throw new RestException(404,
'Invoice not found');
592 if (!in_array($type, array(
'BILLING',
'SHIPPING',
'CUSTOMER'),
true)) {
593 throw new RestException(500,
'Availables types: BILLING, SHIPPING OR CUSTOMER');
597 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
600 $result = $this->invoice->add_contact($contactid, $type,
'external');
603 throw new RestException(500,
'Error when added the contact');
609 'message' =>
'Contact linked to the invoice'
630 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
631 throw new RestException(403);
634 $result = $this->invoice->fetch(
$id);
637 throw new RestException(404,
'Invoice not found');
641 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
644 $contacts = $this->invoice->liste_contact();
646 foreach ($contacts as $contact) {
647 if ($contact[
'id'] == $contactid && $contact[
'code'] == $type) {
648 $result = $this->invoice->delete_contact($contact[
'rowid']);
651 throw new RestException(500,
'Error when deleted the contact');
675 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
676 throw new RestException(403);
678 if (empty($lineid)) {
679 throw new RestException(400,
'Line ID is mandatory');
683 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
686 $result = $this->invoice->fetch(
$id);
688 throw new RestException(404,
'Invoice not found');
691 $updateRes = $this->invoice->deleteLine($lineid,
$id);
692 if ($updateRes > 0) {
693 return $this->
get(
$id);
695 throw new RestException(405, $this->invoice->error);
708 public function put(
$id, $request_data =
null)
710 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
711 throw new RestException(403);
714 $result = $this->invoice->fetch(
$id);
716 throw new RestException(404,
'Invoice not found');
720 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
723 foreach ($request_data as $field => $value) {
724 if ($field ==
'id') {
727 if ($field ===
'caller') {
729 $this->invoice->context[
'caller'] =
sanitizeVal($request_data[
'caller'],
'aZ09');
732 if ($field ==
'array_options' && is_array($value)) {
733 foreach ($value as $index => $val) {
734 $this->invoice->array_options[$index] = $this->
_checkValForAPI($field, $val, $this->invoice);
739 $this->invoice->$field = $this->
_checkValForAPI($field, $value, $this->invoice);
742 if ($field ==
'cond_reglement_id') {
743 $this->invoice->date_lim_reglement = $this->invoice->calculate_date_lim_reglement();
748 if (!empty($this->invoice->fk_account)) {
749 if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) {
750 throw new RestException(400, $this->invoice->error);
754 if ($this->invoice->update(DolibarrApiAccess::$user) > 0) {
755 return $this->
get(
$id);
757 throw new RestException(500, $this->invoice->error);
769 public function delete(
$id)
771 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'supprimer')) {
772 throw new RestException(403);
774 $result = $this->invoice->fetch(
$id);
776 throw new RestException(404,
'Invoice not found');
780 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
783 $result = $this->invoice->delete(DolibarrApiAccess::$user);
785 throw new RestException(500,
'Error when deleting invoice');
786 } elseif ($result == 0) {
787 throw new RestException(403,
'Invoice not erasable');
793 'message' =>
'Invoice deleted'
825 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
826 throw new RestException(403);
829 $result = $this->invoice->fetch(
$id);
831 throw new RestException(404,
'Invoice not found');
835 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
838 $request_data = (object) $request_data;
840 $request_data->desc =
sanitizeVal($request_data->desc,
'restricthtml');
841 $request_data->label =
sanitizeVal($request_data->label);
844 if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) {
845 $request_data->fk_parent_line = 0;
849 $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);
850 $pa_ht = $marginInfos[0];
852 $updateRes = $this->invoice->addline(
854 $request_data->subprice,
856 $request_data->tva_tx,
857 $request_data->localtax1_tx,
858 $request_data->localtax2_tx,
859 $request_data->fk_product,
860 $request_data->remise_percent,
861 $request_data->date_start,
862 $request_data->date_end,
863 $request_data->fk_code_ventilation,
864 $request_data->info_bits,
865 $request_data->fk_remise_except,
866 $request_data->price_base_type ? $request_data->price_base_type :
'HT',
867 $request_data->subprice,
868 $request_data->product_type,
870 $request_data->special_code,
871 $request_data->origin,
872 $request_data->origin_id,
873 $request_data->fk_parent_line,
874 empty($request_data->fk_fournprice) ? null : $request_data->fk_fournprice,
876 $request_data->label,
877 $request_data->array_options,
878 $request_data->situation_percent,
879 $request_data->fk_prev_id,
880 $request_data->fk_unit,
882 $request_data->ref_ext
885 if ($updateRes < 0) {
886 throw new RestException(400,
'Unable to insert the new line. Check your inputs. '.$this->invoice->error);
910 public function addContact(
$id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
912 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
913 throw new RestException(403);
915 $result = $this->invoice->fetch(
$id);
917 throw new RestException(404,
'Invoice not found');
921 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
924 $result = $this->invoice->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
926 throw new RestException(500,
'Error : '.$this->invoice->error);
929 $result = $this->invoice->fetch(
$id);
931 throw new RestException(404,
'Invoice not found');
935 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
959 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
960 throw new RestException(403);
962 $result = $this->invoice->fetch(
$id);
964 throw new RestException(404,
'Invoice not found');
968 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
971 $result = $this->invoice->setDraft(DolibarrApiAccess::$user, $idwarehouse);
973 throw new RestException(304,
'Nothing done.');
976 throw new RestException(500,
'Error : '.$this->invoice->error);
979 $result = $this->invoice->fetch(
$id);
981 throw new RestException(404,
'Invoice not found');
1005 public function validate(
$id, $force_number =
'', $idwarehouse = 0, $notrigger = 0)
1007 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1008 throw new RestException(403);
1010 $result = $this->invoice->fetch(
$id);
1012 throw new RestException(404,
'Invoice not found');
1016 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1019 $result = $this->invoice->validate(DolibarrApiAccess::$user, $force_number, $idwarehouse, $notrigger);
1021 throw new RestException(304,
'Error nothing done. May be object is already validated');
1024 throw new RestException(500,
'Error when validating Invoice: '.$this->invoice->error);
1027 $result = $this->invoice->fetch(
$id);
1029 throw new RestException(404,
'Invoice not found');
1033 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1037 require_once DOL_DOCUMENT_ROOT.
'/core/lib/payments.lib.php';
1038 $this->invoice->online_payment_url = getOnlinePaymentUrl(0,
'invoice', $this->invoice->ref);
1060 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1061 throw new RestException(403);
1063 $result = $this->invoice->fetch(
$id);
1065 throw new RestException(404,
'Invoice not found');
1069 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1072 $result = $this->invoice->setPaid(DolibarrApiAccess::$user, $close_code, $close_note);
1074 throw new RestException(304,
'Error nothing done. May be object is already validated');
1077 throw new RestException(500,
'Error : '.$this->invoice->error);
1081 $result = $this->invoice->fetch(
$id);
1083 throw new RestException(404,
'Invoice not found');
1087 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1109 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1110 throw new RestException(403);
1112 $result = $this->invoice->fetch(
$id);
1114 throw new RestException(404,
'Invoice not found');
1118 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1121 $result = $this->invoice->setUnpaid(DolibarrApiAccess::$user);
1123 throw new RestException(304,
'Nothing done');
1126 throw new RestException(500,
'Error : '.$this->invoice->error);
1130 $result = $this->invoice->fetch(
$id);
1132 throw new RestException(404,
'Invoice not found');
1136 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1152 require_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
1154 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'lire')) {
1155 throw new RestException(403);
1158 $result = $this->invoice->fetch(
$id);
1160 throw new RestException(404,
'Invoice not found');
1164 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1168 $result = $discountcheck->fetch(0, $this->invoice->id);
1171 throw new RestException(404,
'Discount not found');
1174 throw new RestException(500, $discountcheck->error);
1177 return parent::_cleanObjectDatas($discountcheck);
1195 require_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
1197 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1198 throw new RestException(403);
1201 $result = $this->invoice->fetch(
$id);
1203 throw new RestException(404,
'Invoice not found');
1207 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1210 if ($this->invoice->paye) {
1211 throw new RestException(500,
'Alreay paid');
1214 $this->invoice->fetch(
$id);
1215 $this->invoice->fetch_thirdparty();
1219 $result = $discountcheck->fetch(0, $this->invoice->id);
1231 $amount_ht = $amount_tva = $amount_ttc = array();
1232 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1234 @phan-var-force array<string,float> $amount_ht
1235 @phan-var-force array<string,float> $amount_tva
1236 @phan-var-force array<string,float> $amount_ttc
1237 @phan-var-force array<string,float> $multicurrency_amount_ht
1238 @phan-var-force array<string,float> $multicurrency_amount_tva
1239 @phan-var-force array<string,float> $multicurrency_amount_ttc
1244 foreach ($this->invoice->lines as $line) {
1245 if ($line->product_type < 9 && $line->total_ht != 0) {
1246 if (!array_key_exists($line->tva_tx, $amount_ht)) {
1247 $amount_ht[$line->tva_tx] = 0.0;
1248 $amount_tva[$line->tva_tx] = 0.0;
1249 $amount_ttc[$line->tva_tx] = 0.0;
1250 $multicurrency_amount_ht[$line->tva_tx] = 0.0;
1251 $multicurrency_amount_tva[$line->tva_tx] = 0.0;
1252 $multicurrency_amount_ttc[$line->tva_tx] = 0.0;
1255 $amount_ht[$line->tva_tx] += $line->total_ht;
1256 $amount_tva[$line->tva_tx] += $line->total_tva;
1257 $amount_ttc[$line->tva_tx] += $line->total_ttc;
1258 $multicurrency_amount_ht[$line->tva_tx] += $line->multicurrency_total_ht;
1259 $multicurrency_amount_tva[$line->tva_tx] += $line->multicurrency_total_tva;
1260 $multicurrency_amount_ttc[$line->tva_tx] += $line->multicurrency_total_ttc;
1268 $discount->description =
'(CREDIT_NOTE)';
1270 $discount->description =
'(DEPOSIT)';
1272 $discount->description =
'(EXCESS RECEIVED)';
1274 throw new RestException(500,
'Cant convert to reduc an Invoice of this type');
1277 $discount->fk_soc = $this->invoice->socid;
1278 $discount->socid = $this->invoice->socid;
1279 $discount->fk_facture_source = $this->invoice->id;
1287 $sql =
'SELECT SUM(pf.amount) as total_payments';
1288 $sql .=
' FROM '.MAIN_DB_PREFIX.
'paiement_facture as pf, '.MAIN_DB_PREFIX.
'paiement as p';
1289 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as c ON p.fk_paiement = c.id';
1290 $sql .=
' WHERE pf.fk_facture = '.((int) $this->invoice->id);
1291 $sql .=
' AND pf.fk_paiement = p.rowid';
1292 $sql .=
' AND p.entity IN ('.getEntity(
'invoice').
')';
1293 $resql = $this->db->query($sql);
1298 $res = $this->db->fetch_object($resql);
1299 $total_payments = $res->total_payments;
1302 $total_creditnote_and_deposit = 0;
1303 $sql =
"SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1304 $sql .=
" re.description, re.fk_facture_source";
1305 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe_remise_except as re";
1306 $sql .=
" WHERE fk_facture = ".((int) $this->invoice->id);
1307 $resql = $this->db->query($sql);
1308 if (!empty($resql)) {
1309 while ($obj = $this->db->fetch_object($resql)) {
1310 $total_creditnote_and_deposit += $obj->amount_ttc;
1316 $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc;
1317 $discount->amount_tva = 0;
1318 $discount->tva_tx = 0;
1320 $result = $discount->create(DolibarrApiAccess::$user);
1326 foreach ($amount_ht as $tva_tx => $xxx) {
1327 $discount->amount_ht = abs($amount_ht[$tva_tx]);
1328 $discount->amount_tva = abs($amount_tva[$tva_tx]);
1329 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
1330 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
1331 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
1332 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
1333 $discount->tva_tx = abs((
float) $tva_tx);
1335 $result = $discount->create(DolibarrApiAccess::$user);
1343 if (empty($error)) {
1346 $result = $this->invoice->setPaid(DolibarrApiAccess::$user);
1348 $this->db->commit();
1350 $this->db->rollback();
1351 throw new RestException(500,
'Could not set paid');
1354 $this->db->commit();
1357 $this->db->rollback();
1358 throw new RestException(500,
'Discount creation error');
1383 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1384 throw new RestException(403);
1387 throw new RestException(400,
'Invoice ID is mandatory');
1389 if (empty($discountid)) {
1390 throw new RestException(400,
'Discount ID is mandatory');
1394 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1397 $result = $this->invoice->fetch(
$id);
1399 throw new RestException(404,
'Invoice not found');
1402 $result = $this->invoice->insert_discount($discountid);
1404 throw new RestException(405, $this->invoice->error);
1428 require_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
1430 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1431 throw new RestException(403);
1434 throw new RestException(400,
'Invoice ID is mandatory');
1436 if (empty($discountid)) {
1437 throw new RestException(400,
'Credit ID is mandatory');
1441 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1444 $result = $discount->fetch($discountid);
1446 throw new RestException(404,
'Credit not found');
1449 $result = $discount->link_to_invoice(0,
$id);
1451 throw new RestException(405, $discount->error);
1474 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'lire')) {
1475 throw new RestException(403);
1478 throw new RestException(400,
'Invoice ID is mandatory');
1482 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1485 $result = $this->invoice->fetch(
$id);
1487 throw new RestException(404,
'Invoice not found');
1490 $result = $this->invoice->getListOfPayments();
1491 if (!is_array($result) && $result < 0) {
1492 throw new RestException(405, $this->invoice->error);
1520 public function addPayment(
$id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment =
'', $comment =
'', $chqemetteur =
'', $chqbank =
'')
1522 require_once DOL_DOCUMENT_ROOT.
'/compta/paiement/class/paiement.class.php';
1524 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1525 throw new RestException(403);
1528 throw new RestException(400,
'Invoice ID is mandatory');
1532 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1535 if (isModEnabled(
"bank")) {
1536 if (empty($accountid)) {
1537 throw new RestException(400,
'Account ID is mandatory');
1541 if (empty($paymentid)) {
1542 throw new RestException(400,
'Payment ID or Payment Code is mandatory');
1546 $result = $this->invoice->fetch(
$id);
1548 throw new RestException(404,
'Invoice not found');
1552 $totalpaid = $this->invoice->getSommePaiement();
1553 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed();
1554 $totaldeposits = $this->invoice->getSumDepositsUsed();
1555 $resteapayer =
price2num($this->invoice->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits,
'MT');
1560 $multicurrency_amounts = array();
1564 $resteapayer =
price2num($resteapayer,
'MT');
1565 $amounts[
$id] = (float)
price2num(-1 * abs((
float) $resteapayer),
'MT');
1567 $newvalue =
price2num($this->invoice->multicurrency_total_ttc,
'MT');
1568 $multicurrency_amounts[
$id] = (float)
price2num(-1 * (
float) $newvalue,
'MT');
1570 $resteapayer =
price2num($resteapayer,
'MT');
1571 $amounts[
$id] = (float) $resteapayer;
1573 $newvalue =
price2num($this->invoice->multicurrency_total_ttc,
'MT');
1574 $multicurrency_amounts[
$id] = (float) $newvalue;
1578 $paymentobj =
new Paiement($this->db);
1579 if (is_numeric($datepaye)) {
1580 $paymentobj->datepaye = $datepaye;
1584 $paymentobj->amounts = $amounts;
1585 $paymentobj->multicurrency_amounts = $multicurrency_amounts;
1586 $paymentobj->paiementid = $paymentid;
1587 $paymentobj->paiementcode = (string)
dol_getIdFromCode($this->db, (
string) $paymentid,
'c_paiement',
'id',
'code', 1);
1588 $paymentobj->num_payment = $num_payment;
1589 $paymentobj->note_private = $comment;
1591 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices ==
'yes' ? 1 : 0));
1592 if ($payment_id < 0) {
1593 $this->db->rollback();
1594 throw new RestException(400,
'Payment error : '.$paymentobj->error);
1597 if (isModEnabled(
"bank")) {
1598 $label =
'(CustomerInvoicePayment)';
1600 if ($paymentobj->paiementcode ==
'CHQ' && empty($chqemetteur)) {
1601 throw new RestException(400,
'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1604 $label =
'(CustomerInvoicePaymentBack)';
1606 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user,
'payment', $label, $accountid, $chqemetteur, $chqbank);
1608 $this->db->rollback();
1609 throw new RestException(400,
'Add payment to bank error : '.$paymentobj->error);
1613 $this->db->commit();
1646 public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment =
'', $comment =
'', $chqemetteur =
'', $chqbank =
'', $ref_ext =
'', $accepthigherpayment =
false)
1648 require_once DOL_DOCUMENT_ROOT.
'/compta/paiement/class/paiement.class.php';
1650 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1651 throw new RestException(403);
1653 foreach ($arrayofamounts as
$id => $amount) {
1655 throw new RestException(400,
'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}');
1658 throw new RestException(403,
'Access not allowed on invoice ID '.
$id.
' for login '.DolibarrApiAccess::$user->login);
1662 if (isModEnabled(
"bank")) {
1663 if (empty($accountid)) {
1664 throw new RestException(400,
'Account ID is mandatory');
1667 if (empty($paymentid)) {
1668 throw new RestException(400,
'Payment ID or Payment Code is mandatory');
1674 $multicurrency_amounts = array();
1677 foreach ($arrayofamounts as
$id => $amountarray) {
1678 $result = $this->invoice->fetch((
int)
$id);
1680 $this->db->rollback();
1681 throw new RestException(404,
'Invoice ID '.
$id.
' not found');
1684 if (($amountarray[
"amount"] ==
"remain" || $amountarray[
"amount"] > 0) && ($amountarray[
"multicurrency_amount"] ==
"remain" || $amountarray[
"multicurrency_amount"] > 0)) {
1685 $this->db->rollback();
1686 throw new RestException(400,
'Payment in both currency '.
$id.
' ( amount: '.$amountarray[
"amount"].
', multicurrency_amount: '.$amountarray[
"multicurrency_amount"].
')');
1689 $is_multicurrency = 0;
1690 $total_ttc = $this->invoice->total_ttc;
1692 if ($amountarray[
"multicurrency_amount"] > 0 || $amountarray[
"multicurrency_amount"] ==
"remain") {
1693 $is_multicurrency = 1;
1694 $total_ttc = $this->invoice->multicurrency_total_ttc;
1698 $totalpaid = $this->invoice->getSommePaiement($is_multicurrency);
1699 $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency);
1700 $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency);
1701 $remainstopay = $amount = (float)
price2num($total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits,
'MT');
1703 if (!$is_multicurrency && $amountarray[
"amount"] !=
'remain') {
1704 $amount = (float)
price2num($amountarray[
"amount"],
'MT');
1707 if ($is_multicurrency && $amountarray[
"multicurrency_amount"] !=
'remain') {
1708 $amount = (float)
price2num($amountarray[
"multicurrency_amount"],
'MT');
1711 if (abs($amount) > abs($remainstopay) && !$accepthigherpayment) {
1712 $this->db->rollback();
1713 throw new RestException(400,
'Payment amount on invoice ID '.
$id.
' ('.$amount.
') is higher than remain to pay ('.$remainstopay.
')');
1717 $amount = (float)
price2num(-1 * abs((
float) $amount),
'MT');
1720 if ($is_multicurrency) {
1721 $amounts[
$id] =
null;
1723 $multicurrency_amounts[
$id] = (float) $amount;
1725 $amounts[
$id] = (float) $amount;
1727 $multicurrency_amounts[
$id] =
null;
1732 $paymentobj =
new Paiement($this->db);
1733 if (is_numeric($datepaye)) {
1734 $paymentobj->datepaye = $datepaye;
1738 $paymentobj->amounts = $amounts;
1739 $paymentobj->multicurrency_amounts = $multicurrency_amounts;
1740 $paymentobj->paiementid = $paymentid;
1741 $paymentobj->paiementcode = (string)
dol_getIdFromCode($this->db, (
string) $paymentid,
'c_paiement',
'id',
'code', 1);
1742 $paymentobj->num_payment = $num_payment;
1743 $paymentobj->note_private = $comment;
1744 $paymentobj->ref_ext = $ref_ext;
1745 $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices ==
'yes' ? 1 : 0));
1746 if ($payment_id < 0) {
1747 $this->db->rollback();
1748 throw new RestException(400,
'Payment error : '.$paymentobj->error);
1750 if (isModEnabled(
"bank")) {
1751 $label =
'(CustomerInvoicePayment)';
1752 if ($paymentobj->paiementcode ==
'CHQ' && empty($chqemetteur)) {
1753 throw new RestException(400,
'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode);
1756 $label =
'(CustomerInvoicePaymentBack)';
1758 $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user,
'payment', $label, $accountid, $chqemetteur, $chqbank);
1760 $this->db->rollback();
1761 throw new RestException(400,
'Add payment to bank error : '.$paymentobj->error);
1765 $this->db->commit();
1788 require_once DOL_DOCUMENT_ROOT.
'/compta/paiement/class/paiement.class.php';
1790 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'creer')) {
1791 throw new RestException(403);
1794 throw new RestException(400,
'Payment ID is mandatory');
1797 $paymentobj =
new Paiement($this->db);
1798 $result = $paymentobj->fetch(
$id);
1801 throw new RestException(404,
'Payment not found');
1804 if (!empty($num_payment)) {
1805 $result = $paymentobj->update_num($num_payment);
1807 throw new RestException(500,
'Error when updating the payment num');
1814 'message' =>
'Payment updated'
1834 unset(
$object->barcode_type_code);
1835 unset(
$object->barcode_type_label);
1836 unset(
$object->barcode_type_coder);
1852 if ($data ===
null) {
1856 foreach (Invoices::$FIELDS as $field) {
1857 if (!isset($data[$field])) {
1858 throw new RestException(400,
"$field field missing");
1860 $invoice[$field] = $data[$field];
1899 if (!DolibarrApiAccess::$user->hasRight(
'facture',
'lire')) {
1900 throw new RestException(403);
1903 $result = $this->template_invoice->fetch(
$id, $ref, $ref_ext);
1905 throw new RestException(404,
'Template invoice not found');
1909 throw new RestException(403,
'Access not allowed for login '.DolibarrApiAccess::$user->login);
1913 if ($contact_list > -1) {
1914 $tmparray = $this->template_invoice->liste_contact(-1,
'external', $contact_list);
1915 if (is_array($tmparray)) {
1916 $this->template_invoice->contacts_ids = $tmparray;
1920 $this->template_invoice->fetchObjectLinked();
1940 unset(
$object->barcode_type_code);
1941 unset(
$object->barcode_type_label);
1942 unset(
$object->barcode_type_coder);
$id
Support class for third parties, contacts, members, users or resources.
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Class to manage customers orders.
Class to manage absolute discounts.
_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.
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.
postContact($id, $contactid, $type)
Add a contact type of given invoice.
putPayment($id, $num_payment='')
Update a payment.
addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0)
Adds a contact to an invoice.
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.
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.
post($request_data=null)
Create invoice object.
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.
_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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $status='', $sqlfilters='', $properties='', $pagination_data=false, $loadlinkedobjects=0)
List invoices.
deleteLine($id, $lineid)
Deletes a line of a given invoice.
Class to manage payments of customer invoices.
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...
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_now($mode='auto')
Return date for now.
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.
getMarginInfos($pv_ht, $remise_percent, $tva_tx, $localtax1_tx, $localtax2_tx, $fk_pa, $pa_ht)
Return an array with margins information of a line.