42require
'../../main.inc.php';
43require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
44require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
45require_once DOL_DOCUMENT_ROOT.
'/compta/bank/class/account.class.php';
46require_once DOL_DOCUMENT_ROOT.
'/compta/paiement/class/paiement.class.php';
47require_once DOL_DOCUMENT_ROOT.
'/core/modules/facture/modules_facture.php';
48require_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
49require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
50require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formfile.class.php';
51require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formother.class.php';
52require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
53require_once DOL_DOCUMENT_ROOT.
'/core/lib/invoice.lib.php';
54require_once DOL_DOCUMENT_ROOT.
'/core/lib/functions2.lib.php';
55require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
56if (isModEnabled(
'commande')) {
57 require_once DOL_DOCUMENT_ROOT.
'/commande/class/commande.class.php';
59if (isModEnabled(
'project')) {
60 require_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
61 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formprojet.class.php';
63require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
65if (isModEnabled(
'variants')) {
66 require_once DOL_DOCUMENT_ROOT.
'/variants/class/ProductCombination.class.php';
68if (isModEnabled(
'accounting')) {
69 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingjournal.class.php';
73$langs->loadLangs(array(
'bills',
'companies',
'compta',
'products',
'banks',
'main',
'withdrawals'));
74if (isModEnabled(
'incoterm')) {
75 $langs->load(
'incoterm');
77if (isModEnabled(
'margin')) {
78 $langs->load(
'margins');
84$socid =
GETPOST(
'socid',
'int');
85$action =
GETPOST(
'action',
'aZ09');
86$confirm =
GETPOST(
'confirm',
'alpha');
87$cancel =
GETPOST(
'cancel',
'alpha');
88$backtopage =
GETPOST(
'backtopage',
'alpha');
89$lineid =
GETPOST(
'lineid',
'int');
90$userid =
GETPOST(
'userid',
'int');
91$search_ref =
GETPOST(
'sf_ref',
'alpha') ?
GETPOST(
'sf_ref',
'alpha') :
GETPOST(
'search_ref',
'alpha');
92$search_societe =
GETPOST(
'search_societe',
'alpha');
93$search_montant_ht =
GETPOST(
'search_montant_ht',
'alpha');
94$search_montant_ttc =
GETPOST(
'search_montant_ttc',
'alpha');
95$origin =
GETPOST(
'origin',
'alpha');
97$fac_rec =
GETPOST(
'fac_rec',
'int');
98$facid =
GETPOST(
'facid',
'int');
99$ref_client =
GETPOST(
'ref_client',
'int');
100$rank = (
GETPOST(
'rank',
'int') > 0) ?
GETPOST(
'rank',
'int') : -1;
101$projectid = (
GETPOST(
'projectid',
'int') ?
GETPOST(
'projectid',
'int') : 0);
102$selectedLines =
GETPOST(
'toselect',
'array');
112$usehm = (
getDolGlobalString(
'MAIN_USE_HOURMIN_IN_DATE_RANGE') ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
118$extrafields->fetch_name_optionals_label($object->table_element);
121if ($id > 0 || !empty($ref)) {
122 if ($action !=
'add') {
124 $fetch_situation =
false;
126 $fetch_situation =
true;
128 $ret = $object->fetch($id, $ref,
'',
'', $fetch_situation);
129 if ($ret > 0 && isset($object->fk_project)) {
130 $ret = $object->fetch_project();
136$hookmanager->initHooks(array(
'invoicecard',
'globalcard'));
139$usercanread = $user->hasRight(
"facture",
"lire");
140$usercancreate = $user->hasRight(
"facture",
"creer");
141$usercanissuepayment = $user->hasRight(
"facture",
"paiement");
142$usercandelete = $user->hasRight(
"facture",
"supprimer");
143$usercancreatecontract = $user->hasRight(
"contrat",
"creer");
146$usercanvalidate = ((!
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->facture->invoice_advance->validate)));
148$usercanreopen = ((!
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->facture->invoice_advance->reopen)));
150 $usercanreopen =
false;
152$usercanunvalidate = ((!
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !empty($usercancreate)) || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->facture->invoice_advance->unvalidate)));
154$usermustrespectpricemin = ((
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && empty($user->rights->produit->ignore_price_min_advance)) || !
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'));
155$usercancreatemargin = (!empty($user->rights->margins->creer) ? $user->rights->margins->creer : 0);
156$usercanreadallmargin = (!empty($user->rights->margins->liretous) ? $user->rights->margins->liretous : 0);
157$usercancreatewithdrarequest = (!empty($user->rights->prelevement->bons->creer) ? $user->rights->prelevement->bons->creer : 0);
159$permissionnote = $usercancreate;
160$permissiondellink = $usercancreate;
161$permissiontoedit = $usercancreate;
162$permissiontoadd = $usercancreate;
165$retainedWarrantyInvoiceAvailableType = array();
167 $retainedWarrantyInvoiceAvailableType = explode(
'+',
getDolGlobalString(
'INVOICE_USE_RETAINED_WARRANTY'));
172 $socid = $user->socid;
176$result =
restrictedArea($user,
'facture', $object->id,
'',
'',
'fk_soc',
'rowid', $isdraft);
183$parameters = array(
'socid' => $socid);
184$reshook = $hookmanager->executeHooks(
'doActions', $parameters, $object, $action);
189if (empty($reshook)) {
190 $backurlforlist = DOL_URL_ROOT.
'/compta/facture/list.php';
192 if (empty($backtopage) || ($cancel && empty($id))) {
193 if (empty($backtopage) || ($cancel && strpos($backtopage,
'__ID__'))) {
194 if (empty($id) && (($action !=
'add' && $action !=
'create') || $cancel)) {
195 $backtopage = $backurlforlist;
197 $backtopage = DOL_URL_ROOT.
'/compta/facture/card.php?id='.((!empty($id) && $id > 0) ? $id :
'__ID__');
203 if (!empty($backtopageforcancel)) {
204 header(
"Location: ".$backtopageforcancel);
206 } elseif (!empty($backtopage)) {
207 header(
"Location: ".$backtopage);
213 include DOL_DOCUMENT_ROOT.
'/core/actions_setnotes.inc.php';
215 include DOL_DOCUMENT_ROOT.
'/core/actions_dellink.inc.php';
217 include DOL_DOCUMENT_ROOT.
'/core/actions_lineupdown.inc.php';
220 if ($action ==
'confirm_clone' && $confirm ==
'yes' && $permissiontoadd) {
224 $objectutil->socid = $socid;
225 $result = $objectutil->createFromClone($user, $id);
227 header(
"Location: ".$_SERVER[
'PHP_SELF'].
'?facid='.$result);
230 $langs->load(
"errors");
234 } elseif ($action ==
'reopen' && $usercanreopen) {
235 $result = $object->fetch($id);
238 $result = $object->setUnpaid($user);
240 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
246 } elseif ($action ==
'confirm_delete' && $confirm ==
'yes') {
248 $result = $object->fetch($id);
249 $object->fetch_thirdparty();
251 $idwarehouse =
GETPOST(
'idwarehouse');
253 $qualified_for_stock_change = 0;
255 $qualified_for_stock_change = $object->hasProductsOrServices(2);
257 $qualified_for_stock_change = $object->hasProductsOrServices(1);
260 $isErasable = $object->is_erasable();
262 if (($usercandelete && $isErasable > 0)
263 || ($usercancreate && $isErasable == 1)) {
264 $result = $object->delete($user, 0, $idwarehouse);
266 header(
'Location: '.DOL_URL_ROOT.
'/compta/facture/list.php?restore_lastsearch_values=1');
273 } elseif ($action ==
'confirm_deleteline' && $confirm ==
'yes' && $usercancreate) {
276 $object->fetch_thirdparty();
278 $result = $object->deleteline(
GETPOST(
'lineid',
'int'));
281 $object->line_order(
true);
283 $outputlangs = $langs;
289 $newlang = $object->thirdparty->default_lang;
291 if (!empty($newlang)) {
293 $outputlangs->setDefaultLang($newlang);
294 $outputlangs->load(
'products');
297 $ret = $object->fetch($id);
298 $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
301 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
308 } elseif ($action ==
'unlinkdiscount' && $usercancreate) {
311 $result = $discount->fetch(
GETPOSTINT(
"discountid"));
312 $discount->unlink_invoice();
313 } elseif ($action ==
'valid' && $usercancreate) {
317 if ((preg_match(
'/^[\(]?PROV/i', $object->ref) || empty($object->ref)) &&
324 $last_of_type = $object->willBeLastOfSameType(
true);
325 if (empty($object->date_validation) && !$last_of_type[0]) {
334 if ($object->total_ht > 0) {
335 setEventMessages($langs->trans(
"ErrorInvoiceAvoirMustBeNegative"),
null,
'errors');
344 setEventMessages($langs->trans(
"ErrorInvoiceOfThisTypeMustBePositive"),
null,
'errors');
353 $array_of_total_ht_per_vat_rate = array();
354 $array_of_total_ht_devise_per_vat_rate = array();
355 foreach ($object->lines as $line) {
357 $vat_src_code_for_line =
'';
358 if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line])) {
359 $array_of_total_ht_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line] = 0;
361 if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line])) {
362 $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line] = 0;
364 $array_of_total_ht_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line] += $line->total_ht;
365 $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line] += $line->multicurrency_total_ht;
369 foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) {
370 $tmp_total_ht =
price2num($array_of_total_ht_per_vat_rate[$vatrate]);
371 $tmp_total_ht_devise =
price2num($array_of_total_ht_devise_per_vat_rate[$vatrate]);
373 if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) {
374 if ($object->type == $object::TYPE_DEPOSIT) {
375 $langs->load(
"errors");
377 setEventMessages($langs->trans(
"ErrorLinesCantBeNegativeOnDeposits"),
null,
'errors');
381 $tmpvatratetoshow = explode(
'_', $vatrate);
382 $tmpvatratetoshow[0] = round($tmpvatratetoshow[0], 2);
384 if ($tmpvatratetoshow[0] != 0) {
385 $langs->load(
"errors");
386 setEventMessages($langs->trans(
"ErrorLinesCantBeNegativeForOneVATRate", $tmpvatratetoshow[0]),
null,
'errors');
394 } elseif ($action ==
'classin' && $usercancreate) {
396 $object->setProject(
GETPOST(
'projectid',
'int'));
397 } elseif ($action ==
'setmode' && $usercancreate) {
399 $result = $object->setPaymentMethods(
GETPOST(
'mode_reglement_id',
'int'));
403 } elseif ($action ==
'setretainedwarrantyconditions' && $user->hasRight(
'facture',
'creer')) {
405 $object->retained_warranty_fk_cond_reglement = 0;
406 $result = $object->setRetainedWarrantyPaymentTerms(
GETPOST(
'retained_warranty_fk_cond_reglement',
'int'));
411 $old_rw_date_lim_reglement = $object->retained_warranty_date_limit;
412 $new_rw_date_lim_reglement = $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
413 if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) {
414 $object->retained_warranty_date_limit = $new_rw_date_lim_reglement;
416 if ($object->retained_warranty_date_limit < $object->date) {
417 $object->retained_warranty_date_limit = $object->date;
419 $result = $object->update($user);
423 } elseif ($action ==
'setretainedwarranty' && $user->hasRight(
'facture',
'creer')) {
425 $result = $object->setRetainedWarranty(
GETPOST(
'retained_warranty',
'float'));
429 } elseif ($action ==
'setretainedwarrantydatelimit' && $user->hasRight(
'facture',
'creer')) {
431 $result = $object->setRetainedWarrantyDateLimit(
GETPOST(
'retained_warranty_date_limit',
'float'));
435 } elseif ($action ==
'setmulticurrencycode' && $usercancreate) {
436 $result = $object->setMulticurrencyCode(
GETPOST(
'multicurrency_code',
'alpha'));
437 } elseif ($action ==
'setmulticurrencyrate' && $usercancreate) {
438 $result = $object->setMulticurrencyRate(
price2num(
GETPOST(
'multicurrency_tx')),
GETPOST(
'calculation_mode',
'int'));
439 } elseif ($action ==
'setinvoicedate' && $usercancreate) {
441 $old_date_lim_reglement = $object->date_lim_reglement;
443 if (empty($newdate)) {
444 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
445 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id.
'&action=editinvoicedate&token='.newToken());
448 if ($newdate > (
dol_now(
'tzuserrel') + (!
getDolGlobalString(
'INVOICE_MAX_FUTURE_DELAY') ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
450 setEventMessages($langs->trans(
"WarningInvoiceDateInFuture"),
null,
'warnings');
452 setEventMessages($langs->trans(
"WarningInvoiceDateTooFarInFuture"),
null,
'warnings');
456 $object->date = $newdate;
457 $new_date_lim_reglement = $object->calculate_date_lim_reglement();
458 if ($new_date_lim_reglement) {
459 $object->date_lim_reglement = $new_date_lim_reglement;
461 if ($object->date_lim_reglement < $object->date) {
462 $object->date_lim_reglement = $object->date;
464 $result = $object->update($user);
468 } elseif ($action ==
'setdate_pointoftax' && $usercancreate) {
471 $date_pointoftax =
dol_mktime(0, 0, 0,
GETPOST(
'date_pointoftaxmonth',
'int'),
GETPOST(
'date_pointoftaxday',
'int'),
GETPOST(
'date_pointoftaxyear',
'int'),
'tzserver');
473 $object->date_pointoftax = $date_pointoftax;
474 $result = $object->update($user);
478 } elseif ($action ==
'setconditions' && $usercancreate) {
480 $object->cond_reglement_code = 0;
481 $object->cond_reglement_id = 0;
488 $result = $object->setPaymentTerms(
GETPOST(
'cond_reglement_id',
'int'));
496 $old_date_lim_reglement = $object->date_lim_reglement;
497 $new_date_lim_reglement = $object->calculate_date_lim_reglement();
498 if ($new_date_lim_reglement) {
499 $object->date_lim_reglement = $new_date_lim_reglement;
501 if ($object->date_lim_reglement < $object->date) {
502 $object->date_lim_reglement = $object->date;
504 $result = $object->update($user);
516 } elseif ($action ==
'setpaymentterm' && $usercancreate) {
518 $object->date_lim_reglement =
dol_mktime(12, 0, 0,
GETPOST(
'paymenttermmonth',
'int'),
GETPOST(
'paymenttermday',
'int'),
GETPOST(
'paymenttermyear',
'int'));
519 if ($object->date_lim_reglement < $object->date) {
520 $object->date_lim_reglement = $object->calculate_date_lim_reglement();
521 setEventMessages($langs->trans(
"DatePaymentTermCantBeLowerThanObjectDate"),
null,
'warnings');
523 $result = $object->update($user);
527 } elseif ($action ==
'setrevenuestamp' && $usercancreate) {
529 $object->revenuestamp =
GETPOST(
'revenuestamp');
530 $result = $object->update($user);
531 $object->update_price(1);
537 $outputlangs = $langs;
540 $newlang =
GETPOST(
'lang_id',
'aZ09');
543 $newlang = $object->thirdparty->default_lang;
545 if (!empty($newlang)) {
547 $outputlangs->setDefaultLang($newlang);
548 $outputlangs->load(
'products');
550 $model = $object->model_pdf;
551 $ret = $object->fetch($id);
553 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
559 } elseif ($action ==
'set_incoterms' && isModEnabled(
'incoterm')) {
560 $result = $object->setIncoterms(
GETPOST(
'incoterm_id',
'int'),
GETPOST(
'location_incoterms',
'alpha'));
561 } elseif ($action ==
'setbankaccount' && $usercancreate) {
562 $result = $object->setBankAccount(
GETPOST(
'fk_account',
'int'));
563 } elseif ($action ==
'setremisepercent' && $usercancreate) {
565 $result = $object->setDiscount($user,
price2num(
GETPOST(
'remise_percent'),
'', 2));
566 } elseif ($action ==
"setabsolutediscount" && $usercancreate) {
571 if (
GETPOST(
"remise_id",
'int') > 0) {
572 $ret = $object->fetch($id);
574 $result = $object->insert_discount(
GETPOST(
"remise_id",
'int'));
584 if (
GETPOST(
"remise_id_for_payment",
'int') > 0) {
585 require_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
587 $discount->fetch(
GETPOST(
"remise_id_for_payment",
'int'));
591 $remaintopay = $object->getRemainToPay(0);
595 setEventMessages($langs->trans(
"ErrorDiscountLargerThanRemainToPaySplitItBefore"),
null,
'errors');
599 $result = $discount->link_to_invoice(0, $id);
607 $newremaintopay = $object->getRemainToPay(0);
608 if ($newremaintopay == 0) {
609 $object->setPaid($user);
621 $outputlangs = $langs;
624 $newlang =
GETPOST(
'lang_id',
'aZ09');
627 $object->fetch_thirdparty();
628 $newlang = $object->thirdparty->default_lang;
630 if (!empty($newlang)) {
632 $outputlangs->setDefaultLang($newlang);
634 $ret = $object->fetch($id);
636 $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
641 } elseif ($action ==
'setref' && $usercancreate) {
643 $object->setValueFrom(
'ref',
GETPOST(
'ref'),
'',
null,
'',
'', $user,
'BILL_MODIFY');
644 } elseif ($action ==
'setref_client' && $usercancreate) {
646 $object->set_ref_client(
GETPOST(
'ref_client'));
647 } elseif ($action ==
'confirm_valid' && $confirm ==
'yes' && $usercanvalidate) {
649 $idwarehouse =
GETPOST(
'idwarehouse',
'int');
652 $object->fetch_thirdparty();
656 $qualified_for_stock_change = 0;
658 $qualified_for_stock_change = $object->hasProductsOrServices(2);
660 $qualified_for_stock_change = $object->hasProductsOrServices(1);
663 if ($qualified_for_stock_change) {
664 if (!$idwarehouse || $idwarehouse == - 1) {
666 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
"Warehouse")),
null,
'errors');
673 $result = $object->validate($user,
'', $idwarehouse);
677 $outputlangs = $langs;
680 $newlang =
GETPOST(
'lang_id',
'aZ09');
683 $newlang = $object->thirdparty->default_lang;
685 if (!empty($newlang)) {
687 $outputlangs->setDefaultLang($newlang);
688 $outputlangs->load(
'products');
690 $model = $object->model_pdf;
692 $ret = $object->fetch($id);
694 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
700 if (count($object->errors)) {
707 } elseif ($action ==
'confirm_modif' && $usercanunvalidate) {
709 $idwarehouse =
GETPOST(
'idwarehouse',
'int');
712 $object->fetch_thirdparty();
716 $qualified_for_stock_change = 0;
718 $qualified_for_stock_change = $object->hasProductsOrServices(2);
720 $qualified_for_stock_change = $object->hasProductsOrServices(1);
723 if ($qualified_for_stock_change) {
724 if (!$idwarehouse || $idwarehouse == - 1) {
726 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
"Warehouse")),
null,
'errors');
735 $sql =
'SELECT pf.amount';
736 $sql .=
' FROM '.MAIN_DB_PREFIX.
'paiement_facture as pf';
737 $sql .=
' WHERE pf.fk_facture = '.((int) $object->id);
739 $result = $db->query($sql);
742 $num = $db->num_rows($result);
745 $objp = $db->fetch_object($result);
746 $totalpaid += $objp->amount;
753 $resteapayer = $object->total_ttc - $totalpaid;
756 $ventilExportCompta = $object->getVentilExportCompta();
759 if ($ventilExportCompta == 0) {
760 if (
getDolGlobalString(
'INVOICE_CAN_BE_EDITED_EVEN_IF_PAYMENT_DONE') || ($resteapayer == $object->total_ttc && empty($object->paye))) {
761 $result = $object->setDraft($user, $idwarehouse);
768 $outputlangs = $langs;
771 $newlang =
GETPOST(
'lang_id',
'aZ09');
774 $newlang = $object->thirdparty->default_lang;
776 if (!empty($newlang)) {
778 $outputlangs->setDefaultLang($newlang);
779 $outputlangs->load(
'products');
781 $model = $object->model_pdf;
782 $ret = $object->fetch($id);
784 $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
789 } elseif ($action ==
'confirm_paid' && $confirm ==
'yes' && $usercanissuepayment) {
792 $result = $object->setPaid($user);
796 } elseif ($action ==
'confirm_paid_partially' && $confirm ==
'yes' && $usercanissuepayment) {
799 $close_code =
GETPOST(
"close_code",
'restricthtml');
800 $close_note =
GETPOST(
"close_note",
'restricthtml');
802 $result = $object->setPaid($user, $close_code, $close_note);
807 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Reason")),
null,
'errors');
809 } elseif ($action ==
'confirm_canceled' && $confirm ==
'yes') {
812 $close_code =
GETPOST(
"close_code",
'restricthtml');
813 $close_note =
GETPOST(
"close_note",
'restricthtml');
815 $result = $object->setCanceled($user, $close_code, $close_note);
820 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Reason")),
null,
'errors');
822 } elseif ($action ==
'confirm_converttoreduc' && $confirm ==
'yes' && $usercancreate) {
825 $object->fetch_thirdparty();
830 $result = $discountcheck->fetch(0, $object->id);
843 $amount_ht = $amount_tva = $amount_ttc = array();
844 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
848 foreach ($object->lines as $line) {
849 if ($line->product_type < 9 && $line->total_ht != 0) {
850 $keyforvatrate = $line->tva_tx.($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
852 $amount_ht[$keyforvatrate] += $line->total_ht;
853 $amount_tva[$keyforvatrate] += $line->total_tva;
854 $amount_ttc[$keyforvatrate] += $line->total_ttc;
855 $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
856 $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
857 $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
864 $alreadypaid = $object->getSommePaiement();
865 if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
866 $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
867 foreach ($amount_ht as $vatrate => $val) {
868 $amount_ht[$vatrate] =
price2num($amount_ht[$vatrate] * $ratio,
'MU');
869 $amount_tva[$vatrate] =
price2num($amount_tva[$vatrate] * $ratio,
'MU');
870 $amount_ttc[$vatrate] =
price2num($amount_ttc[$vatrate] * $ratio,
'MU');
871 $multicurrency_amount_ht[$vatrate] =
price2num($multicurrency_amount_ht[$vatrate] * $ratio,
'MU');
872 $multicurrency_amount_tva[$vatrate] =
price2num($multicurrency_amount_tva[$vatrate] * $ratio,
'MU');
873 $multicurrency_amount_ttc[$vatrate] =
price2num($multicurrency_amount_ttc[$vatrate] * $ratio,
'MU');
882 $discount->description =
'(CREDIT_NOTE)';
884 $discount->description =
'(DEPOSIT)';
886 $discount->description =
'(EXCESS RECEIVED)';
888 setEventMessages($langs->trans(
'CantConvertToReducAnInvoiceOfThisType'),
null,
'errors');
890 $discount->fk_soc = $object->socid;
891 $discount->fk_facture_source = $object->id;
899 $sql =
'SELECT SUM(pf.amount) as total_paiements';
900 $sql .=
' FROM '.MAIN_DB_PREFIX.
'paiement_facture as pf, '.MAIN_DB_PREFIX.
'paiement as p';
901 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as c ON p.fk_paiement = c.id';
902 $sql .=
' WHERE pf.fk_facture = '.((int) $object->id);
903 $sql .=
' AND pf.fk_paiement = p.rowid';
904 $sql .=
' AND p.entity IN ('.getEntity(
'invoice').
')';
905 $resql = $db->query($sql);
910 $res = $db->fetch_object($resql);
911 $total_paiements = $res->total_paiements;
914 $total_creditnote_and_deposit = 0;
915 $sql =
"SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
916 $sql .=
" re.description, re.fk_facture_source";
917 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe_remise_except as re";
918 $sql .=
" WHERE fk_facture = ".((int) $object->id);
919 $resql = $db->query($sql);
920 if (!empty($resql)) {
921 while ($obj = $db->fetch_object($resql)) {
922 $total_creditnote_and_deposit += $obj->amount_ttc;
928 $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
929 $discount->amount_tva = 0;
930 $discount->tva_tx = 0;
931 $discount->vat_src_code =
'';
933 $result = $discount->create($user);
939 foreach ($amount_ht as $tva_tx => $xxx) {
940 $discount->amount_ht = abs($amount_ht[$tva_tx]);
941 $discount->amount_tva = abs($amount_tva[$tva_tx]);
942 $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
943 $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
944 $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
945 $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
950 if (preg_match(
'/\((.*)\)/', $tva_tx, $reg)) {
951 $vat_src_code = $reg[1];
952 $tva_tx = preg_replace(
'/\s*\(.*\)/',
'', $tva_tx);
955 $discount->tva_tx = abs($tva_tx);
956 $discount->vat_src_code = $vat_src_code;
958 $result = $discount->create($user);
969 $result = $object->setPaid($user);
984 } elseif ($action ==
'confirm_delete_paiement' && $confirm ==
'yes' && $usercanissuepayment) {
989 $result = $paiement->fetch(
GETPOST(
'paiement_id',
'int'));
991 $result = $paiement->delete();
993 header(
"Location: ".$_SERVER[
'PHP_SELF'].
"?id=".$id);
1001 } elseif ($action ==
'add' && $usercancreate) {
1004 $object->socid =
GETPOST(
'socid',
'int');
1007 if (
GETPOST(
'type',
'int') ===
'') {
1008 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Type")),
null,
'errors');
1014 $originentity =
GETPOST(
'originentity');
1016 $ret = $extrafields->setOptionalsFromPost(
null, $object);
1022 $date_pointoftax =
dol_mktime(0, 0, 0,
GETPOST(
'date_pointoftaxmonth',
'int'),
GETPOST(
'date_pointoftaxday',
'int'),
GETPOST(
'date_pointoftaxyear',
'int'),
'tzserver');
1026 if (empty($dateinvoice)) {
1028 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
1036 if (!(
GETPOST(
'fac_replacement',
'int') > 0)) {
1038 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"ReplaceInvoice")),
null,
'errors');
1044 $result = $object->fetch(
GETPOST(
'fac_replacement',
'int'));
1045 $object->fetch_thirdparty();
1047 $object->date = $dateinvoice;
1048 $object->date_pointoftax = $date_pointoftax;
1049 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1050 $object->note_private = trim(
GETPOST(
'note_private',
'restricthtml'));
1051 $object->ref_client =
GETPOST(
'ref_client',
'alphanohtml');
1052 $object->ref_customer =
GETPOST(
'ref_client',
'alphanohtml');
1053 $object->model_pdf =
GETPOST(
'model',
'alphanohtml');
1054 $object->fk_project =
GETPOST(
'projectid',
'int');
1055 $object->cond_reglement_id =
GETPOST(
'cond_reglement_id',
'int');
1056 $object->mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int');
1057 $object->fk_account =
GETPOST(
'fk_account',
'int');
1060 $object->fk_incoterms =
GETPOST(
'incoterm_id',
'int');
1061 $object->location_incoterms =
GETPOST(
'location_incoterms',
'alpha');
1062 $object->multicurrency_code =
GETPOST(
'multicurrency_code',
'alpha');
1063 $object->multicurrency_tx =
GETPOST(
'originmulticurrency_tx',
'int');
1066 $object->fk_facture_source =
GETPOST(
'fac_replacement',
'int');
1069 $id = $object->createFromCurrent($user);
1078 $sourceinvoice =
GETPOST(
'fac_avoir',
'int');
1079 if (!($sourceinvoice > 0) && !
getDolGlobalString(
'INVOICE_CREDIT_NOTE_STANDALONE')) {
1081 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"CorrectInvoice")),
null,
'errors');
1085 if (empty($dateinvoice)) {
1087 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
1097 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceSubtype")),
null,
'errors');
1102 if (!empty($originentity)) {
1103 $object->entity = $originentity;
1105 $object->socid =
GETPOST(
'socid',
'int');
1106 $object->subtype =
GETPOST(
'subtype');
1107 $object->ref =
GETPOST(
'ref');
1108 $object->date = $dateinvoice;
1109 $object->date_pointoftax = $date_pointoftax;
1110 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1111 $object->note_private = trim(
GETPOST(
'note_private',
'restricthtml'));
1112 $object->ref_client =
GETPOST(
'ref_client',
'alphanohtml');
1113 $object->ref_customer =
GETPOST(
'ref_client',
'alphanohtml');
1114 $object->model_pdf =
GETPOST(
'model');
1115 $object->fk_project =
GETPOST(
'projectid',
'int');
1116 $object->cond_reglement_id = 0;
1117 $object->mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int');
1118 $object->fk_account =
GETPOST(
'fk_account',
'int');
1121 $object->fk_incoterms =
GETPOST(
'incoterm_id',
'int');
1122 $object->location_incoterms =
GETPOST(
'location_incoterms',
'alpha');
1123 $object->multicurrency_code =
GETPOST(
'multicurrency_code',
'alpha');
1124 $object->multicurrency_tx =
GETPOST(
'originmulticurrency_tx',
'int');
1127 $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice :
'';
1130 $facture_source =
new Facture($db);
1131 if ($facture_source->fetch($object->fk_facture_source) > 0) {
1133 $object->situation_counter = $facture_source->situation_counter;
1134 $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
1135 $facture_source->fetchPreviousNextSituationInvoice();
1140 $id = $object->create($user);
1145 if ($object->copy_linked_contact($facture_source,
'internal') < 0) {
1147 } elseif ($facture_source->socid == $object->socid) {
1149 if ($object->copy_linked_contact($facture_source,
'external') < 0) {
1160 if (
GETPOST(
'invoiceAvoirWithLines',
'int') == 1 && $id > 0) {
1161 if (!empty($facture_source->lines)) {
1162 $fk_parent_line = 0;
1164 foreach ($facture_source->lines as $line) {
1166 if (method_exists($line,
'fetch_optionals')) {
1168 $line->fetch_optionals();
1172 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1173 $fk_parent_line = 0;
1178 $source_fk_prev_id = $line->fk_prev_id;
1179 $line->fk_prev_id = $line->id;
1181 if (!empty($facture_source->tab_previous_situation_invoice)) {
1184 $tab_jumped_credit_notes = array();
1185 $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
1186 $searchPreviousInvoice =
true;
1187 while ($searchPreviousInvoice) {
1188 if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type ==
Facture::TYPE_SITUATION || $lineIndex < 1) {
1189 $searchPreviousInvoice =
false;
1193 $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
1199 $maxPrevSituationPercent = 0;
1200 foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
1201 if ($prevLine->id == $source_fk_prev_id) {
1202 $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
1205 $line->total_ht = $line->total_ht - $prevLine->total_ht;
1206 $line->total_tva = $line->total_tva - $prevLine->total_tva;
1207 $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
1208 $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
1209 $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
1211 $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
1212 $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
1213 $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
1214 $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
1219 $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
1224 $maxPrevSituationPercent = 0;
1225 foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
1226 foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
1227 if ($prevLine->fk_prev_id == $source_fk_prev_id) {
1228 $maxPrevSituationPercent = $prevLine->situation_percent;
1230 $line->total_ht -= $prevLine->total_ht;
1231 $line->total_tva -= $prevLine->total_tva;
1232 $line->total_ttc -= $prevLine->total_ttc;
1233 $line->total_localtax1 -= $prevLine->total_localtax1;
1234 $line->total_localtax2 -= $prevLine->total_localtax2;
1236 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
1237 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
1238 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
1239 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
1245 $line->situation_percent += $maxPrevSituationPercent;
1251 $line->fk_facture = $object->id;
1252 $line->fk_parent_line = $fk_parent_line;
1254 $line->subprice = -$line->subprice;
1255 $line->pa_ht = $line->pa_ht;
1256 $line->total_ht = -$line->total_ht;
1257 $line->total_tva = -$line->total_tva;
1258 $line->total_ttc = -$line->total_ttc;
1259 $line->total_localtax1 = -$line->total_localtax1;
1260 $line->total_localtax2 = -$line->total_localtax2;
1262 $line->multicurrency_subprice = -$line->multicurrency_subprice;
1263 $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
1264 $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
1265 $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
1267 $line->context[
'createcreditnotefrominvoice'] = 1;
1268 $result = $line->insert(0, 1);
1270 $object->lines[] = $line;
1273 if ($result > 0 && $line->product_type == 9) {
1274 $fk_parent_line = $result;
1278 $object->update_price(1);
1282 if (
GETPOST(
'invoiceAvoirWithPaymentRestAmount',
'int') == 1 && $id > 0) {
1283 if ($facture_source->fetch($object->fk_facture_source) > 0) {
1284 $totalpaid = $facture_source->getSommePaiement();
1285 $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
1286 $totaldeposits = $facture_source->getSumDepositsUsed();
1287 $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
1289 $object->addline($langs->trans(
'invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0,
'',
'',
'TTC');
1294 if (!empty($object->fk_facture_source) && $id > 0) {
1295 $facture_source->fetch($object->fk_facture_source);
1296 $facture_source->fetchObjectLinked();
1298 if (!empty($facture_source->linkedObjectsIds)) {
1299 foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
1300 $object->add_object_linked($sourcetype, current($TIds));
1309 if (empty($dateinvoice)) {
1311 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
1322 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceSubtype")),
null,
'errors');
1327 $object->socid =
GETPOST(
'socid',
'int');
1328 $object->type =
GETPOST(
'type');
1329 $object->subtype =
GETPOST(
'subtype');
1330 $object->ref =
GETPOST(
'ref');
1331 $object->date = $dateinvoice;
1332 $object->date_pointoftax = $date_pointoftax;
1333 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1334 $object->note_private = trim(
GETPOST(
'note_private',
'restricthtml'));
1335 $object->ref_customer =
GETPOST(
'ref_client');
1336 $object->ref_client = $object->ref_customer;
1337 $object->model_pdf =
GETPOST(
'model');
1338 $object->fk_project =
GETPOST(
'projectid',
'int');
1339 $object->cond_reglement_id = (
GETPOST(
'type') == 3 ? 1 :
GETPOST(
'cond_reglement_id'));
1340 $object->mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int');
1341 $object->fk_account =
GETPOST(
'fk_account',
'int');
1345 $object->fk_incoterms =
GETPOST(
'incoterm_id',
'int');
1346 $object->location_incoterms =
GETPOST(
'location_incoterms',
'alpha');
1347 $object->multicurrency_code =
GETPOST(
'multicurrency_code',
'alpha');
1348 $object->multicurrency_tx =
GETPOST(
'originmulticurrency_tx',
'int');
1351 $object->fac_rec =
GETPOST(
'fac_rec',
'int');
1353 $id = $object->create($user);
1359 $typeamount =
GETPOST(
'typedeposit',
'aZ09');
1360 $valuestandardinvoice =
price2num(str_replace(
'%',
'',
GETPOST(
'valuestandardinvoice',
'alpha')),
'MU');
1361 $valuedeposit =
price2num(str_replace(
'%',
'',
GETPOST(
'valuedeposit',
'alpha')),
'MU');
1363 if (
GETPOST(
'socid',
'int') < 1) {
1365 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Customer")),
null,
'errors');
1369 if (empty($dateinvoice)) {
1371 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
1381 if ($valuestandardinvoice < 0 || $valuestandardinvoice > 100) {
1382 setEventMessages($langs->trans(
"ErrorAPercentIsRequired"),
null,
'errors');
1387 if ($typeamount && !empty($origin) && !empty($originid)) {
1388 if ($typeamount ==
'amount' && $valuedeposit <= 0) {
1389 setEventMessages($langs->trans(
"ErrorAnAmountWithoutTaxIsRequired"),
null,
'errors');
1393 if ($typeamount ==
'variable' && $valuedeposit <= 0) {
1394 setEventMessages($langs->trans(
"ErrorAPercentIsRequired"),
null,
'errors');
1398 if ($typeamount ==
'variablealllines' && $valuedeposit <= 0) {
1399 setEventMessages($langs->trans(
"ErrorAPercentIsRequired"),
null,
'errors');
1409 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceSubtype")),
null,
'errors');
1414 $object->socid =
GETPOST(
'socid',
'int');
1415 $object->type =
GETPOST(
'type');
1416 $object->subtype =
GETPOST(
'subtype');
1417 $object->ref =
GETPOST(
'ref');
1418 $object->date = $dateinvoice;
1419 $object->date_pointoftax = $date_pointoftax;
1420 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1421 $object->note_private = trim(
GETPOST(
'note_private',
'restricthtml'));
1422 $object->ref_client =
GETPOST(
'ref_client');
1423 $object->ref_customer =
GETPOST(
'ref_client');
1424 $object->model_pdf =
GETPOST(
'model');
1425 $object->fk_project =
GETPOST(
'projectid',
'int');
1426 $object->cond_reglement_id = (
GETPOST(
'type') == 3 ? 1 :
GETPOST(
'cond_reglement_id'));
1427 $object->mode_reglement_id =
GETPOST(
'mode_reglement_id');
1428 $object->fk_account =
GETPOST(
'fk_account',
'int');
1432 $object->fk_incoterms =
GETPOST(
'incoterm_id',
'int');
1433 $object->location_incoterms =
GETPOST(
'location_incoterms',
'alpha');
1434 $object->multicurrency_code =
GETPOST(
'multicurrency_code',
'alpha');
1435 $object->multicurrency_tx =
GETPOST(
'originmulticurrency_tx',
'int');
1438 $object->situation_counter = 1;
1439 $object->situation_final = 0;
1440 $object->situation_cycle_ref = $object->newCycle();
1443 if (in_array($object->type, $retainedWarrantyInvoiceAvailableType)) {
1444 $object->retained_warranty =
GETPOST(
'retained_warranty',
'int');
1445 $object->retained_warranty_fk_cond_reglement =
GETPOST(
'retained_warranty_fk_cond_reglement',
'int');
1447 $object->retained_warranty = 0;
1448 $object->retained_warranty_fk_cond_reglement = 0;
1451 $retained_warranty_date_limit =
GETPOST(
'retained_warranty_date_limit');
1452 if (!empty($retained_warranty_date_limit) &&
dol_stringtotime($retained_warranty_date_limit)) {
1453 $object->retained_warranty_date_limit =
dol_stringtotime($retained_warranty_date_limit);
1455 $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
1457 $object->fetch_thirdparty();
1460 if (!empty($origin) && !empty($originid)) {
1463 $element = $subelement = $origin;
1464 if (preg_match(
'/^([^_]+)_([^_]+)/i', $origin, $regs)) {
1465 $element = $regs[1];
1466 $subelement = $regs[2];
1470 if ($element ==
'order') {
1471 $element = $subelement =
'commande';
1473 if ($element ==
'propal') {
1474 $element =
'comm/propal';
1475 $subelement =
'propal';
1477 if ($element ==
'contract') {
1478 $element = $subelement =
'contrat';
1480 if ($element ==
'inter') {
1481 $element = $subelement =
'ficheinter';
1483 if ($element ==
'shipping') {
1484 $element = $subelement =
'expedition';
1487 $object->origin = $origin;
1488 $object->origin_id = $originid;
1491 $object->linked_objects[$object->origin] = $object->origin_id;
1493 if ($object->origin ==
'shipping') {
1494 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
1496 $exp->fetch($object->origin_id);
1497 $exp->fetchObjectLinked();
1498 if (is_array($exp->linkedObjectsIds[
'commande']) && count($exp->linkedObjectsIds[
'commande']) > 0) {
1499 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
1500 $object->linked_objects[
'commande'] = $value;
1505 if (is_array($_POST[
'other_linked_objects']) && !empty($_POST[
'other_linked_objects'])) {
1506 $object->linked_objects = array_merge($object->linked_objects, $_POST[
'other_linked_objects']);
1509 $id = $object->create($user);
1514 $classname = ucfirst($subelement);
1515 $srcobject =
new $classname($db);
1517 dol_syslog(
"Try to find source object origin=".$object->origin.
" originid=".$object->origin_id.
" to add lines or deposit lines");
1518 $result = $srcobject->fetch($object->origin_id);
1523 $amountdeposit = array();
1525 if ($typeamount ==
'amount') {
1526 $amount = $valuedeposit;
1528 $amount = $srcobject->total_ttc * ($valuedeposit / 100);
1531 $TTotalByTva = array();
1532 foreach ($srcobject->lines as &$line) {
1533 if (!empty($line->special_code)) {
1536 $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1539 foreach ($TTotalByTva as $tva => &$total) {
1540 $coef = $total / $srcobject->total_ttc;
1541 $am = $amount * $coef;
1542 $amount_ttc_diff += $am;
1543 $amountdeposit[$tva] += $am / (1 + $tva / 100);
1546 if ($typeamount ==
'amount') {
1547 $amountdeposit[0] = $valuedeposit;
1548 } elseif ($typeamount ==
'variable') {
1551 $lines = $srcobject->lines;
1552 $numlines = count($lines);
1553 for ($i = 0; $i < $numlines; $i++) {
1555 if (empty($lines[$i]->qty)) {
1558 if (!empty($lines[$i]->special_code)) {
1562 $totalamount += $lines[$i]->total_ht;
1563 $tva_tx = $lines[$i]->tva_tx;
1564 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100;
1568 if ($totalamount == 0) {
1569 $amountdeposit[0] = 0;
1577 $amount_ttc_diff = $amountdeposit[0];
1580 foreach ($amountdeposit as $tva => $amount) {
1581 if (empty($amount)) {
1586 'amount' =>
'FixAmount',
1587 'variable' =>
'VarAmount'
1589 $descline =
'(DEPOSIT)';
1591 if ($typeamount ==
'amount') {
1592 $descline .=
' ('.price($valuedeposit,
'', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).
')';
1593 } elseif ($typeamount ==
'variable') {
1594 $descline .=
' ('.$valuedeposit.
'%)';
1597 $descline .=
' - '.$srcobject->ref;
1598 $result = $object->addline(
1605 (!
getDolGlobalString(
'INVOICE_PRODUCTID_DEPOSIT') ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT),
1610 $lines[$i]->info_bits,
1616 $lines[$i]->special_code,
1629 (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)?0:1)
1633 $diff = $object->total_ttc - $amount_ttc_diff;
1636 $object->fetch_lines();
1637 $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
1638 $object->updateline($object->lines[0]->id, $object->lines[0]->desc, $subprice_diff, $object->lines[0]->qty, $object->lines[0]->remise_percent, $object->lines[0]->date_start, $object->lines[0]->date_end, $object->lines[0]->tva_tx, 0, 0,
'HT', $object->lines[0]->info_bits, $object->lines[0]->product_type, 0, 0, 0, $object->lines[0]->pa_ht, $object->lines[0]->label, 0, array(), 100);
1645 $lines = $srcobject->lines;
1646 if (empty($lines) && method_exists($srcobject,
'fetch_lines')) {
1647 $srcobject->fetch_lines();
1648 $lines = $srcobject->lines;
1653 if (is_array($lines)) {
1654 foreach ($lines as $line) {
1656 $line->qty =
price2num($line->qty * $valuestandardinvoice / 100,
'MS');
1662 if (is_array($lines)) {
1663 foreach ($lines as $line) {
1665 $line->qty =
price2num($line->qty * $valuedeposit / 100,
'MS');
1670 $fk_parent_line = 0;
1671 $num = count($lines);
1673 for ($i = 0; $i < $num; $i++) {
1674 if (!in_array($lines[$i]->
id, $selectedLines)) {
1679 if ($srcobject->element ==
'shipping' &&
getDolGlobalString(
'SHIPMENT_GETS_ALL_ORDER_PRODUCTS') && $lines[$i]->qty == 0) {
1683 if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) {
1684 $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE =
'5';
1686 if ($srcobject->element ==
'contrat' && in_array($lines[$i]->
statut, explode(
',',
getDolGlobalString(
'CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE')))) {
1690 $label = (!empty($lines[$i]->label) ? $lines[$i]->label :
'');
1691 $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc :
'');
1692 if ($object->situation_counter == 1) {
1693 $lines[$i]->situation_percent = 0;
1696 if ($lines[$i]->subprice < 0 && !
getDolGlobalString(
'INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN')) {
1699 $desc = $label ? $label : $langs->trans(
'Discount');
1703 $discount->fk_soc = $object->socid;
1704 $discount->amount_ht = abs($lines[$i]->total_ht);
1705 $discount->amount_tva = abs($lines[$i]->total_tva);
1706 $discount->amount_ttc = abs($lines[$i]->total_ttc);
1707 $discount->tva_tx = $lines[$i]->tva_tx;
1708 $discount->fk_user = $user->id;
1709 $discount->description = $desc;
1710 $discount->multicurrency_subprice = abs($lines[$i]->multicurrency_subprice);
1711 $discount->multicurrency_amount_ht = abs($lines[$i]->multicurrency_total_ht);
1712 $discount->multicurrency_amount_tva = abs($lines[$i]->multicurrency_total_tva);
1713 $discount->multicurrency_amount_ttc = abs($lines[$i]->multicurrency_total_ttc);
1715 $discountid = $discount->create($user);
1716 if ($discountid > 0) {
1717 $result = $object->insert_discount($discountid);
1729 $date_start =
false;
1730 if ($lines[$i]->date_debut_prevue) {
1731 $date_start = $lines[$i]->date_debut_prevue;
1733 if ($lines[$i]->date_debut_reel) {
1734 $date_start = $lines[$i]->date_debut_reel;
1736 if ($lines[$i]->date_start) {
1737 $date_start = $lines[$i]->date_start;
1742 if ($lines[$i]->date_fin_prevue) {
1743 $date_end = $lines[$i]->date_fin_prevue;
1745 if ($lines[$i]->date_fin_reel) {
1746 $date_end = $lines[$i]->date_fin_reel;
1748 if ($lines[$i]->date_end) {
1749 $date_end = $lines[$i]->date_end;
1753 if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
1754 $fk_parent_line = 0;
1758 if (method_exists($lines[$i],
'fetch_optionals')) {
1759 $lines[$i]->fetch_optionals();
1760 $array_options = $lines[$i]->array_options;
1763 $tva_tx = $lines[$i]->tva_tx;
1764 if (!empty($lines[$i]->vat_src_code) && !preg_match(
'/\(/', $tva_tx)) {
1765 $tva_tx .=
' ('.$lines[$i]->vat_src_code.
')';
1770 $localtax1_tx =
get_localtax($tva_tx, 1, $object->thirdparty);
1771 $localtax2_tx =
get_localtax($tva_tx, 2, $object->thirdparty);
1773 $result = $object->addline(
1775 $lines[$i]->subprice,
1780 $lines[$i]->fk_product,
1781 $lines[$i]->remise_percent,
1785 $lines[$i]->info_bits,
1786 $lines[$i]->fk_remise_except,
1791 $lines[$i]->special_code,
1795 $lines[$i]->fk_fournprice,
1799 $lines[$i]->situation_percent ?? 100,
1800 $lines[$i]->fk_prev_id ?? 0,
1801 $lines[$i]->fk_unit,
1816 if ($result > 0 && $lines[$i]->product_type == 9) {
1817 $fk_parent_line = $result;
1827 $object->update_price(1,
'auto', 0, $mysoc);
1856 $parameters = array(
'objFrom' => $srcobject);
1857 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $object, $action);
1868 $id = $object->create($user);
1870 for ($i = 1; $i <= $NBLINES; $i++) {
1871 if (
GETPOST(
'idprod'.$i,
'int')) {
1873 $product->fetch(
GETPOST(
'idprod'.$i,
'int'));
1876 $result = $object->addline($product->description, $product->price,
price2num(
GETPOST(
'qty'.$i),
'MS'), $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx,
GETPOST(
'idprod'.$i,
'int'),
price2num(
GETPOST(
'remise_percent'.$i),
'', 2), $startday, $endday, 0, 0,
'', $product->price_base_type, $product->price_ttc, $product->type, -1, 0,
'', 0, 0,
null, 0,
'', 0, 100,
'', $product->fk_unit, 0,
'', 1);
1880 $object->update_price(1,
'auto', 0, $mysoc);
1887 if (empty($dateinvoice)) {
1889 $mesg = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date"));
1897 if (!(
GETPOST(
'situations',
'int') > 0)) {
1899 $mesg = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceSituation"));
1905 $result = $object->fetch(
GETPOST(
'situations',
'int'));
1906 $object->fk_facture_source =
GETPOST(
'situations',
'int');
1909 if (!empty($origin) && !empty($originid)) {
1910 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
1912 $object->origin = $origin;
1913 $object->origin_id = $originid;
1917 $retained_warranty =
GETPOST(
'retained_warranty',
'int');
1918 if (
price2num($retained_warranty) > 0) {
1919 $object->retained_warranty =
price2num($retained_warranty);
1922 if (
GETPOST(
'retained_warranty_fk_cond_reglement',
'int') > 0) {
1923 $object->retained_warranty_fk_cond_reglement =
GETPOST(
'retained_warranty_fk_cond_reglement',
'int');
1926 $retained_warranty_date_limit =
GETPOST(
'retained_warranty_date_limit');
1927 if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) {
1928 $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit);
1930 $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
1933 foreach ($object->lines as $i => &$line) {
1934 $line->origin = $object->origin;
1935 $line->origin_id = $line->id;
1936 $line->fk_prev_id = $line->id;
1937 $line->fetch_optionals();
1938 $line->situation_percent = $line->get_prev_progress($object->id);
1941 $tabprice =
calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0,
'HT', 0, $line->product_type, $mysoc,
'', $line->situation_percent);
1942 $line->total_ht = $tabprice[0];
1943 $line->total_tva = $tabprice[1];
1944 $line->total_ttc = $tabprice[2];
1945 $line->total_localtax1 = $tabprice[9];
1946 $line->total_localtax2 = $tabprice[10];
1947 $line->multicurrency_total_ht = $tabprice[16];
1948 $line->multicurrency_total_tva = $tabprice[17];
1949 $line->multicurrency_total_ttc = $tabprice[18];
1952 if ($line->fk_remise_except) {
1954 $result = $discount->fetch($line->fk_remise_except);
1957 if ($discount->fk_facture_line > 0) {
1958 $line->fk_remise_except = 0;
1965 $object->fetch_thirdparty();
1966 $object->date = $dateinvoice;
1967 $object->date_pointoftax = $date_pointoftax;
1968 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1969 $object->note = trim(
GETPOST(
'note',
'restricthtml'));
1970 $object->note_private = trim(
GETPOST(
'note',
'restricthtml'));
1971 $object->ref_client =
GETPOST(
'ref_client',
'alpha');
1972 $object->model_pdf =
GETPOST(
'model',
'alpha');
1973 $object->fk_project =
GETPOST(
'projectid',
'int');
1974 $object->cond_reglement_id =
GETPOST(
'cond_reglement_id',
'int');
1975 $object->mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int');
1978 $object->fk_account =
GETPOST(
'fk_account',
'int');
1983 $object->situation_counter = $object->situation_counter + 1;
1984 $id = $object->createFromCurrent($user);
1986 $mesg = $object->error;
1988 $nextSituationInvoice =
new Facture($db);
1989 $nextSituationInvoice->fetch($id);
1992 $extrafields->fetch_name_optionals_label($nextSituationInvoice->table_element);
1993 $ret = $extrafields->setOptionalsFromPost(
null, $nextSituationInvoice);
1995 $nextSituationInvoice->insertExtraFields();
2002 if ($id > 0 && !$error) {
2007 $outputlangs = $langs;
2010 $newlang =
GETPOST(
'lang_id',
'aZ09');
2013 $newlang = $object->thirdparty->default_lang;
2015 if (!empty($newlang)) {
2016 $outputlangs =
new Translate(
"", $conf);
2017 $outputlangs->setDefaultLang($newlang);
2018 $outputlangs->load(
'products');
2020 $model = $object->model_pdf;
2021 $ret = $object->fetch($id);
2023 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
2029 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
2034 $_GET[
"origin"] = $_POST[
"origin"];
2035 $_GET[
"originid"] = $_POST[
"originid"];
2038 } elseif ($action ==
'addline' &&
GETPOST(
'submitforalllines',
'alpha') &&
GETPOST(
'vatforalllines',
'alpha') !==
'') {
2040 $vat_rate = (
GETPOST(
'vatforalllines') ?
GETPOST(
'vatforalllines') : 0);
2041 $vat_rate = str_replace(
'*',
'', $vat_rate);
2042 $localtax1_rate =
get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
2043 $localtax2_rate =
get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
2044 foreach ($object->lines as $line) {
2045 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vat_rate, $localtax1_rate, $localtax2_rate,
'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
2047 } elseif ($action ==
'addline' &&
GETPOST(
'submitforalllines',
'alpha') &&
GETPOST(
'remiseforalllines',
'alpha') !==
'' && $usercancreate) {
2049 $remise_percent = (
GETPOST(
'remiseforalllines') ?
GETPOST(
'remiseforalllines') : 0);
2050 $remise_percent = str_replace(
'*',
'', $remise_percent);
2051 foreach ($object->lines as $line) {
2052 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
2054 } elseif ($action ==
'addline' && $usercancreate) {
2055 $langs->load(
'errors');
2060 $product_desc =(GETPOSTISSET(
'dp_desc') ?
GETPOST(
'dp_desc',
'restricthtml') :
'');
2063 $price_ht_devise =
'';
2065 $price_ttc_devise =
'';
2067 $price_min_ttc =
'';
2069 if (
GETPOST(
'price_ht') !==
'') {
2072 if (
GETPOST(
'multicurrency_price_ht') !==
'') {
2075 if (
GETPOST(
'price_ttc') !==
'') {
2078 if (
GETPOST(
'multicurrency_price_ttc') !==
'') {
2079 $price_ttc_devise =
price2num(
GETPOST(
'multicurrency_price_ttc'),
'CU', 2);
2082 $prod_entry_mode =
GETPOST(
'prod_entry_mode',
'aZ09');
2083 if ($prod_entry_mode ==
'free') {
2086 $idprod =
GETPOST(
'idprod',
'int');
2089 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"ProductOrService")),
null,
'errors');
2094 $tva_tx =
GETPOST(
'tva_tx',
'alpha');
2097 $remise_percent = (GETPOSTISSET(
'remise_percent'.$predef) ?
price2num(
GETPOST(
'remise_percent'.$predef,
'alpha'),
'', 2) : 0);
2098 if (empty($remise_percent)) {
2099 $remise_percent = 0;
2103 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
2104 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
2106 if (is_array($extralabelsline)) {
2108 foreach ($extralabelsline as $key => $value) {
2109 unset($_POST[
"options_".$key.$predef]);
2113 if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
2114 setEventMessages($langs->trans(
'ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv(
'UnitPriceHT'), $langs->transnoentitiesnoconv(
'Qty')),
null,
'errors');
2117 if (!$prod_entry_mode) {
2119 setEventMessages($langs->trans(
'ErrorChooseBetweenFreeEntryOrPredefinedProduct'),
null,
'errors');
2123 if ($prod_entry_mode ==
'free' && (empty($idprod) || $idprod < 0) &&
GETPOST(
'type') < 0) {
2124 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Type')),
null,
'errors');
2127 if ($prod_entry_mode ==
'free' && (empty($idprod) || $idprod < 0) && (($price_ht < 0 && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) || $price_ht ==
'') && (($price_ht_devise < 0 && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) || $price_ht_devise ==
'') && $price_ttc ===
'' && $price_ttc_devise ===
'' && $object->type !=
Facture::TYPE_CREDIT_NOTE) {
2128 if (($price_ht < 0 || $price_ttc < 0) && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) {
2129 $langs->load(
"errors");
2130 if ($object->type == $object::TYPE_DEPOSIT) {
2132 setEventMessages($langs->trans(
"ErrorLinesCantBeNegativeOnDeposits"),
null,
'errors');
2134 setEventMessages($langs->trans(
"ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv(
"UnitPriceHT"), $langs->transnoentitiesnoconv(
"CustomerAbsoluteDiscountShort")),
null,
'errors');
2138 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"UnitPriceHT")),
null,
'errors');
2143 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Qty')),
null,
'errors');
2146 if ($prod_entry_mode ==
'free' && empty($idprod) && empty($product_desc)) {
2147 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Description')),
null,
'errors');
2151 $langs->load(
"errors");
2152 setEventMessages($langs->trans(
'ErrorQtyForCustomerInvoiceCantBeNegative'),
null,
'errors');
2156 if (!$error && isModEnabled(
'variants') && $prod_entry_mode !=
'free') {
2157 if ($combinations =
GETPOST(
'combinations',
'array')) {
2161 if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
2162 $idprod = $res->fk_product_child;
2164 setEventMessages($langs->trans(
'ErrorProductCombinationNotFound'),
null,
'errors');
2170 if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
2171 $ret = $object->fetch($id);
2176 $ret = $object->fetch_thirdparty();
2181 $price_base_type = (
GETPOST(
'price_base_type',
'alpha') ?
GETPOST(
'price_base_type',
'alpha') :
'HT');
2192 if (!empty($idprod) && $idprod > 0) {
2194 $prod->fetch($idprod);
2196 $label = ((
GETPOST(
'product_label') &&
GETPOST(
'product_label') != $prod->label) ?
GETPOST(
'product_label') :
'');
2201 $datapriceofproduct = $prod->getSellPrice($mysoc, $object->thirdparty, $pqp);
2203 $pu_ht = $datapriceofproduct[
'pu_ht'];
2204 $pu_ttc = $datapriceofproduct[
'pu_ttc'];
2205 $price_min = $datapriceofproduct[
'price_min'];
2206 $price_min_ttc = (isset($datapriceofproduct[
'price_min_ttc'])) ? $datapriceofproduct[
'price_min_ttc'] : null;
2207 $price_base_type = empty($datapriceofproduct[
'price_base_type']) ?
'HT' : $datapriceofproduct[
'price_base_type'];
2211 $tmpvat = (float)
price2num(preg_replace(
'/\s*\(.*\)/',
'', $tva_tx));
2212 $tmpprodvat =
price2num(preg_replace(
'/\s*\(.*\)/',
'', $prod->tva_tx));
2216 if (!empty($price_ht) || $price_ht ===
'0') {
2218 $pu_ttc =
price2num($pu_ht * (1 + ($tmpvat / 100)),
'MU');
2219 } elseif (!empty($price_ht_devise) || $price_ht_devise ===
'0') {
2220 $pu_ht_devise =
price2num($price_ht_devise,
'MU');
2223 } elseif (!empty($price_ttc) || $price_ttc ===
'0') {
2225 $pu_ht =
price2num($pu_ttc / (1 + ($tmpvat / 100)),
'MU');
2226 } elseif ($tmpvat != $tmpprodvat) {
2228 if ($price_base_type !=
'HT') {
2229 $pu_ht =
price2num($pu_ttc / (1 + ($tmpvat / 100)),
'MU');
2231 $pu_ttc =
price2num($pu_ht * (1 + ($tmpvat / 100)),
'MU');
2239 $outputlangs = $langs;
2241 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
2242 $newlang =
GETPOST(
'lang_id',
'aZ09');
2244 if (empty($newlang)) {
2245 $newlang = $object->thirdparty->default_lang;
2247 if (!empty($newlang)) {
2248 $outputlangs =
new Translate(
"", $conf);
2249 $outputlangs->setDefaultLang($newlang);
2250 $outputlangs->load(
'products');
2253 $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] [
"description"])) ? $prod->multilangs [$outputlangs->defaultlang] [
"description"] : $prod->
description;
2255 $desc = $prod->description;
2264 $desc = $product_desc;
2270 if (!
getDolGlobalString(
'MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE') && (!empty($prod->customcode) || !empty($prod->country_code))) {
2274 $outputlangs = $langs;
2276 if (empty($newlang) &&
GETPOST(
'lang_id',
'alpha')) {
2277 $newlang =
GETPOST(
'lang_id',
'alpha');
2279 if (empty($newlang)) {
2280 $newlang = $object->thirdparty->default_lang;
2282 if (!empty($newlang)) {
2283 $outputlangs =
new Translate(
"", $conf);
2284 $outputlangs->setDefaultLang($newlang);
2285 $outputlangs->load(
'products');
2287 if (!empty($prod->customcode)) {
2288 $tmptxt .= $outputlangs->transnoentitiesnoconv(
"CustomCode").
': '.$prod->customcode;
2290 if (!empty($prod->customcode) && !empty($prod->country_code)) {
2293 if (!empty($prod->country_code)) {
2294 $tmptxt .= $outputlangs->transnoentitiesnoconv(
"CountryOrigin").
': '.
getCountry($prod->country_code, 0, $db, $outputlangs, 0);
2297 if (!empty($prod->customcode)) {
2298 $tmptxt .= $langs->transnoentitiesnoconv(
"CustomCode").
': '.$prod->customcode;
2300 if (!empty($prod->customcode) && !empty($prod->country_code)) {
2303 if (!empty($prod->country_code)) {
2304 $tmptxt .= $langs->transnoentitiesnoconv(
"CountryOrigin").
': '.
getCountry($prod->country_code, 0, $db, $langs, 0);
2311 $type = $prod->type;
2312 $fk_unit = $prod->fk_unit;
2314 if (!empty($price_ht)) $pu_ht =
price2num($price_ht,
'MU');
2316 if (!empty($price_ttc)) $pu_ttc =
price2num($price_ttc,
'MU');
2318 $tva_npr = (preg_match(
'/\*/', $tva_tx) ? 1 : 0);
2319 $tva_tx = str_replace(
'*',
'', $tva_tx);
2320 if (empty($tva_tx)) {
2323 $label = (
GETPOST(
'product_label') ?
GETPOST(
'product_label') :
'');
2324 $desc = $product_desc;
2326 $fk_unit =
GETPOST(
'units',
'alpha');
2328 if ($pu_ttc && !$pu_ht) {
2329 $price_base_type =
'TTC';
2340 $localtax1_tx =
get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
2341 $localtax2_tx =
get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
2343 $pu_ht_devise =
price2num($price_ht_devise,
'', 2);
2344 $pu_ttc_devise =
price2num($price_ttc_devise,
'', 2);
2347 $pu_equivalent = $pu_ht;
2348 $pu_equivalent_ttc = $pu_ttc;
2350 $currency_tx = $object->multicurrency_tx;
2354 if ($pu_ht ==
'' && $pu_ht_devise !=
'' && $currency_tx !=
'') {
2355 $pu_equivalent = $pu_ht_devise * $currency_tx;
2357 if ($pu_ttc ==
'' && $pu_ttc_devise !=
'' && $currency_tx !=
'') {
2358 $pu_equivalent_ttc = $pu_ttc_devise * $currency_tx;
2378 $price2num_remise_percent =
price2num($remise_percent);
2379 $price2num_price_min =
price2num($price_min);
2380 $price2num_price_min_ttc =
price2num($price_min_ttc);
2381 if (empty($price2num_pu_ht)) {
2382 $price2num_pu_ht = 0;
2384 if (empty($price2num_remise_percent)) {
2385 $price2num_remise_percent = 0;
2387 if (empty($price2num_price_min)) {
2388 $price2num_price_min = 0;
2390 if (empty($price2num_price_min_ttc)) {
2391 $price2num_price_min_ttc = 0;
2396 if ($pu_equivalent && $price_min && ((
price2num($pu_equivalent) * (1 - $remise_percent / 100)) <
price2num($price_min)) && $price_base_type ==
'HT') {
2397 $mesg = $langs->trans(
"CantBeLessThanMinPrice",
price(
price2num($price_min,
'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2400 } elseif ($pu_equivalent_ttc && $price_min_ttc && ((
price2num($pu_equivalent_ttc) * (1 - $remise_percent / 100)) <
price2num($price_min_ttc)) && $price_base_type ==
'TTC') {
2401 $mesg = $langs->trans(
"CantBeLessThanMinPriceInclTax",
price(
price2num($price_min_ttc,
'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2409 if (isModEnabled(
'productbatch') && !empty($lines[$i]->detail_batch) && is_array($lines[$i]->detail_batch) &&
getDolGlobalString(
'INVOICE_INCUDE_DETAILS_OF_LOTS_SERIALS')) {
2410 $langs->load(
'productbatch');
2411 foreach ($lines[$i]->detail_batch as $batchline) {
2412 $desc .=
' '.$langs->trans(
'Batch').
' '.$batchline->batch.
' '.$langs->trans(
'printQty', $batchline->qty).
' ';
2417 $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $date_start, $date_end, 0, $info_bits,
'', $price_base_type, $pu_ttc, $type, min($rank, count($object->lines) + 1), $special_code,
'', 0,
GETPOST(
'fk_parent_line'), $fournprice, $buyingprice, $label, $array_options,
GETPOST(
'progress'),
'', $fk_unit, $pu_ht_devise);
2422 $outputlangs = $langs;
2425 $newlang =
GETPOST(
'lang_id',
'aZ09');
2428 $newlang = $object->thirdparty->default_lang;
2430 if (!empty($newlang)) {
2431 $outputlangs =
new Translate(
"", $conf);
2432 $outputlangs->setDefaultLang($newlang);
2433 $outputlangs->load(
'products');
2435 $model = $object->model_pdf;
2436 $ret = $object->fetch($id);
2438 $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
2444 unset($_POST[
'prod_entry_mode']);
2445 unset($_POST[
'qty']);
2446 unset($_POST[
'type']);
2447 unset($_POST[
'remise_percent']);
2448 unset($_POST[
'price_ht']);
2449 unset($_POST[
'multicurrency_price_ht']);
2450 unset($_POST[
'price_ttc']);
2451 unset($_POST[
'tva_tx']);
2452 unset($_POST[
'product_ref']);
2453 unset($_POST[
'product_label']);
2454 unset($_POST[
'product_desc']);
2455 unset($_POST[
'fournprice']);
2456 unset($_POST[
'buying_price']);
2457 unset($_POST[
'np_marginRate']);
2458 unset($_POST[
'np_markRate']);
2459 unset($_POST[
'dp_desc']);
2460 unset($_POST[
'idprod']);
2461 unset($_POST[
'units']);
2462 unset($_POST[
'date_starthour']);
2463 unset($_POST[
'date_startmin']);
2464 unset($_POST[
'date_startsec']);
2465 unset($_POST[
'date_startday']);
2466 unset($_POST[
'date_startmonth']);
2467 unset($_POST[
'date_startyear']);
2468 unset($_POST[
'date_endhour']);
2469 unset($_POST[
'date_endmin']);
2470 unset($_POST[
'date_endsec']);
2471 unset($_POST[
'date_endday']);
2472 unset($_POST[
'date_endmonth']);
2473 unset($_POST[
'date_endyear']);
2474 unset($_POST[
'situations']);
2475 unset($_POST[
'progress']);
2483 } elseif ($action ==
'updateline' && $usercancreate && !
GETPOST(
'cancel',
'alpha')) {
2484 if (!$object->fetch($id) > 0) {
2487 $object->fetch_thirdparty();
2496 $vat_rate = str_replace(
'*',
'', $vat_rate);
2508 if (preg_match(
'/\*/', $vat_rate)) {
2513 $vat_rate = str_replace(
'*',
'', $vat_rate);
2514 $localtax1_rate =
get_localtax($vat_rate, 1, $object->thirdparty);
2515 $localtax2_rate =
get_localtax($vat_rate, 2, $object->thirdparty);
2522 $pu_equivalent = $pu_ht;
2523 $pu_equivalent_ttc = $pu_ttc;
2525 $currency_tx = $object->multicurrency_tx;
2529 if ($pu_ht ==
'' && $pu_ht_devise !=
'' && $currency_tx !=
'') {
2530 $pu_equivalent = $pu_ht_devise * $currency_tx;
2532 if ($pu_ttc ==
'' && $pu_ttc_devise !=
'' && $currency_tx !=
'') {
2533 $pu_equivalent_ttc = $pu_ttc_devise * $currency_tx;
2548 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
2549 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
2551 if (is_array($extralabelsline)) {
2553 foreach ($extralabelsline as $key => $value) {
2554 unset($_POST[
"options_".$key]);
2559 $special_code =
GETPOST(
'special_code',
'int');
2560 if ($special_code == 3) {
2565 $line->fetch(
GETPOST(
'lineid',
'int'));
2566 $percent = $line->get_prev_progress($object->id);
2571 if ($progress >= 0) {
2572 $mesg = $langs->trans(
"CantBeNullOrPositive");
2576 } elseif ($progress < $line->situation_percent) {
2577 $mesg = $langs->trans(
"CantBeLessThanMinPercent");
2581 } elseif ($progress < $percent) {
2582 $mesg =
'<div class="warning">'.$langs->trans(
"CantBeLessThanMinPercent").
'</div>';
2592 $productid =
GETPOST(
'productid',
'int');
2593 if (!empty($productid)) {
2595 $product->fetch($productid);
2597 $type = $product->type;
2599 $price_min = $product->price_min;
2601 $price_min = $product->multiprices_min[$object->thirdparty->price_level];
2603 $price_min_ttc = $product->price_min_ttc;
2605 $price_min_ttc = $product->multiprices_min_ttc[$object->thirdparty->price_level];
2612 if ($pu_equivalent && $price_min && (((
float)
price2num($pu_equivalent) * (1 - (
float) $remise_percent / 100)) < (float)
price2num($price_min)) && $price_base_type ==
'HT') {
2613 $mesg = $langs->trans(
"CantBeLessThanMinPrice",
price(
price2num($price_min,
'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2616 $action =
'editline';
2617 } elseif ($pu_equivalent_ttc && $price_min_ttc && ((
price2num($pu_equivalent_ttc) * (1 - (
float) $remise_percent / 100)) <
price2num($price_min_ttc)) && $price_base_type ==
'TTC') {
2618 $mesg = $langs->trans(
"CantBeLessThanMinPriceInclTax",
price(
price2num($price_min_ttc,
'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2621 $action =
'editline';
2626 $label = (
GETPOST(
'product_label') ?
GETPOST(
'product_label') :
'');
2630 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Type")),
null,
'errors');
2635 $langs->load(
"errors");
2636 setEventMessages($langs->trans(
'ErrorQtyForCustomerInvoiceCantBeNegative'),
null,
'errors');
2639 if (empty($productid) && (($pu_ht < 0 && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) || $pu_ht ==
'') && (($pu_ht_devise < 0 && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) || $pu_ht_devise ==
'') && $pu_ttc ===
'' && $pu_ttc_devise ===
'' && $object->type !=
Facture::TYPE_CREDIT_NOTE) {
2640 if (($pu_ht < 0 || $pu_ttc < 0) && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) {
2641 $langs->load(
"errors");
2642 if ($object->type == $object::TYPE_DEPOSIT) {
2644 setEventMessages($langs->trans(
"ErrorLinesCantBeNegativeOnDeposits"),
null,
'errors');
2646 setEventMessages($langs->trans(
"ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv(
"UnitPriceHT"), $langs->transnoentitiesnoconv(
"CustomerAbsoluteDiscountShort")),
null,
'errors');
2650 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"UnitPriceHT")),
null,
'errors');
2658 if (empty($usercancreatemargin)) {
2659 foreach ($object->lines as &$line) {
2660 if ($line->id ==
GETPOST(
'lineid',
'int')) {
2661 $fournprice = $line->fk_fournprice;
2662 $buyingprice = $line->pa_ht;
2668 $price_base_type =
'HT';
2670 if (empty($pu) && !empty($pu_ttc)) {
2672 $price_base_type =
'TTC';
2675 $result = $object->updateline(
2689 GETPOST(
'fk_parent_line',
'int'),
2704 $outputlangs = $langs;
2707 $newlang =
GETPOST(
'lang_id',
'aZ09');
2710 $newlang = $object->thirdparty->default_lang;
2712 if (!empty($newlang)) {
2713 $outputlangs =
new Translate(
"", $conf);
2714 $outputlangs->setDefaultLang($newlang);
2715 $outputlangs->load(
'products');
2718 $ret = $object->fetch($id);
2719 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2722 unset($_POST[
'qty']);
2723 unset($_POST[
'type']);
2724 unset($_POST[
'productid']);
2725 unset($_POST[
'remise_percent']);
2726 unset($_POST[
'price_ht']);
2727 unset($_POST[
'multicurrency_price_ht']);
2728 unset($_POST[
'price_ttc']);
2729 unset($_POST[
'tva_tx']);
2730 unset($_POST[
'product_ref']);
2731 unset($_POST[
'product_label']);
2732 unset($_POST[
'product_desc']);
2733 unset($_POST[
'fournprice']);
2734 unset($_POST[
'buying_price']);
2735 unset($_POST[
'np_marginRate']);
2736 unset($_POST[
'np_markRate']);
2737 unset($_POST[
'dp_desc']);
2738 unset($_POST[
'idprod']);
2739 unset($_POST[
'units']);
2740 unset($_POST[
'date_starthour']);
2741 unset($_POST[
'date_startmin']);
2742 unset($_POST[
'date_startsec']);
2743 unset($_POST[
'date_startday']);
2744 unset($_POST[
'date_startmonth']);
2745 unset($_POST[
'date_startyear']);
2746 unset($_POST[
'date_endhour']);
2747 unset($_POST[
'date_endmin']);
2748 unset($_POST[
'date_endsec']);
2749 unset($_POST[
'date_endday']);
2750 unset($_POST[
'date_endmonth']);
2751 unset($_POST[
'date_endyear']);
2752 unset($_POST[
'situations']);
2753 unset($_POST[
'progress']);
2758 } elseif ($action ==
'updatealllines' && $usercancreate &&
GETPOST(
'all_percent') == $langs->trans(
'Modifier')) {
2759 if (!$object->fetch($id) > 0) {
2762 if (
GETPOST(
'all_progress') !=
"") {
2763 $all_progress =
GETPOST(
'all_progress',
'int');
2764 foreach ($object->lines as $line) {
2765 $percent = $line->get_prev_progress($object->id);
2766 if ((
float) $all_progress < (
float) $percent) {
2767 $mesg = $langs->trans(
"Line").
' '.$i.
' : '.$langs->trans(
"CantBeLessThanMinPercent");
2771 $object->update_percent($line,
GETPOST(
'all_progress'),
false);
2774 $object->update_price(1);
2776 } elseif ($action ==
'updateline' && $usercancreate && !$cancel) {
2777 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
2779 } elseif ($action ==
'confirm_situationout' && $confirm ==
'yes' && $usercancreate) {
2781 $object->fetch($id,
'',
'',
'',
true);
2787 && $object->is_last_in_cycle()
2788 && $usercanunvalidate
2791 $newCycle = $object->newCycle();
2792 if ($newCycle > 1) {
2794 $lastCycle = $object->situation_cycle_ref;
2795 $lastSituationCounter = $object->situation_counter;
2796 $linkedCreditNotesList = array();
2798 if (count($object->tab_next_situation_invoice) > 0) {
2799 foreach ($object->tab_next_situation_invoice as $next_invoice) {
2801 && $next_invoice->situation_counter == $object->situation_counter
2802 && $next_invoice->fk_facture_source == $object->id
2804 $linkedCreditNotesList[] = $next_invoice->id;
2809 $object->situation_cycle_ref = $newCycle;
2810 $object->situation_counter = 1;
2811 $object->situation_final = 0;
2812 if ($object->update($user) > 0) {
2814 if (count($linkedCreditNotesList) > 0) {
2816 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
2817 $sql .=
' SET situation_cycle_ref = '.((int) $newCycle);
2818 $sql .=
' , situation_final=0';
2819 $sql .=
' , situation_counter='.((int) $object->situation_counter);
2820 $sql .=
' WHERE rowid IN ('.$db->sanitize(implode(
',', $linkedCreditNotesList)).
')';
2822 $resql = $db->query($sql);
2828 foreach ($object->lines as $line) {
2830 if ($line->product_type == 9) {
2835 if (!empty($object->tab_previous_situation_invoice)) {
2837 $lineIndex = count($object->tab_previous_situation_invoice) - 1;
2838 $searchPreviousInvoice =
true;
2839 while ($searchPreviousInvoice) {
2841 $searchPreviousInvoice =
false;
2849 $maxPrevSituationPercent = 0;
2850 foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
2851 if ($prevLine->id == $line->fk_prev_id) {
2852 $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
2857 $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent;
2859 if ($line->update() < 0) {
2868 header(
"Location: ".$_SERVER[
'PHP_SELF'].
"?id=".$id);
2870 setEventMessages($langs->trans(
'ErrorOutingSituationInvoiceCreditNote'), array(),
'errors');
2873 setEventMessages($langs->trans(
'ErrorOutingSituationInvoiceOnUpdate'), array(),
'errors');
2876 setEventMessages($langs->trans(
'ErrorFindNextSituationInvoice'), array(),
'errors');
2879 } elseif ($action ==
'import_lines_from_object'
2884 $fromElement =
GETPOST(
'fromelement');
2885 $fromElementid =
GETPOST(
'fromelementid');
2886 $importLines =
GETPOST(
'line_checkbox');
2888 if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
2889 if ($fromElement ==
'commande') {
2891 $lineClassName =
'OrderLine';
2892 } elseif ($fromElement ==
'propal') {
2893 dol_include_once(
'/comm/'.$fromElement.
'/class/'.$fromElement.
'.class.php');
2894 $lineClassName =
'PropaleLigne';
2896 $nextRang = count($object->lines) + 1;
2899 foreach ($importLines as $lineId) {
2900 $lineId = intval($lineId);
2901 $originLine =
new $lineClassName($db);
2902 if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
2903 $originLine->fetch_optionals();
2904 $desc = $originLine->desc;
2905 $pu_ht = $originLine->subprice;
2906 $qty = $originLine->qty;
2907 $txtva = $originLine->tva_tx;
2908 $txlocaltax1 = $originLine->localtax1_tx;
2909 $txlocaltax2 = $originLine->localtax2_tx;
2910 $fk_product = $originLine->fk_product;
2911 $remise_percent = $originLine->remise_percent;
2912 $date_start = $originLine->date_start;
2913 $date_end = $originLine->date_end;
2915 $info_bits = $originLine->info_bits;
2916 $fk_remise_except = $originLine->fk_remise_except;
2917 $price_base_type =
'HT';
2919 $type = $originLine->product_type;
2920 $rang = $nextRang++;
2921 $special_code = $originLine->special_code;
2922 $origin = $originLine->element;
2923 $origin_id = $originLine->id;
2924 $fk_parent_line = 0;
2925 $fk_fournprice = $originLine->fk_fournprice;
2926 $pa_ht = $originLine->pa_ht;
2927 $label = $originLine->label;
2928 $array_options = $originLine->array_options;
2930 $situation_percent = 0;
2932 $situation_percent = 100;
2935 $fk_unit = $originLine->fk_unit;
2936 $pu_ht_devise = $originLine->multicurrency_subprice;
2938 $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $ventil, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $type, $rang, $special_code, $origin, $origin_id, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $situation_percent, $fk_prev_id, $fk_unit, $pu_ht_devise);
2957 include DOL_DOCUMENT_ROOT.
'/core/actions_printing.inc.php';
2963 $triggersendname =
'BILL_SENTBYMAIL';
2965 $autocopy =
'MAIN_MAIL_AUTOCOPY_INVOICE_TO';
2966 $trackid =
'inv'.$object->id;
2967 include DOL_DOCUMENT_ROOT.
'/core/actions_sendmails.inc.php';
2970 $upload_dir = $conf->facture->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity];
2971 $permissiontoadd = $usercancreate;
2972 include DOL_DOCUMENT_ROOT.
'/core/actions_builddoc.inc.php';
2975 if ($action ==
'update_extras') {
2976 $object->oldcopy =
dol_clone($object, 2);
2979 $ret = $extrafields->setOptionalsFromPost(
null, $object,
GETPOST(
'attribute',
'restricthtml'));
2986 $result = $object->insertExtraFields(
'BILL_MODIFY');
2994 $action =
'edit_extras';
2999 if ($action ==
'addcontact') {
3000 $result = $object->fetch($id);
3002 if ($result > 0 && $id > 0) {
3005 $result = $object->add_contact($contactid, $typeid,
GETPOST(
"source",
'aZ09'));
3009 header(
"Location: ".$_SERVER[
'PHP_SELF'].
"?id=".$object->id);
3012 if ($object->error ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
3013 $langs->load(
"errors");
3014 setEventMessages($langs->trans(
"ErrorThisContactIsAlreadyDefinedAsThisType"),
null,
'errors');
3019 } elseif ($action ==
'swapstatut') {
3021 if ($object->fetch($id)) {
3022 $result = $object->swapContactStatus(
GETPOST(
'ligne',
'int'));
3026 } elseif ($action ==
'deletecontact') {
3028 $object->fetch($id);
3029 $result = $object->delete_contact($lineid);
3032 header(
"Location: ".$_SERVER[
'PHP_SELF'].
"?id=".$object->id);
3040 $action =
'edit_extras';
3051$form =
new Form($db);
3057$bankaccountstatic =
new Account($db);
3058if (isModEnabled(
'project')) {
3064$title = $object->ref.
" - ".$langs->trans(
'Card');
3065if ($action ==
'create') {
3066 $title = $langs->trans(
"NewBill");
3068$help_url =
"EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
3074if ($action ==
'create') {
3075 $facturestatic =
new Facture($db);
3076 $extrafields->fetch_name_optionals_label($facturestatic->table_element);
3081 $res = $soc->fetch($socid);
3084 $currency_code = $conf->currency;
3086 $cond_reglement_id =
GETPOST(
'cond_reglement_id',
'int');
3087 $mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int');
3088 $fk_account =
GETPOST(
'fk_account',
'int');
3092 if (!empty($origin) && !empty($originid)) {
3094 $element = $subelement = $origin;
3096 if (preg_match(
'/^([^_]+)_([^_]+)/i', $origin, $regs)) {
3097 $element = $regs[1];
3098 $subelement = $regs[2];
3101 if ($element ==
'project') {
3102 $projectid = $originid;
3104 if (empty($cond_reglement_id)) {
3105 $cond_reglement_id = $soc->cond_reglement_id;
3107 if (empty($mode_reglement_id)) {
3108 $mode_reglement_id = $soc->mode_reglement_id;
3110 if (empty($fk_account)) {
3111 $fk_account = $soc->fk_account;
3113 if (!$remise_percent) {
3114 $remise_percent = $soc->remise_percent;
3116 if (!$dateinvoice) {
3118 $dateinvoice = (empty($dateinvoice) ? (!
getDolGlobalString(
'MAIN_AUTOFILL_DATE') ? -1 :
'') : $dateinvoice);
3122 if ($element ==
'order' || $element ==
'commande') {
3123 $element = $subelement =
'commande';
3125 if ($element ==
'propal') {
3126 $element =
'comm/propal';
3127 $subelement =
'propal';
3129 if ($element ==
'contract') {
3130 $element = $subelement =
'contrat';
3132 if ($element ==
'shipping') {
3133 $element = $subelement =
'expedition';
3138 $classname = ucfirst($subelement);
3139 $objectsrc =
new $classname($db);
3140 $objectsrc->fetch($originid);
3141 if (empty($objectsrc->lines) && method_exists($objectsrc,
'fetch_lines')) {
3142 $objectsrc->fetch_lines();
3144 $objectsrc->fetch_thirdparty();
3146 $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project);
3147 $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer :
''));
3150 if (empty($socid)) {
3151 $soc = $objectsrc->thirdparty;
3154 $dateinvoice = (empty($dateinvoice) ? (!
getDolGlobalString(
'MAIN_AUTOFILL_DATE') ? -1 :
'') : $dateinvoice);
3156 if ($element ==
'expedition') {
3157 $ref_client = (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer :
'');
3159 $elem = $subelem = $objectsrc->origin;
3160 $expeoriginid = $objectsrc->origin_id;
3162 $classname = ucfirst($subelem);
3164 $expesrc =
new $classname($db);
3165 $expesrc->fetch($expeoriginid);
3167 $cond_reglement_id = (!empty($expesrc->cond_reglement_id) ? $expesrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 1));
3168 $mode_reglement_id = (!empty($expesrc->mode_reglement_id) ? $expesrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
3169 $fk_account = (!empty($expesrc->fk_account) ? $expesrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
3173 if (isModEnabled(
'multicurrency')) {
3174 $currency_code = (!empty($expesrc->multicurrency_code) ? $expesrc->multicurrency_code : (!empty($soc->multicurrency_code) ? $soc->multicurrency_code : $objectsrc->multicurrency_code));
3175 $currency_tx = (!empty($expesrc->multicurrency_tx) ? $expesrc->multicurrency_tx : (!empty($soc->multicurrency_tx) ? $soc->multicurrency_tx : $objectsrc->multicurrency_tx));
3179 $expesrc->fetch_optionals();
3180 $object->array_options = $expesrc->array_options;
3182 $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0));
3183 $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
3184 $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
3188 if (isModEnabled(
'multicurrency')) {
3189 if (!empty($objectsrc->multicurrency_code)) {
3190 $currency_code = $objectsrc->multicurrency_code;
3192 if (
getDolGlobalString(
'MULTICURRENCY_USE_ORIGIN_TX') && !empty($objectsrc->multicurrency_tx)) {
3193 $currency_tx = $objectsrc->multicurrency_tx;
3198 $objectsrc->fetch_optionals();
3199 $object->array_options = $objectsrc->array_options;
3203 $cond_reglement_id = empty($soc->cond_reglement_id) ? $cond_reglement_id : $soc->cond_reglement_id;
3204 $mode_reglement_id = empty($soc->mode_reglement_id) ? $mode_reglement_id : $soc->mode_reglement_id;
3205 $fk_account = empty($soc->fk_account) ? $fk_account : $soc->fk_account;
3208 $dateinvoice = (empty($dateinvoice) ? (!
getDolGlobalString(
'MAIN_AUTOFILL_DATE') ? -1 :
'') : $dateinvoice);
3210 if (isModEnabled(
'multicurrency') && !empty($soc->multicurrency_code)) {
3211 $currency_code = $soc->multicurrency_code;
3216 if (!
GETPOST(
'changecompany')) {
3217 if (GETPOSTISSET(
'cond_reglement_id')) {
3218 $cond_reglement_id =
GETPOST(
'cond_reglement_id',
'int');
3220 if (GETPOSTISSET(
'mode_reglement_id')) {
3221 $mode_reglement_id =
GETPOST(
'mode_reglement_id',
'int');
3223 if (GETPOSTISSET(
'cond_reglement_id')) {
3224 $fk_account =
GETPOST(
'fk_account',
'int');
3229 if (empty($cond_reglement_id)) {
3230 $cond_reglement_id =
GETPOST(
"cond_reglement_id",
'int');
3234 if (empty($mode_reglement_id)) {
3235 $mode_reglement_id =
GETPOST(
"mode_reglement_id",
'int');
3245 if (!empty($soc->id)) {
3246 $absolute_discount = $soc->getAvailableDiscounts();
3248 $note_public = $object->getDefaultCreateValueFor(
'note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) &&
getDolGlobalString(
'FACTURE_REUSE_NOTES_ON_CREATE_FROM')) ? $objectsrc->note_public : null));
3249 $note_private = $object->getDefaultCreateValueFor(
'note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) &&
getDolGlobalString(
'FACTURE_REUSE_NOTES_ON_CREATE_FROM')) ? $objectsrc->note_private : null));
3251 if (!empty($conf->use_javascript_ajax)) {
3252 require_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
3258 if ($origin ==
'contrat') {
3259 $langs->load(
"admin");
3260 $text = $langs->trans(
"ToCreateARecurringInvoice");
3261 $text .=
' '.$langs->trans(
"ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv(
"MenuFinancial"), $langs->transnoentitiesnoconv(
"BillsCustomers"), $langs->transnoentitiesnoconv(
"ListOfTemplates"));
3263 $text .=
' '.$langs->trans(
"ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv(
'Module2300Name'));
3265 print
info_admin($text, 0, 0, 0,
'opacitymedium').
'<br>';
3268 print
'<form name="add" action="'.$_SERVER[
"PHP_SELF"].
'" method="POST" id="formtocreate" name="formtocreate">';
3269 print
'<input type="hidden" name="token" value="'.newToken().
'">';
3270 print
'<input type="hidden" name="action" id="formtocreateaction" value="add">';
3271 print
'<input type="hidden" name="changecompany" value="0">';
3273 print
'<input type="hidden" name="socid" value="'.$soc->id.
'">'.
"\n";
3275 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
3276 print
'<input name="ref" type="hidden" value="provisoire">';
3277 print
'<input name="ref_client" type="hidden" value="'.$ref_client.
'">';
3278 print
'<input name="force_cond_reglement_id" type="hidden" value="0">';
3279 print
'<input name="force_mode_reglement_id" type="hidden" value="0">';
3280 print
'<input name="force_fk_account" type="hidden" value="0">';
3281 print
'<input type="hidden" name="origin" value="'.$origin.
'">';
3282 print
'<input type="hidden" name="originid" value="'.$originid.
'">';
3283 print
'<input type="hidden" name="originentity" value="'.GETPOST(
'originentity').
'">';
3284 if (!empty($currency_tx)) {
3285 print
'<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.
'">';
3291 $parameters = array();
3293 $reshook = $hookmanager->executeHooks(
'tabContentCreateInvoice', $parameters, $object, $action);
3294 if (empty($reshook)) {
3295 print
'<table class="border centpercent">';
3300 $exampletemplateinvoice =
new FactureRec($db);
3302 if (empty($origin) && empty($originid) &&
GETPOST(
'fac_rec',
'int') > 0) {
3303 $invoice_predefined->fetch(
GETPOST(
'fac_rec',
'int'));
3307 if ($soc->id > 0 && (!
GETPOST(
'fac_rec',
'int') || !empty($invoice_predefined->frequency))) {
3309 print
'<tr><td class="fieldrequired">'.$langs->trans(
'Customer').
'</td>';
3310 print
'<td colspan="2">';
3311 print $soc->getNomUrl(1,
'customer');
3312 print
'<input type="hidden" name="socid" value="'.$soc->id.
'">';
3314 $arrayoutstandingbills = $soc->getOutstandingBills();
3315 $outstandingBills = $arrayoutstandingbills[
'opened'];
3316 print
' - <span class="opacitymedium">'.$langs->trans(
'CurrentOutstandingBill').
':</span> ';
3317 print
'<span class="amount">'.price($outstandingBills,
'', $langs, 0, 0, -1, $conf->currency).
'</span>';
3318 if ($soc->outstanding_limit !=
'') {
3319 if ($outstandingBills > $soc->outstanding_limit) {
3320 print
img_warning($langs->trans(
"OutstandingBillReached"));
3322 print
' / '.price($soc->outstanding_limit,
'', $langs, 0, 0, -1, $conf->currency);
3327 print
'<tr><td class="fieldrequired">'.$langs->trans(
'Customer').
'</td>';
3328 print
'<td colspan="2">';
3329 $filter =
'((s.client:IN:1,2,3) AND (s.status:=:1))';
3330 print
img_picto(
'',
'company',
'class="pictofixedwidth"').$form->select_company($soc->id,
'socid', $filter,
'SelectThirdParty', 1, 0,
null, 0,
'minwidth300 widthcentpercentminusxx maxwidth500');
3334 $(document).ready(function() {
3335 $("#socid").change(function() {
3337 console.log("Submit page");
3338 $(\'input[name="action"]\').val(\'create\');
3339 $(\'input[name="force_cond_reglement_id"]\').val(\'1\');
3340 $(\'input[name="force_mode_reglement_id"]\').val(\'1\');
3341 $(\'input[name="force_fk_account"]\').val(\'1\');
3342 $("#formtocreate").submit(); */
3344 // For company change, we must submit page with action=create instead of action=add
3345 console.log("We have changed the company - Resubmit page");
3346 jQuery("input[name=changecompany]").val("1");
3347 jQuery("#formtocreateaction").val("create");
3348 jQuery("#formtocreate").submit();
3353 if (!
GETPOST(
'fac_rec',
'int')) {
3354 print
' <a href="'.DOL_URL_ROOT.
'/societe/card.php?action=create&client=3&fournisseur=0&backtopage='.urlencode($_SERVER[
"PHP_SELF"].
'?action=create').
'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans(
"AddThirdParty").
'"></span></a>';
3361 if (empty($origin) && empty($originid) &&
GETPOST(
'fac_rec',
'int') > 0) {
3362 $invoice_predefined->fetch(
GETPOST(
'fac_rec',
'int'));
3364 $dateinvoice = $invoice_predefined->date_when;
3365 if (empty($projectid)) {
3366 $projectid = $invoice_predefined->fk_project;
3368 $cond_reglement_id = $invoice_predefined->cond_reglement_id;
3369 $mode_reglement_id = $invoice_predefined->mode_reglement_id;
3370 $fk_account = $invoice_predefined->fk_account;
3371 $note_public = $invoice_predefined->note_public;
3372 $note_private = $invoice_predefined->note_private;
3374 if (!empty($invoice_predefined->multicurrency_code)) {
3375 $currency_code = $invoice_predefined->multicurrency_code;
3377 if (!empty($invoice_predefined->multicurrency_tx)) {
3378 $currency_tx = $invoice_predefined->multicurrency_tx;
3381 $sql =
'SELECT r.rowid, r.titre as title, r.total_ttc';
3382 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture_rec as r';
3383 $sql .=
' WHERE r.fk_soc = '.((int) $invoice_predefined->socid);
3385 $resql = $db->query($sql);
3387 $num = $db->num_rows($resql);
3391 print
'<tr><td>'.$langs->trans(
'CreateFromRepeatableInvoice').
'</td><td>';
3393 print
'<select class="flat" id="fac_rec" name="fac_rec">';
3394 print
'<option value="0" selected></option>';
3396 $objp = $db->fetch_object($resql);
3397 print
'<option value="'.$objp->rowid.
'"';
3398 if (
GETPOST(
'fac_rec',
'int') == $objp->rowid) {
3400 $exampletemplateinvoice->fetch(
GETPOST(
'fac_rec',
'int'));
3402 print
'>'.$objp->title.
' ('.
price($objp->total_ttc).
' '.$langs->trans(
"TTC").
')</option>';
3411 print
'<script type="text/javascript">
3412 $(document).ready(function() {
3413 $("#fac_rec").change(function() {
3414 console.log("We have changed the template invoice - Reload page");
3415 var fac_rec = $(this).val();
3416 var socid = $(\'#socid\').val();
3417 // For template invoice change, we must reuse data of template, not input already done, so we call a GET with action=create, not a POST submit.
3418 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?action=create&socid="+socid+"&fac_rec="+fac_rec;
3431 print
'<tr><td class="tdtop fieldrequired">'.$langs->trans(
'Type').
'</td><td colspan="2">';
3432 print
'<div class="tagtable">'.
"\n";
3435 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3436 $tmp =
'<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOST(
'type',
'int') ?
'' :
' checked').
'> ';
3437 $tmp = $tmp.
'<label for="radio_standard" >'.$langs->trans(
"InvoiceStandardAsk").
'</label>';
3438 $desc = $form->textwithpicto($tmp, $langs->transnoentities(
"InvoiceStandardDesc"), 1,
'help',
'', 0, 3,
'standardonsmartphone');
3439 print
'<table class="nobordernopadding"><tr>';
3443 if ((($origin ==
'propal') || ($origin ==
'commande')) && (!empty($originid))) {
3452 print
'<td class="nowrap" style="padding-left: 15px">';
3453 print
'<span class="opacitymedium">'.$langs->trans(
'PercentOfOriginalObject').
'</span>:<input class="right" placeholder="100%" type="text" id="valuestandardinvoice" name="valuestandardinvoice" size="3" value="'.(GETPOSTISSET(
'valuestandardinvoice') ?
GETPOST(
'valuestandardinvoice',
'alpha') :
'100%').
'"/>';
3456 print
'</tr></table>';
3457 print
'</div></div>';
3459 if ((empty($origin)) || ((($origin ==
'propal') || ($origin ==
'commande')) && (!empty($originid)))) {
3462 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3463 $tmp =
'<input type="radio" id="radio_deposit" name="type" value="3"'.(GETPOST(
'type') == 3 ?
' checked' :
'').
'> ';
3464 print
'<script type="text/javascript">
3465 jQuery(document).ready(function() {
3466 jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
3467 jQuery("#radio_standard").prop("checked", true);
3469 jQuery("#typedeposit, #valuedeposit").click(function() {
3470 jQuery("#radio_deposit").prop("checked", true);
3472 jQuery("#typedeposit").change(function() {
3473 console.log("We change type of down payment");
3474 jQuery("#radio_deposit").prop("checked", true);
3475 setRadioForTypeOfInvoice();
3477 jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_creditnote, #radio_template").change(function() {
3478 setRadioForTypeOfInvoice();
3480 function setRadioForTypeOfInvoice() {
3481 console.log("Change radio");
3482 if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
3483 jQuery(".checkforselect").prop("disabled", true);
3484 jQuery(".checkforselect").prop("checked", false);
3486 jQuery(".checkforselect").prop("disabled", false);
3487 jQuery(".checkforselect").prop("checked", true);
3493 print
'<table class="nobordernopadding"><tr>';
3495 $tmp = $tmp.
'<label for="radio_deposit">'.$langs->trans(
"InvoiceDeposit").
'</label>';
3496 $desc = $form->textwithpicto($tmp, $langs->transnoentities(
"InvoiceDepositDesc"), 1,
'help',
'', 0, 3,
'depositonsmartphone');
3499 if (($origin ==
'propal') || ($origin ==
'commande')) {
3500 print
'<td class="nowrap" style="padding-left: 15px">';
3502 'amount' => $langs->transnoentitiesnoconv(
'FixAmount', $langs->transnoentitiesnoconv(
'Deposit')),
3503 'variable' => $langs->transnoentitiesnoconv(
'VarAmountOneLine', $langs->transnoentitiesnoconv(
'Deposit')),
3504 'variablealllines' => $langs->transnoentitiesnoconv(
'VarAmountAllLines')
3506 $typedeposit =
GETPOST(
'typedeposit',
'aZ09');
3507 $valuedeposit =
GETPOST(
'valuedeposit',
'int');
3508 if (empty($typedeposit) && !empty($objectsrc->deposit_percent)) {
3509 $origin_payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $objectsrc->cond_reglement_id);
3510 if (!empty($origin_payment_conditions_deposit_percent)) {
3511 $typedeposit =
'variable';
3514 if (empty($valuedeposit) && $typedeposit ==
'variable' && !empty($objectsrc->deposit_percent)) {
3515 $valuedeposit = $objectsrc->deposit_percent;
3517 print $form->selectarray(
'typedeposit', $arraylist, $typedeposit, 0, 0, 0,
'', 1);
3519 print
'<td class="nowrap" style="padding-left: 5px">';
3520 print
'<span class="opacitymedium paddingleft">'.$langs->trans(
"AmountOrPercent").
'</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="'.$valuedeposit.
'"/>';
3523 print
'</tr></table>';
3525 print
'</div></div>';
3532 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3533 $tmp =
'<input id="radio_situation" type="radio" name="type" value="5"'.(GETPOST(
'type') == 5 ?
' checked' :
'').
'> ';
3534 $tmp = $tmp.
'<label for="radio_situation" >'.$langs->trans(
"InvoiceFirstSituationAsk").
'</label>';
3535 $desc = $form->textwithpicto($tmp, $langs->transnoentities(
"InvoiceFirstSituationDesc"), 1,
'help',
'', 0, 3,
'firstsituationonsmartphone');
3537 print
'</div></div>';
3540 $opt = $form->selectSituationInvoices(
GETPOST(
'originid',
'int'), $socid);
3542 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3543 $tmp =
'<input type="radio" name="type" value="5"'.(GETPOST(
'type') == 5 &&
GETPOST(
'originid',
'int') ?
' checked' :
'');
3544 if ($opt == (
'<option value ="0" selected>'.$langs->trans(
'NoSituations').
'</option>') || (
GETPOST(
'origin') &&
GETPOST(
'origin') !=
'facture' &&
GETPOST(
'origin') !=
'commande')) {
3545 $tmp .=
' disabled';
3548 $text = $tmp.
'<label>'.$langs->trans(
"InvoiceSituationAsk").
'</label> ';
3549 $text .=
'<select class="flat" id="situations" name="situations"';
3550 if ($opt == (
'<option value ="0" selected>'.$langs->trans(
'NoSituations').
'</option>') || (
GETPOST(
'origin') &&
GETPOST(
'origin') !=
'facture' &&
GETPOST(
'origin') !=
'commande')) {
3551 $text .=
' disabled';
3555 $text .=
'</select>';
3556 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceSituationDesc"), 1,
'help',
'', 0, 3);
3558 print
'</div></div>';
3564 $facids = $facturestatic->list_replacable_invoices($soc->id);
3570 if (is_array($facids)) {
3571 foreach ($facids as $facparam) {
3572 $options .=
'<option value="'.$facparam [
'id'].
'"';
3573 if ($facparam[
'id'] ==
GETPOST(
'fac_replacement',
'int')) {
3574 $options .=
' selected';
3576 $options .=
'>'.$facparam[
'ref'];
3577 $options .=
' ('.$facturestatic->LibStatut($facparam[
'paid'], $facparam[
'status'], 0, $facparam[
'alreadypaid']).
')';
3578 $options .=
'</option>';
3582 print
'<!-- replacement line -->';
3583 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3584 $tmp =
'<input type="radio" name="type" id="radio_replacement" value="1"'.(GETPOST(
'type') == 1 ?
' checked' :
'');
3585 if (!$options || $invoice_predefined->id > 0) {
3586 $tmp .=
' disabled';
3589 print
'<script type="text/javascript">
3590 jQuery(document).ready(function() {
3591 jQuery("#fac_replacement").change(function() {
3592 jQuery("#radio_replacement").prop("checked", true);
3596 $text = $tmp.
'<label for="radio_replacement">'.$langs->trans(
"InvoiceReplacementAsk").
'</label>';
3597 $text .=
'<select class="flat" name="fac_replacement" id="fac_replacement"';
3598 if (!$options || $invoice_predefined->id > 0) {
3599 $text .=
' disabled';
3603 $text .=
'<option value="-1"> </option>';
3606 $text .=
'<option value="-1">'.$langs->trans(
"NoReplacableInvoice").
'</option>';
3608 $text .=
'</select>';
3609 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceReplacementDesc"), 1,
'help',
'', 0, 3);
3611 print
'</div></div>';
3615 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3616 $tmp =
'<input type="radio" name="type" id="radio_situation" value="0" disabled> ';
3617 $text = $tmp.
'<label>'.$langs->trans(
"InvoiceSituationAsk").
'</label> ';
3618 $text .=
'<span class="opacitymedium">('.$langs->trans(
"YouMustCreateInvoiceFromThird").
')</span> ';
3619 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceFirstSituationDesc"), 1,
'help',
'', 0, 3,
'firstsituationonsmartphone');
3621 print
'</div></div>';
3624 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3625 $tmp =
'<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
3626 $text = $tmp.
'<label for="radio_replacement" class="opacitymedium">'.$langs->trans(
"InvoiceReplacement").
'</label> ';
3628 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceReplacementDesc").
'<br><br>'.$langs->trans(
"YouMustCreateInvoiceFromThird"), 1,
'help',
'', 0, 3,
'replacementonsmartphone');
3630 print
'</div></div>';
3633 if (empty($origin)) {
3638 $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
3644 $newinvoice_static =
new Facture($db);
3645 foreach ($facids as $key => $valarray) {
3646 $newinvoice_static->id = $key;
3647 $newinvoice_static->ref = $valarray [
'ref'];
3648 $newinvoice_static->statut = $valarray [
'status'];
3649 $newinvoice_static->type = $valarray [
'type'];
3650 $newinvoice_static->paye = $valarray [
'paye'];
3652 $optionsav .=
'<option value="'.$key.
'"';
3653 if ($key ==
GETPOST(
'fac_avoir')) {
3654 $optionsav .=
' selected';
3657 $newinvoice_static->fetch_optionals($key);
3658 $object->array_options = $newinvoice_static->array_options;
3661 $optionsav .= $newinvoice_static->ref;
3662 $optionsav .=
' ('.$newinvoice_static->getLibStatut(1, $valarray [
'paymentornot']).
')';
3663 $optionsav .=
'</option>';
3666 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3667 $tmp =
'<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST(
'type') == 2 ?
' checked' :
'');
3668 if ((!$optionsav && !
getDolGlobalString(
'INVOICE_CREDIT_NOTE_STANDALONE')) || $invoice_predefined->id > 0) {
3669 $tmp .=
' disabled';
3673 print
'<script type="text/javascript">
3674 jQuery(document).ready(function() {
3675 if (jQuery("#radio_creditnote").is(":checked"))
3677 jQuery("#radio_standard").prop("disabled", true);
3679 jQuery("#radio_standard").prop("disabled", false);
3681 if (! jQuery("#radio_creditnote").is(":checked"))
3683 jQuery("#credit_note_options").hide();
3685 jQuery("#radio_creditnote").click(function() {
3686 jQuery("#credit_note_options").show();
3688 jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
3689 jQuery("#credit_note_options").hide();
3693 $text =
'<label>'.$tmp.$langs->transnoentities(
"InvoiceAvoirAsk").
'</label> ';
3694 $text .=
'<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
3695 if (!$optionsav || $invoice_predefined->id > 0) {
3696 $text .=
' disabled';
3700 $text .=
'<option value="-1"></option>';
3701 $text .= $optionsav;
3703 $text .=
'<option value="-1">'.$langs->trans(
"NoInvoiceToCorrect").
'</option>';
3705 $text .=
'</select>';
3706 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceAvoirDesc"), 1,
'help',
'', 0, 3);
3709 print
'<div id="credit_note_options" class="clearboth paddingtop marginbottomonly">';
3710 print
' <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST(
'invoiceAvoirWithLines',
'int') > 0 ?
'checked' :
'').
' /> <label for="invoiceAvoirWithLines">'.$langs->trans(
'invoiceAvoirWithLines').
"</label>";
3711 print
'<br> <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST(
'invoiceAvoirWithPaymentRestAmount',
'int') > 0 ?
'checked' :
'').
' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans(
'invoiceAvoirWithPaymentRestAmount').
"</label>";
3714 print
'</div></div>';
3717 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3719 $tmp =
'<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
3721 $tmp =
'<input type="radio" name="type" id="radio_creditnote" value="2" > ';
3723 $text = $tmp.
'<label class="opacitymedium" for="radio_creditnote">'.$langs->trans(
"InvoiceAvoir").
'</label> ';
3725 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceAvoirDesc").
'<br><br>'.$langs->trans(
"CreateCreditNoteWhenClientInvoiceExists"), 1,
'help',
'', 0, 3,
'creditnoteonsmartphone');
3727 print
'</div></div>'.
"\n";
3732 print
'<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3733 $tmp =
'<input type="radio" name="type" id="radio_template" value="0" disabled> ';
3734 $text = $tmp.
'<label class="opacitymedium" for="radio_template">'.$langs->trans(
"RepeatableInvoice").
'</label> ';
3735 $desc = $form->textwithpicto($text, $langs->transnoentities(
"YouMustCreateStandardInvoiceFirstDesc"), 1,
'help',
'', 0, 3,
'templateonsmartphone');
3737 print
'</div></div>';
3746 foreach ($listtType as $type) {
3747 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$type;
3749 $jsListType .= (!empty($jsListType) ?
',' :
'').
'"'.$type.
'":"'.$curent.
'"';
3752 print
'<script type="text/javascript">
3753 $(document).ready(function() {
3754 var listType = {'.$jsListType.
'};
3755 $("[name=\'type\'").change(function() {
3756 console.log("change name=type");
3757 if ($( this ).prop("checked"))
3759 if(($( this ).val() in listType))
3761 $("#model").val(listType[$( this ).val()]);
3778 print
'<tr><td class="fieldrequired">'.$langs->trans(
'InvoiceSubtype').
'</td><td colspan="2">';
3779 print $form->getSelectInvoiceSubtype(
GETPOST(
'subtype'),
'subtype', 1, 0,
'');
3785 print
'<tr><td>'.$langs->trans(
'DiscountStillRemaining').
'</td><td colspan="2">';
3789 $backtopage = $_SERVER[
"PHP_SELF"].
'?socid='.$thirdparty->id.
'&action='.$action.
'&origin='.urlencode(
GETPOST(
'origin')).
'&originid='.urlencode(
GETPOSTINT(
'originid'));
3790 include DOL_DOCUMENT_ROOT.
'/core/tpl/object_discounts.tpl.php';
3796 $date_pointoftax =
dol_mktime(0, 0, 0,
GETPOST(
'date_pointoftaxmonth',
'int'),
GETPOST(
'date_pointoftaxday',
'int'),
GETPOST(
'date_pointoftaxyear',
'int'),
'tzserver');
3799 print
'<tr><td class="fieldrequired">'.$langs->trans(
'DateInvoice').
'</td><td colspan="2">';
3800 print
img_picto(
'',
'action',
'class="pictofixedwidth"');
3801 print $form->selectDate($newdateinvoice ? $newdateinvoice : $dateinvoice,
'',
'',
'',
'',
"add", 1, 1);
3806 print
'<tr><td class="fieldrequired">'.$langs->trans(
'DatePointOfTax').
'</td><td colspan="2">';
3807 print
img_picto(
'',
'action',
'class="pictofixedwidth"');
3808 print $form->selectDate($date_pointoftax ? $date_pointoftax : -1,
'date_pointoftax',
'',
'',
'',
"add", 1, 1);
3813 print
'<tr><td class="nowrap fieldrequired">'.$langs->trans(
'PaymentConditionsShort').
'</td><td colspan="2">';
3814 print
img_picto(
'',
'payment',
'class="pictofixedwidth"');
3815 print $form->getSelectConditionsPaiements($cond_reglement_id,
'cond_reglement_id', -1, 1, 0,
'maxwidth500 widthcentpercentminusx');
3820 $rwStyle =
'display:none;';
3821 if (in_array(
GETPOST(
'type',
'int'), $retainedWarrantyInvoiceAvailableType)) {
3825 $retained_warranty =
GETPOST(
'retained_warranty',
'int');
3826 if (empty($retained_warranty)) {
3827 if (!empty($objectsrc->retained_warranty)) {
3828 $retained_warranty = $objectsrc->retained_warranty;
3831 $retained_warranty_js_default = !empty($retained_warranty) ? $retained_warranty : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT;
3833 print
'<tr class="retained-warranty-line" style="'.$rwStyle.
'" ><td class="nowrap">'.$langs->trans(
'RetainedWarranty').
'</td><td colspan="2">';
3834 print
'<input id="new-situation-invoice-retained-warranty" name="retained_warranty" type="number" value="'.$retained_warranty.
'" step="0.01" min="0" max="100" />%';
3837 print
'<tr class="retained-warranty-line" style="'.$rwStyle.
'" ><td class="nowrap">'.$langs->trans(
'PaymentConditionsShortRetainedWarranty').
'</td><td colspan="2">';
3838 $retained_warranty_fk_cond_reglement =
GETPOST(
'retained_warranty_fk_cond_reglement',
'int');
3839 if (empty($retained_warranty_fk_cond_reglement)) {
3840 $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
3841 if (!empty($objectsrc->retained_warranty_fk_cond_reglement)) {
3842 $retained_warranty_fk_cond_reglement = $objectsrc->retained_warranty_fk_cond_reglement;
3844 $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
3847 print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement,
'retained_warranty_fk_cond_reglement', -1, 1);
3850 print
'<script type="text/javascript">
3851 $(document).ready(function() {
3852 $("[name=\'type\']").change(function() {
3853 if($( this ).prop("checked") && $.inArray($( this ).val(), '.json_encode($retainedWarrantyInvoiceAvailableType).
' ) !== -1)
3855 $(".retained-warranty-line").show();
3856 $("#new-situation-invoice-retained-warranty").val("'.(float) $retained_warranty_js_default.
'");
3859 $(".retained-warranty-line").hide();
3860 $("#new-situation-invoice-retained-warranty").val("");
3864 $("[name=\'type\']:checked").trigger("change");
3870 print
'<tr><td>'.$langs->trans(
'PaymentMode').
'</td><td colspan="2">';
3871 print
img_picto(
'',
'bank',
'class="pictofixedwidth"');
3872 print $form->select_types_paiements($mode_reglement_id,
'mode_reglement_id',
'CRDT', 0, 1, 0, 0, 1,
'maxwidth200 widthcentpercentminusx', 1);
3876 if (isModEnabled(
"banque")) {
3877 print
'<tr><td>'.$langs->trans(
'BankAccount').
'</td><td colspan="2">';
3878 print
img_picto(
'',
'bank_account',
'class="pictofixedwidth"');
3879 print $form->select_comptes($fk_account,
'fk_account', 0,
'', 1,
'', 0,
'maxwidth200 widthcentpercentminusx', 1);
3884 if (isModEnabled(
'project')) {
3885 $langs->load(
'projects');
3886 print
'<tr><td>'.$langs->trans(
'Project').
'</td><td colspan="2">';
3887 print
img_picto(
'',
'project',
'class="pictofixedwidth"').$formproject->select_projects(($socid > 0 ? $socid : -1), $projectid,
'projectid', 0, 0, 1, 1, 0, 0, 0,
'', 1, 0,
'maxwidth500 widthcentpercentminusxx');
3888 print
' <a href="'.DOL_URL_ROOT.
'/projet/card.php?socid='.$soc->id.
'&action=create&status=1&backtopage='.urlencode($_SERVER[
"PHP_SELF"].
'?action=create&socid='.$soc->id.($fac_rec ?
'&fac_rec='.$fac_rec :
'')).
'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans(
"AddProject").
'"></span></a>';
3893 if (isModEnabled(
'incoterm')) {
3895 print
'<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans(
"IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms :
'', 1).
'</label></td>';
3896 print
'<td colspan="2" class="maxwidthonsmartphone">';
3897 $incoterm_id =
GETPOST(
'incoterm_id');
3898 $incoterm_location =
GETPOST(
'location_incoterms');
3899 if (empty($incoterm_id)) {
3900 $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
3901 $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
3903 print
img_picto(
'',
'incoterm',
'class="pictofixedwidth"');
3904 print $form->select_incoterms($incoterm_id, $incoterm_location);
3909 $parameters = array(
'objectsrc' => !empty($objectsrc) ? $objectsrc : 0,
'colspan' =>
' colspan="2"',
'cols' =>
'2',
'socid'=>$socid);
3910 $reshook = $hookmanager->executeHooks(
'formObjectOptions', $parameters, $object, $action);
3911 print $hookmanager->resPrint;
3912 if (empty($reshook)) {
3913 if (
getDolGlobalString(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE') && !empty($soc->id)) {
3916 $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
3917 if ($soc->fetch_optionals() > 0) {
3918 $object->array_options = array_merge($object->array_options, $soc->array_options);
3922 print $object->showOptionals($extrafields,
'create', $parameters);
3926 print
'<tr><td>'.$langs->trans(
'Model').
'</td>';
3927 print
'<td colspan="2">';
3928 print
img_picto(
'',
'pdf',
'class="pictofixedwidth"');
3929 include_once DOL_DOCUMENT_ROOT.
'/core/modules/facture/modules_facture.php';
3932 $type = GETPOSTISSET(
'type') ?
GETPOSTINT(
'type') : $object->
type;
3934 $paramkey =
'FACTURE_ADDON_PDF_'.$type;
3939 print $form->selectarray(
'model', $liste, $preselected, 0, 0, 0,
'', 0, 0, 0,
'',
'maxwidth200 widthcentpercentminusx', 1);
3943 if (isModEnabled(
'multicurrency')) {
3945 print
'<td>'.$form->editfieldkey(
'Currency',
'multicurrency_code',
'', $object, 0).
'</td>';
3946 print
'<td colspan="2" class="maxwidthonsmartphone">';
3947 print
img_picto(
'',
'currency',
'class="pictofixedwidth"');
3948 print $form->selectMultiCurrency(((GETPOSTISSET(
'multicurrency_code') && !
GETPOST(
'changecompany')) ?
GETPOST(
'multicurrency_code') : $currency_code),
'multicurrency_code');
3954 if (
GETPOST(
'fac_rec',
'int') > 0) {
3955 $dateexample = ($newdateinvoice ? $newdateinvoice : $dateinvoice);
3956 if (empty($dateexample)) {
3959 $substitutionarray = array(
3960 '__TOTAL_HT__' => $langs->trans(
"AmountHT").
' ('.$langs->trans(
"Example").
': '.
price($exampletemplateinvoice->total_ht).
')',
3961 '__TOTAL_TTC__' => $langs->trans(
"AmountTTC").
' ('.$langs->trans(
"Example").
': '.
price($exampletemplateinvoice->total_ttc).
')',
3962 '__INVOICE_PREVIOUS_MONTH__' => $langs->trans(
"PreviousMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, -1,
'm'),
'%m').
')',
3963 '__INVOICE_MONTH__' => $langs->trans(
"MonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date($dateexample,
'%m').
')',
3964 '__INVOICE_NEXT_MONTH__' => $langs->trans(
"NextMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, 1,
'm'),
'%m').
')',
3965 '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans(
"TextPreviousMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, -1,
'm'),
'%B').
')',
3966 '__INVOICE_MONTH_TEXT__' => $langs->trans(
"TextMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date($dateexample,
'%B').
')',
3967 '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans(
"TextNextMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, 1,
'm'),
'%B').
')',
3968 '__INVOICE_PREVIOUS_YEAR__' => $langs->trans(
"PreviousYearOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, -1,
'y'),
'%Y').
')',
3969 '__INVOICE_YEAR__' => $langs->trans(
"YearOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date($dateexample,
'%Y').
')',
3970 '__INVOICE_NEXT_YEAR__' => $langs->trans(
"NextYearOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, 1,
'y'),
'%Y').
')'
3973 $htmltext =
'<i>'.$langs->trans(
"FollowingConstantsWillBeSubstituted").
':<br>';
3974 foreach ($substitutionarray as $key => $val) {
3975 $htmltext .= $key.
' = '.$langs->trans($val).
'<br>';
3977 $htmltext .=
'</i>';
3982 print
'<td class="tdtop">';
3983 print $form->textwithpicto($langs->trans(
'NotePublic'), $htmltext);
3985 print
'<td valign="top" colspan="2">';
3986 $doleditor =
new DolEditor(
'note_public', $note_public,
'', 80,
'dolibarr_notes',
'In', 0,
false, !
getDolGlobalString(
'FCKEDITOR_ENABLE_NOTE_PUBLIC') ? 0 : 1, ROWS_3,
'90%');
3987 print $doleditor->Create(1);
3990 if (empty($user->socid)) {
3992 print
'<td class="tdtop">';
3993 print $form->textwithpicto($langs->trans(
'NotePrivate'), $htmltext);
3995 print
'<td valign="top" colspan="2">';
3996 $doleditor =
new DolEditor(
'note_private', $note_private,
'', 80,
'dolibarr_notes',
'In', 0,
false, !
getDolGlobalString(
'FCKEDITOR_ENABLE_NOTE_PRIVATE') ? 0 : 1, ROWS_3,
'90%');
3997 print $doleditor->Create(1);
4003 if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
4004 $langs->loadLangs(array(
'orders',
'propal'));
4007 if ($origin ==
'contrat') {
4011 $objectsrc->update_price(1,
'auto', 1);
4014 print
"\n<!-- Show ref of origin ".$classname.
" -->\n";
4015 print
'<input type="hidden" name="amount" value="'.$objectsrc->total_ht.
'">'.
"\n";
4016 print
'<input type="hidden" name="total" value="'.$objectsrc->total_ttc.
'">'.
"\n";
4017 print
'<input type="hidden" name="tva" value="'.$objectsrc->total_tva.
'">'.
"\n";
4022 switch (get_class($objectsrc)) {
4024 $newclassname =
'CommercialProposal';
4027 $newclassname =
'Order';
4030 $newclassname =
'Sending';
4033 $newclassname =
'Contract';
4036 $newclassname =
'Intervention';
4039 $newclassname = get_class($objectsrc);
4043 print
'<tr><td>'.$langs->trans($newclassname).
'</td>';
4044 print
'<td colspan="2">';
4045 print $objectsrc->getNomUrl(1);
4047 $objectsrc->fetchObjectLinked($originid, $origin,
'',
'facture');
4048 if (isset($objectsrc->linkedObjects[
'facture']) && is_array($objectsrc->linkedObjects[
'facture']) && count($objectsrc->linkedObjects[
'facture']) >= 1) {
4050 echo
' - '.$langs->trans(
'LatestRelatedBill').
' '.end($objectsrc->linkedObjects[
'facture'])->getNomUrl(1);
4053 print
'<tr><td>'.$langs->trans(
'AmountHT').
'</td><td colspan="2">'.
price($objectsrc->total_ht).
'</td></tr>';
4054 print
'<tr><td>'.$langs->trans(
'AmountVAT').
'</td><td colspan="2">'.
price($objectsrc->total_tva).
"</td></tr>";
4055 if ($mysoc->localtax1_assuj ==
"1" || $objectsrc->total_localtax1 != 0) {
4056 print
'<tr><td>'.$langs->transcountry(
"AmountLT1", $mysoc->country_code).
'</td><td colspan="2">'.
price($objectsrc->total_localtax1).
"</td></tr>";
4059 if ($mysoc->localtax2_assuj ==
"1" || $objectsrc->total_localtax2 != 0) {
4060 print
'<tr><td>'.$langs->transcountry(
"AmountLT2", $mysoc->country_code).
'</td><td colspan="2">'.
price($objectsrc->total_localtax2).
"</td></tr>";
4062 print
'<tr><td>'.$langs->trans(
'AmountTTC').
'</td><td colspan="2">'.
price($objectsrc->total_ttc).
"</td></tr>";
4064 if (isModEnabled(
'multicurrency')) {
4065 print
'<tr><td>'.$langs->trans(
'MulticurrencyAmountHT').
'</td><td colspan="2">'.
price($objectsrc->multicurrency_total_ht).
'</td></tr>';
4066 print
'<tr><td>'.$langs->trans(
'MulticurrencyAmountVAT').
'</td><td colspan="2">'.
price($objectsrc->multicurrency_total_tva).
"</td></tr>";
4067 print
'<tr><td>'.$langs->trans(
'MulticurrencyAmountTTC').
'</td><td colspan="2">'.
price($objectsrc->multicurrency_total_ttc).
"</td></tr>";
4075 print $form->buttonsSaveCancel(
"CreateDraft");
4078 if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
4081 $title = $langs->trans(
'ProductsAndServices');
4084 print
'<div class="div-table-responsive-no-min">';
4085 print
'<table class="noborder centpercent">';
4087 $objectsrc->printOriginLinesList(
'', $selectedLines);
4094} elseif ($id > 0 || !empty($ref)) {
4095 if (empty($object->id)) {
4096 $langs->load(
'errors');
4097 echo
'<div class="error">'.$langs->trans(
"ErrorRecordNotFound").
'</div>';
4106 $result = $object->fetch($id, $ref);
4113 $extrafields->fetch_name_optionals_label($object->table_element);
4115 if ($user->socid > 0 && $user->socid != $object->socid) {
4119 $result = $object->fetch_thirdparty();
4121 $result = $soc->fetch($object->socid);
4125 $selleruserevenustamp = $mysoc->useRevenueStamp();
4127 $totalpaid = $object->getSommePaiement();
4128 $totalcreditnotes = $object->getSumCreditNotesUsed();
4129 $totaldeposits = $object->getSumDepositsUsed();
4137 $resteapayer =
price2num($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits,
'MT');
4140 if (isModEnabled(
'multicurrency')) {
4141 $multicurrency_totalpaid = $object->getSommePaiement(1);
4142 $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
4143 $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
4144 $multicurrency_resteapayer =
price2num($object->multicurrency_total_ttc - $multicurrency_totalpaid - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits,
'MT');
4148 if ($resteapayer == 0 && $multicurrency_resteapayer != 0 && $object->multicurrency_code != $conf->currency) {
4149 $resteapayer =
price2num($multicurrency_resteapayer / $object->multicurrency_tx,
'MT');
4153 if ($object->paye) {
4156 $resteapayeraffiche = $resteapayer;
4159 $filterabsolutediscount =
"fk_facture_source IS NULL";
4160 $filtercreditnote =
"fk_facture_source IS NOT NULL";
4162 $filterabsolutediscount =
"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
4163 $filtercreditnote =
"fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
4166 $absolute_discount = $soc->getAvailableDiscounts(
'', $filterabsolutediscount);
4167 $absolute_creditnote = $soc->getAvailableDiscounts(
'', $filtercreditnote);
4168 $absolute_discount =
price2num($absolute_discount,
'MT');
4169 $absolute_creditnote =
price2num($absolute_creditnote,
'MT');
4171 $author =
new User($db);
4172 if ($object->user_author) {
4173 $author->fetch($object->user_author);
4176 $objectidnext = $object->getIdReplacingInvoice();
4180 print
dol_get_fiche_head($head,
'compta', $langs->trans(
'InvoiceCustomer'), -1,
'bill');
4185 if ($action ==
'converttoreduc') {
4187 $type_fac =
'ExcessReceived';
4189 $type_fac =
'CreditNote';
4191 $type_fac =
'Deposit';
4193 $text = $langs->trans(
'ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac)));
4194 $text .=
'<br>'.$langs->trans(
'ConfirmConvertToReduc2');
4195 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $langs->trans(
'ConvertToReduc'), $text,
'confirm_converttoreduc',
'',
"yes", 2);
4199 if ($action ==
'delete') {
4200 $text = $langs->trans(
'ConfirmDeleteBill', $object->ref);
4201 $formquestion = array();
4204 $qualified_for_stock_change = 0;
4206 $qualified_for_stock_change = $object->hasProductsOrServices(2);
4208 $qualified_for_stock_change = $object->hasProductsOrServices(1);
4211 if ($qualified_for_stock_change) {
4212 $langs->load(
"stocks");
4213 require_once DOL_DOCUMENT_ROOT.
'/product/class/html.formproduct.class.php';
4215 $label = $object->type ==
Facture::TYPE_CREDIT_NOTE ? $langs->trans(
"SelectWarehouseForStockDecrease") : $langs->trans(
"SelectWarehouseForStockIncrease");
4217 if ($conf->browser->name ==
'ie') {
4220 $formquestion = array(
4224 array(
'type' =>
'other',
'name' =>
'idwarehouse',
'label' => $label,
'value' => $formproduct->selectWarehouses(
GETPOST(
'idwarehouse') ?
GETPOST(
'idwarehouse') :
'ifone',
'idwarehouse',
'', 1, 0, 0, $langs->trans(
"NoStockAction"), 0, $forcecombo))
4226 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $langs->trans(
'DeleteBill'), $text,
'confirm_delete', $formquestion,
"yes", 1);
4228 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $langs->trans(
'DeleteBill'), $text,
'confirm_delete',
'',
'no', 1);
4231 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $langs->trans(
'DeleteBill'), $text,
'confirm_delete',
'',
'no', 1);
4236 if ($action ==
'situationout') {
4237 $text = $langs->trans(
'ConfirmRemoveSituationFromCycle', $object->ref);
4238 $label = $langs->trans(
"ConfirmOuting");
4239 $formquestion = array();
4244 && $object->is_last_in_cycle()
4245 && $usercanunvalidate
4247 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $label, $text,
'confirm_situationout', $formquestion,
"yes", 1);
4252 if ($action ==
'valid') {
4254 $objectref = substr($object->ref, 1, 4);
4255 if ($objectref ==
'PROV') {
4256 $savdate = $object->date;
4259 $object->date_lim_reglement = $object->calculate_date_lim_reglement();
4261 $numref = $object->getNextNumRef($soc);
4264 $numref = $object->ref;
4267 $text = $langs->trans(
'ConfirmValidateBill', $numref);
4268 if (isModEnabled(
'notification')) {
4269 require_once DOL_DOCUMENT_ROOT.
'/core/class/notify.class.php';
4270 $notify =
new Notify($db);
4272 $text .= $notify->confirmMessage(
'BILL_VALIDATE', $object->socid, $object);
4274 $formquestion = array();
4277 $qualified_for_stock_change = 0;
4279 $qualified_for_stock_change = $object->hasProductsOrServices(2);
4281 $qualified_for_stock_change = $object->hasProductsOrServices(1);
4284 if ($qualified_for_stock_change) {
4285 $langs->load(
"stocks");
4286 require_once DOL_DOCUMENT_ROOT.
'/product/class/html.formproduct.class.php';
4287 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
4290 $warehouse_array = $warehouse->list_array();
4291 if (count($warehouse_array) == 1) {
4292 $label = $object->type ==
Facture::TYPE_CREDIT_NOTE ? $langs->trans(
"WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans(
"WarehouseForStockDecrease", current($warehouse_array));
4293 $value =
'<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).
'">';
4295 $label = $object->type ==
Facture::TYPE_CREDIT_NOTE ? $langs->trans(
"SelectWarehouseForStockIncrease") : $langs->trans(
"SelectWarehouseForStockDecrease");
4296 $value = $formproduct->selectWarehouses(
GETPOST(
'idwarehouse') ?
GETPOST(
'idwarehouse') :
'ifone',
'idwarehouse',
'', 1);
4298 $formquestion = array(
4304 array(
'type' =>
'other',
'name' =>
'idwarehouse',
'label' => $label,
'value' => $value));
4308 $text .=
'<br>'.img_warning().
' '.$langs->trans(
"ErrorInvoiceOfThisTypeMustBePositive");
4313 foreach ($object->lines as $line) {
4314 $res = $line->fetch_product();
4316 if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end))) {
4322 if ($nbMandated > 0) {
4323 $text .=
'<div><span class="clearboth nowraponall warning">'.$langs->trans(
"mandatoryPeriodNeedTobeSetMsgValidate").
'</span></div>';
4327 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.$object->id, $langs->trans(
'ValidateBill'), $text,
'confirm_valid', $formquestion, (($object->type !=
Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) ?
"no" :
"yes"), 2);
4331 if ($action ==
'modif') {
4332 $text = $langs->trans(
'ConfirmUnvalidateBill', $object->ref);
4333 $formquestion = array();
4336 $qualified_for_stock_change = 0;
4338 $qualified_for_stock_change = $object->hasProductsOrServices(2);
4340 $qualified_for_stock_change = $object->hasProductsOrServices(1);
4343 if ($qualified_for_stock_change) {
4344 $langs->load(
"stocks");
4345 require_once DOL_DOCUMENT_ROOT.
'/product/class/html.formproduct.class.php';
4346 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
4349 $warehouse_array = $warehouse->list_array();
4350 if (count($warehouse_array) == 1) {
4351 $label = $object->type ==
Facture::TYPE_CREDIT_NOTE ? $langs->trans(
"WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans(
"WarehouseForStockIncrease", current($warehouse_array));
4352 $value =
'<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).
'">';
4354 $label = $object->type ==
Facture::TYPE_CREDIT_NOTE ? $langs->trans(
"SelectWarehouseForStockDecrease") : $langs->trans(
"SelectWarehouseForStockIncrease");
4355 $value = $formproduct->selectWarehouses(
GETPOST(
'idwarehouse') ?
GETPOST(
'idwarehouse') :
'ifone',
'idwarehouse',
'', 1);
4357 $formquestion = array(
4363 array(
'type' =>
'other',
'name' =>
'idwarehouse',
'label' => $label,
'value' => $value));
4367 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.$object->id, $langs->trans(
'UnvalidateBill'), $text,
'confirm_modif', $formquestion,
"yes", 1);
4371 if ($action ==
'paid' && ($resteapayer <= 0 || (
getDolGlobalString(
'INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') && $resteapayer == $object->total_ttc))) {
4372 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.$object->id, $langs->trans(
'ClassifyPaid'), $langs->trans(
'ConfirmClassifyPaidBill', $object->ref),
'confirm_paid',
'',
"yes", 1);
4374 if ($action ==
'paid' && $resteapayer > 0 && (!
getDolGlobalString(
'INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') || $resteapayer != $object->total_ttc)) {
4378 $close[$i][
'code'] =
'discount_vat';
4380 $close[$i][
'code'] =
'badcustomer';
4382 $close[$i][
'code'] =
'bankcharge';
4384 $close[$i][
'code'] =
'withholdingtax';
4386 $close[$i][
'code'] =
'other';
4390 $close[$i][
'label'] = $langs->trans(
"HelpEscompte").
'<br><br>'.$langs->trans(
"ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
4392 $close[$i][
'label'] = $langs->trans(
"ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
4394 $close[$i][
'label'] = $langs->trans(
"ConfirmClassifyPaidPartiallyReasonBankChargeDesc");
4396 $close[$i][
'label'] = $langs->trans(
"ConfirmClassifyPaidPartiallyReasonWithholdingTaxDesc");
4398 $close[$i][
'label'] = $langs->trans(
"Other");
4402 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans(
"Currency".$conf->currency)), $close[$i][
'label'], 1);
4404 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans(
"Currency".$conf->currency)), $close[$i][
'label'], 1);
4406 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonBankCharge", $resteapayer, $langs->trans(
"Currency".$conf->currency)), $close[$i][
'label'], 1);
4408 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonWithholdingTax"), $close[$i][
'label'], 1);
4410 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"Other"), $close[$i][
'label'], 1);
4413 foreach ($close as $key => $val) {
4414 $arrayreasons[$close[$key][
'code']] = $close[$key][
'reason'];
4418 $formquestion = array(
'text' => $langs->trans(
"ConfirmClassifyPaidPartiallyQuestion"), array(
'type' =>
'radio',
'name' =>
'close_code',
'label' => $langs->trans(
"Reason"),
'values' => $arrayreasons), array(
'type' =>
'text',
'name' =>
'close_note',
'label' => $langs->trans(
"Comment"),
'value' =>
'',
'morecss' =>
'minwidth300'));
4420 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.$object->id, $langs->trans(
'ClassifyPaid'), $langs->trans(
'ConfirmClassifyPaidPartially', $object->ref),
'confirm_paid_partially', $formquestion,
"yes", 1, 380, 600);
4424 if ($action ==
'canceled') {
4427 if ($objectidnext) {
4428 $facturereplacement =
new Facture($db);
4429 $facturereplacement->fetch($objectidnext);
4430 $statusreplacement = $facturereplacement->statut;
4432 if ($objectidnext && $statusreplacement == 0) {
4433 print
'<div class="error">'.$langs->trans(
"ErrorCantCancelIfReplacementInvoiceNotValidated").
'</div>';
4436 $close[1][
'code'] =
'badcustomer';
4437 $close[2][
'code'] =
'abandon';
4439 $close[1][
'label'] = $langs->trans(
"ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
4440 $close[2][
'label'] = $langs->trans(
"ConfirmClassifyAbandonReasonOtherDesc");
4442 $close[1][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close[1][
'label'], 1);
4443 $close[2][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyAbandonReasonOther"), $close[2][
'label'], 1);
4445 $arrayreasons[$close[1][
'code']] = $close[1][
'reason'];
4446 $arrayreasons[$close[2][
'code']] = $close[2][
'reason'];
4449 $formquestion = array(
'text' => $langs->trans(
"ConfirmCancelBillQuestion"), array(
'type' =>
'radio',
'name' =>
'close_code',
'label' => $langs->trans(
"Reason"),
'values' => $arrayreasons), array(
'type' =>
'text',
'name' =>
'close_note',
'label' => $langs->trans(
"Comment"),
'value' =>
'',
'morecss' =>
'minwidth300'));
4451 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $langs->trans(
'CancelBill'), $langs->trans(
'ConfirmCancelBill', $object->ref),
'confirm_canceled', $formquestion,
"yes", 1, 270);
4455 if ($action ==
'deletepayment') {
4456 $payment_id =
GETPOST(
'paiement_id');
4457 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?id='.$object->id.
'&paiement_id='.$payment_id, $langs->trans(
'DeletePayment'), $langs->trans(
'ConfirmDeletePayment'),
'confirm_delete_paiement',
'',
'no', 1);
4461 if ($action ==
'ask_deleteline') {
4462 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.$object->id.
'&lineid='.$lineid, $langs->trans(
'DeleteProductLine'), $langs->trans(
'ConfirmDeleteProductLine'),
'confirm_deleteline',
'',
'no', 1);
4466 if ($action ==
'clone') {
4467 $filter =
'(s.client:IN:1,2,3)';
4469 $formquestion = array(
4470 array(
'type' =>
'other',
'name' =>
'socid',
'label' => $langs->trans(
"SelectThirdParty"),
'value' => $form->select_company($object->socid,
'socid', $filter, 1)),
4471 array(
'type' =>
'date',
'name' =>
'newdate',
'label' => $langs->trans(
"Date"),
'value' =>
dol_now())
4474 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.$object->id, $langs->trans(
'ToClone'), $langs->trans(
'ConfirmCloneInvoice', $object->ref),
'confirm_clone', $formquestion,
'yes', 1, 250);
4477 if ($action ==
"remove_file_comfirm") {
4478 $file =
GETPOST(
'file',
'alpha');
4480 $formconfirm = $form->formconfirm(
4481 $_SERVER[
"PHP_SELF"].
'?facid='.$object->id.
'&file='.urlencode($file),
4482 $langs->trans(
'DeleteFileHeader'),
4483 $langs->trans(
'DeleteFileText').
"<br><br>".$file,
4492 $parameters = array(
'formConfirm' => $formconfirm,
'lineid' => $lineid,
'remainingtopay' => &$resteapayer);
4493 $reshook = $hookmanager->executeHooks(
'formConfirm', $parameters, $object, $action);
4494 if (empty($reshook)) {
4495 $formconfirm .= $hookmanager->resPrint;
4496 } elseif ($reshook > 0) {
4497 $formconfirm = $hookmanager->resPrint;
4505 $linkback =
'<a href="'.DOL_URL_ROOT.
'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ?
'&socid='.$socid :
'').
'">'.$langs->trans(
"BackToList").
'</a>';
4507 $morehtmlref =
'<div class="refidno">';
4509 if ($object->status == $object::STATUS_DRAFT && !$mysoc->isInEEC() &&
getDolGlobalString(
'INVOICE_ALLOW_FREE_REF')) {
4510 $morehtmlref .= $form->editfieldkey(
"Ref",
'ref', $object->ref, $object, $usercancreate,
'string',
'', 0, 1);
4511 $morehtmlref .= $form->editfieldval(
"Ref",
'ref', $object->ref, $object, $usercancreate,
'string',
'',
null,
null,
'', 1);
4512 $morehtmlref .=
'<br>';
4515 $morehtmlref .= $form->editfieldkey(
"RefCustomer",
'ref_client', $object->ref_client, $object, $usercancreate,
'string',
'', 0, 1);
4516 $morehtmlref .= $form->editfieldval(
"RefCustomer",
'ref_client', $object->ref_client, $object, $usercancreate,
'string'.(isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ?
':' .
getDolGlobalString(
'THIRDPARTY_REF_INPUT_SIZE') :
''),
'', null, null,
'', 1);
4518 $morehtmlref .=
'<br>'.$object->thirdparty->getNomUrl(1,
'customer');
4520 $morehtmlref .=
' (<a href="'.DOL_URL_ROOT.
'/compta/facture/list.php?socid='.$object->thirdparty->id.
'&search_societe='.urlencode($object->thirdparty->name).
'">'.$langs->trans(
"OtherBills").
'</a>)';
4523 if (isModEnabled(
'project')) {
4524 $langs->load(
"projects");
4525 $morehtmlref .=
'<br>';
4526 if ($usercancreate) {
4527 $morehtmlref .=
img_picto($langs->trans(
"Project"),
'project',
'class="pictofixedwidth"');
4528 if ($action !=
'classify') {
4529 $morehtmlref .=
'<a class="editfielda" href="'.$_SERVER[
'PHP_SELF'].
'?action=classify&token='.newToken().
'&id='.$object->id.
'">'.
img_edit($langs->transnoentitiesnoconv(
'SetProject')).
'</a> ';
4531 $morehtmlref .= $form->form_project($_SERVER[
'PHP_SELF'].
'?id='.$object->id, $object->socid, $object->fk_project, ($action ==
'classify' ?
'projectid' :
'none'), 0, 0, 0, 1,
'',
'maxwidth300');
4533 if (!empty($object->fk_project)) {
4535 $proj->fetch($object->fk_project);
4536 $morehtmlref .= $proj->getNomUrl(1);
4538 $morehtmlref .=
'<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).
'</span>';
4543 $morehtmlref .=
'</div>';
4545 $object->totalpaid = $totalpaid;
4547 dol_banner_tab($object,
'ref', $linkback, 1,
'ref',
'ref', $morehtmlref,
'', 0,
'',
'');
4550 $parameters = array();
4552 $reshook = $hookmanager->executeHooks(
'tabContentViewInvoice', $parameters, $object, $action);
4553 if (empty($reshook)) {
4554 print
'<div class="fichecenter">';
4555 print
'<div class="fichehalfleft">';
4556 print
'<div class="underbanner clearboth"></div>';
4558 print
'<table class="border centpercent tableforfield">';
4561 print
'<tr><td class="titlefield fieldname_type">'.$langs->trans(
'Type').
'</td><td class="valuefield fieldname_type">';
4562 print $object->getLibType(2);
4563 if ($object->subtype > 0) {
4564 print
' '.$object->getSubtypeLabel(
'facture');
4566 if ($object->module_source) {
4567 print
' <span class="opacitymediumbycolor paddingleft">('.$langs->trans(
"POS").
' '.
dol_escape_htmltag(ucfirst($object->module_source)).
' - '.$langs->trans(
"Terminal").
' '.
dol_escape_htmltag($object->pos_source).
')</span>';
4570 $facreplaced =
new Facture($db);
4571 $facreplaced->fetch($object->fk_facture_source);
4572 print
' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities(
"ReplaceInvoice", $facreplaced->getNomUrl(1,
'', 32)).
'</span>';
4576 $facusing->fetch($object->fk_facture_source);
4577 print
' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities(
"CorrectInvoice", $facusing->getNomUrl(1,
'', 32)).
'</span>';
4580 $facidavoir = $object->getListIdAvoirFromInvoice();
4581 if (count($facidavoir) > 0) {
4582 print
' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities(
"InvoiceHasAvoir");
4584 foreach ($facidavoir as $id) {
4591 $facavoir->fetch($id);
4592 print $facavoir->getNomUrl(1,
'', 32);
4596 if ($objectidnext > 0) {
4597 $facthatreplace =
new Facture($db);
4598 $facthatreplace->fetch($objectidnext);
4599 print
' <span class="opacitymediumbycolor paddingleft">'.str_replace(
'{s1}', $facthatreplace->getNomUrl(1), $langs->transnoentities(
"ReplacedByInvoice",
'{s1}')).
'</span>';
4604 $result = $discount->fetch(0, $object->id);
4606 print
' <span class="opacitymediumbycolor paddingleft">';
4607 $s = $langs->trans(
"CreditNoteConvertedIntoDiscount",
'{s1}',
'{s2}');
4608 $s = str_replace(
'{s1}', $object->getLibType(0), $s);
4609 $s = str_replace(
'{s2}', $discount->getNomUrl(1,
'discount'), $s);
4611 print
'</span><br>';
4615 if ($object->fk_fac_rec_source > 0) {
4617 $result = $tmptemplate->fetch($object->fk_fac_rec_source);
4619 print
' <span class="opacitymediumbycolor paddingleft">';
4620 $s = $langs->transnoentities(
"GeneratedFromTemplate",
'{s1}');
4621 $s = str_replace(
'{s1}', $tmptemplate->getNomUrl(1,
'', 32), $s);
4629 print
'<!-- Discounts -->'.
"\n";
4630 print
'<tr><td>'.$langs->trans(
'DiscountStillRemaining').
'</td>';
4634 $backtopage = $_SERVER[
"PHP_SELF"].
'?facid='.$object->id;
4635 include DOL_DOCUMENT_ROOT.
'/core/tpl/object_discounts.tpl.php';
4640 print
'<table class="nobordernopadding centpercent"><tr><td>';
4641 print $langs->trans(
'DateInvoice');
4643 if ($action !=
'editinvoicedate' && $object->status == $object::STATUS_DRAFT && $usercancreate && !
getDolGlobalString(
'FAC_FORCE_DATE_VALIDATION')) {
4644 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editinvoicedate&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'SetDate'), 1).
'</a></td>';
4646 print
'</tr></table>';
4649 if ($action ==
'editinvoicedate') {
4650 $form->form_date($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $object->date,
'invoicedate');
4652 print
'<span class="valuedate">'.dol_print_date($object->date,
'day').
'</span>';
4661 print
'<table class="nobordernopadding centpercent"><tr><td>';
4662 print $langs->trans(
'DatePointOfTax');
4664 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editdate_pointoftax&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'SetDate'), 1).
'</a></td>';
4665 print
'</tr></table>';
4667 if ($action ==
'editdate_pointoftax') {
4668 $form->form_date($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $object->date_pointoftax,
'date_pointoftax');
4670 print
'<span class="valuedate">'.dol_print_date($object->date_pointoftax,
'day').
'</span>';
4677 print
'<table class="nobordernopadding centpercent"><tr><td>';
4678 print $langs->trans(
'PaymentConditionsShort');
4681 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editconditions&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'SetConditions'), 1).
'</a></td>';
4683 print
'</tr></table>';
4686 if ($action ==
'editconditions') {
4687 $form->form_conditions_reglement($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $object->cond_reglement_id,
'cond_reglement_id');
4689 $form->form_conditions_reglement($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $object->cond_reglement_id,
'none');
4698 print
'<table class="nobordernopadding centpercent"><tr><td>';
4699 print $langs->trans(
'DateMaxPayment');
4702 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editpaymentterm&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'SetDate'), 1).
'</a></td>';
4704 print
'</tr></table>';
4707 if ($action ==
'editpaymentterm') {
4708 $form->form_date($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $object->date_lim_reglement,
'paymentterm');
4710 print
'<span class="valuedate">'.dol_print_date($object->date_lim_reglement,
'day').
'</span>';
4711 if ($object->hasDelay()) {
4722 print
'<table class="nobordernopadding centpercent"><tr><td>';
4723 print $langs->trans(
'PaymentMode');
4725 if ($action !=
'editmode' && $usercancreate) {
4726 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editmode&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'SetMode'), 1).
'</a></td>';
4728 print
'</tr></table>';
4730 if ($action ==
'editmode') {
4731 $form->form_modes_reglement($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $object->mode_reglement_id,
'mode_reglement_id',
'CRDT', 1, 1);
4733 $form->form_modes_reglement($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $object->mode_reglement_id,
'none',
'CRDT');
4738 if (isModEnabled(
'multicurrency')) {
4742 print
'<table class="nobordernopadding centpercent"><tr><td>';
4743 print $form->editfieldkey(
'Currency',
'multicurrency_code',
'', $object, 0);
4745 if ($usercancreate && $action !=
'editmulticurrencycode' && $object->status == $object::STATUS_DRAFT) {
4746 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editmulticurrencycode&token='.newToken().
'&id='.$object->id.
'">'.
img_edit($langs->transnoentitiesnoconv(
'SetMultiCurrencyCode'), 1).
'</a></td>';
4748 print
'</tr></table>';
4750 $htmlname = (($usercancreate && $action ==
'editmulticurrencycode') ?
'multicurrency_code' :
'none');
4751 $form->form_multicurrency_code($_SERVER[
'PHP_SELF'].
'?id='.$object->id, $object->multicurrency_code, $htmlname);
4755 if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
4758 print
'<table class="nobordernopadding" width="100%"><tr><td>';
4759 print $form->editfieldkey(
'CurrencyRate',
'multicurrency_tx',
'', $object, 0);
4761 if ($usercancreate && $action !=
'editmulticurrencyrate' && $object->status == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
4762 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editmulticurrencyrate&token='.newToken().
'&id='.$object->id.
'">'.
img_edit($langs->transnoentitiesnoconv(
'SetMultiCurrencyCode'), 1).
'</a></td>';
4764 print
'</tr></table>';
4766 if ($action ==
'editmulticurrencyrate' || $action ==
'actualizemulticurrencyrate') {
4767 if ($action ==
'actualizemulticurrencyrate') {
4770 $form->form_multicurrency_rate($_SERVER[
'PHP_SELF'].
'?id='.$object->id, $object->multicurrency_tx, ($usercancreate ?
'multicurrency_tx' :
'none'), $object->multicurrency_code);
4772 $form->form_multicurrency_rate($_SERVER[
'PHP_SELF'].
'?id='.$object->id, $object->multicurrency_tx,
'none', $object->multicurrency_code);
4773 if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
4774 print
'<div class="inline-block"> ';
4775 print
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$object->id.
'&action=actualizemulticurrencyrate">'.$langs->trans(
"ActualizeCurrency").
'</a>';
4784 if (isModEnabled(
"banque")) {
4785 print
'<tr><td class="nowrap">';
4786 print
'<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
4787 print $langs->trans(
'BankAccount');
4789 if (($action !=
'editbankaccount') && $usercancreate) {
4790 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editbankaccount&token='.newToken().
'&id='.$object->id.
'">'.
img_edit($langs->trans(
'SetBankAccount'), 1).
'</a></td>';
4792 print
'</tr></table>';
4794 if ($action ==
'editbankaccount') {
4795 $form->formSelectAccount($_SERVER[
'PHP_SELF'].
'?id='.$object->id, $object->fk_account,
'fk_account', 1);
4797 $form->formSelectAccount($_SERVER[
'PHP_SELF'].
'?id='.$object->id, $object->fk_account,
'none');
4804 if (isModEnabled(
'incoterm')) {
4806 print
'<table class="nobordernopadding centpercent"><tr><td>';
4807 print $langs->trans(
'IncotermLabel');
4808 print
'<td><td class="right">';
4809 if ($usercancreate) {
4810 print
'<a class="editfielda" href="'.DOL_URL_ROOT.
'/compta/facture/card.php?facid='.$object->id.
'&action=editincoterm&token='.newToken().
'">'.
img_edit().
'</a>';
4814 print
'</td></tr></table>';
4817 if ($action !=
'editincoterm') {
4818 print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
4820 print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms :
''), (!empty($object->location_incoterms) ? $object->location_incoterms :
''), $_SERVER[
'PHP_SELF'].
'?id='.$object->id);
4827 if (!empty($object->retained_warranty) ||
getDolGlobalString(
'INVOICE_USE_RETAINED_WARRANTY')) {
4828 $displayWarranty =
true;
4829 if (!in_array($object->type, $retainedWarrantyInvoiceAvailableType) && empty($object->retained_warranty)) {
4830 $displayWarranty =
false;
4833 if ($displayWarranty) {
4835 print
'<tr class="retained-warranty-lines" ><td>';
4836 print
'<table id="retained-warranty-table" class="nobordernopadding centpercent"><tr><td>';
4837 print $langs->trans(
'RetainedWarranty');
4839 if ($action !=
'editretainedwarranty' && $user->hasRight(
'facture',
'creer') && $object->statut ==
Facture::STATUS_DRAFT) {
4840 print
'<td align="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editretainedwarranty&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'setretainedwarranty'), 1).
'</a></td>';
4843 print
'</tr></table>';
4846 print
'<form id="retained-warranty-form" method="POST" action="'.$_SERVER[
'PHP_SELF'].
'?facid='.$object->id.
'">';
4847 print
'<input type="hidden" name="action" value="setretainedwarranty">';
4848 print
'<input type="hidden" name="token" value="'.newToken().
'">';
4849 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
4850 print
'<input name="retained_warranty" type="number" step="0.01" min="0" max="100" value="'.$object->retained_warranty.
'" >';
4851 print
'<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans(
"Modify").
'">';
4854 print
price($object->retained_warranty).
'%';
4859 print
'<tr class="retained-warranty-lines" ><td>';
4860 print
'<table id="retained-warranty-cond-reglement-table" class="nobordernopadding" width="100%"><tr><td>';
4861 print $langs->trans(
'PaymentConditionsShortRetainedWarranty');
4863 if ($action !=
'editretainedwarrantypaymentterms' && $user->hasRight(
'facture',
'creer') && $object->statut ==
Facture::STATUS_DRAFT) {
4864 print
'<td align="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editretainedwarrantypaymentterms&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'setPaymentConditionsShortRetainedWarranty'), 1).
'</a></td>';
4867 print
'</tr></table>';
4869 $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime(
'-1 years', $object->date_lim_reglement);
4870 if ($object->date > $defaultDate) {
4871 $defaultDate = $object->date;
4876 print
'<form method="POST" action="'.$_SERVER[
'PHP_SELF'].
'?facid='.$object->id.
'">';
4877 print
'<input type="hidden" name="action" value="setretainedwarrantyconditions">';
4878 print
'<input type="hidden" name="token" value="'.newToken().
'">';
4879 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
4880 $retained_warranty_fk_cond_reglement =
GETPOST(
'retained_warranty_fk_cond_reglement',
'int');
4881 $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $object->retained_warranty_fk_cond_reglement;
4882 $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
4883 print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement,
'retained_warranty_fk_cond_reglement', -1, 1);
4884 print
'<input type="submit" class="button valignmiddle" value="'.$langs->trans(
"Modify").
'">';
4887 $form->form_conditions_reglement($_SERVER[
'PHP_SELF'].
'?facid='.$object->id, $object->retained_warranty_fk_cond_reglement,
'none');
4888 if (!$displayWarranty) {
4889 print
img_picto($langs->trans(
'RetainedWarrantyNeed100Percent'),
'warning.png',
'class="pictowarning valignmiddle" ');
4895 print
'<tr class="retained-warranty-lines" ><td>';
4896 print
'<table id="retained-warranty-date-limit-table" class="nobordernopadding" width="100%"><tr><td>';
4897 print $langs->trans(
'RetainedWarrantyDateLimit');
4899 if ($action !=
'editretainedwarrantydatelimit' && $user->hasRight(
'facture',
'creer') && $object->statut ==
Facture::STATUS_DRAFT) {
4900 print
'<td align="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editretainedwarrantydatelimit&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'setretainedwarrantyDateLimit'), 1).
'</a></td>';
4903 print
'</tr></table>';
4905 $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime(
'-1 years', $object->date_lim_reglement);
4906 if ($object->date > $defaultDate) {
4907 $defaultDate = $object->date;
4912 print
'<form method="POST" action="'.$_SERVER[
'PHP_SELF'].
'?facid='.$object->id.
'">';
4913 print
'<input type="hidden" name="action" value="setretainedwarrantydatelimit">';
4914 print
'<input type="hidden" name="token" value="'.newToken().
'">';
4915 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
4916 print
'<input name="retained_warranty_date_limit" type="date" step="1" min="'.dol_print_date($object->date,
'%Y-%m-%d').
'" value="'.
dol_print_date($defaultDate,
'%Y-%m-%d').
'" >';
4917 print
'<input type="submit" class="button valignmiddle" value="'.$langs->trans(
"Modify").
'">';
4920 print
dol_print_date($object->retained_warranty_date_limit,
'day');
4929 include DOL_DOCUMENT_ROOT.
'/core/tpl/extrafields_view.tpl.php';
4934 print
'<div class="fichehalfright">';
4936 print
'<!-- amounts -->'.
"\n";
4937 print
'<div class="underbanner clearboth"></div>'.
"\n";
4939 print
'<table class="border tableforfield centpercent">';
4942 if (
getDolGlobalString(
'INVOICE_POSITIVE_CREDIT_NOTE_SCREEN') && $object->type == $object::TYPE_CREDIT_NOTE) {
4947 print
'<td class="titlefieldmiddle">' . $langs->trans(
'AmountHT') .
'</td>';
4948 print
'<td class="nowrap amountcard right">' .
price($sign * $object->total_ht,
'', $langs, 0, -1, -1, $conf->currency) .
'</td>';
4949 if (isModEnabled(
"multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
4951 print
'<td class="nowrap amountcard right">' .
price($sign * $object->multicurrency_total_ht,
'', $langs, 0, -1, -1, $object->multicurrency_code) .
'</td>';
4957 print
'<td class="titlefieldmiddle">' . $langs->trans(
'AmountVAT') .
'</td>';
4958 print
'<td class="nowrap amountcard right">' .
price($sign * $object->total_tva,
'', $langs, 0, -1, -1, $conf->currency) .
'</td>';
4959 if (isModEnabled(
"multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
4961 print
'<td class="nowrap amountcard right">' .
price($sign * $object->multicurrency_total_tva,
'', $langs, 0, -1, -1, $object->multicurrency_code) .
'</td>';
4966 if (($mysoc->localtax1_assuj ==
"1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) {
4968 print
'<td class="titlefieldmiddle">' . $langs->transcountry(
"AmountLT1", $mysoc->country_code) .
'</td>';
4969 print
'<td class="nowrap amountcard right">' .
price($sign * $object->total_localtax1,
'', $langs, 0, -1, -1, $conf->currency) .
'</td>';
4970 if (isModEnabled(
"multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
4971 $object->multicurrency_total_localtax1 =
price2num($object->total_localtax1 * $object->multicurrency_tx,
'MT');
4973 print
'<td class="nowrap amountcard right">' .
price($sign * $object->multicurrency_total_localtax1,
'', $langs, 0, -1, -1, $object->multicurrency_code) .
'</td>';
4978 if (($mysoc->localtax2_assuj ==
"1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) {
4980 print
'<td>' . $langs->transcountry(
"AmountLT2", $mysoc->country_code) .
'</td>';
4981 print
'<td class="nowrap amountcard right">' .
price($sign * $object->total_localtax2,
'', $langs, 0, -1, -1, $conf->currency) .
'</td>';
4982 if (isModEnabled(
"multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
4983 $object->multicurrency_total_localtax2 =
price2num($object->total_localtax2 * $object->multicurrency_tx,
'MT');
4985 print
'<td class="nowrap amountcard right">' .
price($sign * $object->multicurrency_total_localtax2,
'', $langs, 0, -1, -1, $object->multicurrency_code) .
'</td>';
4991 if ($selleruserevenustamp) {
4992 print
'<tr><td class="titlefieldmiddle">';
4993 print
'<table class="nobordernopadding centpercent"><tr><td>';
4994 print $langs->trans(
'RevenueStamp');
4996 if ($action !=
'editrevenuestamp' && $object->status == $object::STATUS_DRAFT && $usercancreate) {
4997 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editrevenuestamp&token='.newToken().
'&facid='.$object->id.
'">'.
img_edit($langs->trans(
'SetRevenuStamp'), 1).
'</a></td>';
4999 print
'</tr></table>';
5000 print
'</td><td class="nowrap amountcard right">';
5001 if ($action ==
'editrevenuestamp') {
5002 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?id='.$object->id.
'" method="post">';
5003 print
'<input type="hidden" name="token" value="'.newToken().
'">';
5004 print
'<input type="hidden" name="action" value="setrevenuestamp">';
5005 print
'<input type="hidden" name="revenuestamp" id="revenuestamp_val" value="'.price2num($object->revenuestamp).
'">';
5006 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
5007 print $formother->select_revenue_stamp(
'',
'revenuestamp_type', $mysoc->country_code);
5008 print
' → <span id="revenuestamp_span"></span>';
5009 print
' <input type="submit" class="button buttongen button-save small" value="'.$langs->trans(
'Modify').
'">';
5012 $(document).ready(function(){
5013 js_recalculate_revenuestamp();
5014 $('select[name=revenuestamp_type]').on('change',function(){
5015 js_recalculate_revenuestamp();
5018 function js_recalculate_revenuestamp(){
5019 var valselected = $('select[name=revenuestamp_type]').val();
5020 console.log('Calculate revenue stamp from '+valselected);
5022 if (valselected.indexOf('%') == -1)
5024 revenue = valselected;
5028 var revenue_type = parseFloat(valselected);
5029 var amount_net = ".round($object->total_ht, 2).
";
5030 revenue = revenue_type * amount_net / 100;
5031 revenue = revenue.toFixed(2);
5033 $('#revenuestamp_val').val(revenue);
5034 $('#revenuestamp_span').html(revenue);
5038 print
price($object->revenuestamp, 1,
'', 1, -1, -1, $conf->currency);
5045 print
'<td>' . $langs->trans(
'AmountTTC') .
'</td>';
5046 print
'<td class="nowrap amountcard right">' .
price($sign * $object->total_ttc,
'', $langs, 0, -1, -1, $conf->currency) .
'</td>';
5047 if (isModEnabled(
"multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
5049 print
'<td class="nowrap amountcard right">' .
price($sign * $object->multicurrency_total_ttc,
'', $langs, 0, -1, -1, $object->multicurrency_code) .
'</td>';
5057 if (isModEnabled(
'project')) {
5060 if (isModEnabled(
"banque")) {
5064 if ($mysoc->localtax1_assuj ==
"1" || $object->total_localtax1 != 0) {
5067 if ($mysoc->localtax2_assuj ==
"1" || $object->total_localtax2 != 0) {
5070 if ($selleruserevenustamp) {
5073 if (isModEnabled(
'multicurrency')) {
5076 if (isModEnabled(
'incoterm')) {
5081 if (($object->situation_cycle_ref > 0) &&
getDolGlobalString(
'INVOICE_USE_SITUATION')) {
5082 print
'<!-- List of situation invoices -->';
5083 print
'<table class="noborder situationstable" width="100%">';
5085 print
'<tr class="liste_titre">';
5086 print
'<td>'.$langs->trans(
'ListOfSituationInvoices').
'</td>';
5088 print
'<td class="center">'.$langs->trans(
'Situation').
'</td>';
5089 if (isModEnabled(
"banque")) {
5090 print
'<td class="right"></td>';
5092 print
'<td class="right">'.$langs->trans(
'AmountHT').
'</td>';
5093 print
'<td class="right">'.$langs->trans(
'AmountTTC').
'</td>';
5094 print
'<td width="18"> </td>';
5097 $total_prev_ht = $total_prev_ttc = 0;
5098 $total_global_ht = $total_global_ttc = 0;
5100 if (count($object->tab_previous_situation_invoice) > 0) {
5103 $current_situation_counter = array();
5104 foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
5105 $tmptotalpaidforthisinvoice = $prev_invoice->getSommePaiement();
5106 $total_prev_ht += $prev_invoice->total_ht;
5107 $total_prev_ttc += $prev_invoice->total_ttc;
5108 $current_situation_counter[] = (($prev_invoice->type ==
Facture::TYPE_CREDIT_NOTE) ? -1 : 1) * $prev_invoice->situation_counter;
5109 print
'<tr class="oddeven">';
5110 print
'<td>'.$prev_invoice->getNomUrl(1).
'</td>';
5112 print
'<td align="center" >'.(($prev_invoice->type ==
Facture::TYPE_CREDIT_NOTE) ? $langs->trans(
'situationInvoiceShortcode_AS') : $langs->trans(
'situationInvoiceShortcode_S')).$prev_invoice->situation_counter.
'</td>';
5113 if (isModEnabled(
"banque")) {
5114 print
'<td class="right"></td>';
5116 print
'<td class="right"><span class="amount">'.price($prev_invoice->total_ht).
'</span></td>';
5117 print
'<td class="right"><span class="amount">'.price($prev_invoice->total_ttc).
'</span></td>';
5118 print
'<td class="right">'.$prev_invoice->getLibStatut(3, $tmptotalpaidforthisinvoice).
'</td>';
5124 $total_global_ht += $total_prev_ht;
5125 $total_global_ttc += $total_prev_ttc;
5126 $total_global_ht += $object->total_ht;
5127 $total_global_ttc += $object->total_ttc;
5129 print
'<tr class="oddeven">';
5130 print
'<td>'.$object->getNomUrl(1).
'</td>';
5132 print
'<td class="center">'.(($object->type ==
Facture::TYPE_CREDIT_NOTE) ? $langs->trans(
'situationInvoiceShortcode_AS&