50require
'../../main.inc.php';
60require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
61require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
62require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture-rec.class.php';
63require_once DOL_DOCUMENT_ROOT.
'/compta/bank/class/account.class.php';
64require_once DOL_DOCUMENT_ROOT.
'/compta/paiement/class/paiement.class.php';
65require_once DOL_DOCUMENT_ROOT.
'/core/modules/facture/modules_facture.php';
66require_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
67require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
68require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formfile.class.php';
69require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formother.class.php';
70require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formmargin.class.php';
71require_once DOL_DOCUMENT_ROOT.
'/core/lib/invoice.lib.php';
72require_once DOL_DOCUMENT_ROOT.
'/core/lib/functions2.lib.php';
73require_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
75 require_once DOL_DOCUMENT_ROOT.
'/commande/class/commande.class.php';
78 require_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
79 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formprojet.class.php';
81require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
84 require_once DOL_DOCUMENT_ROOT.
'/variants/class/ProductCombination.class.php';
87 require_once DOL_DOCUMENT_ROOT.
'/accountancy/class/accountingjournal.class.php';
91$langs->loadLangs(array(
'bills',
'companies',
'compta',
'products',
'banks',
'main',
'withdrawals'));
93 $langs->load(
'incoterm');
96 $langs->load(
'margins');
100$action =
GETPOST(
'action',
'aZ09');
101$confirm =
GETPOST(
'confirm',
'alpha');
102$cancel =
GETPOST(
'cancel',
'alpha');
103$backtopage =
GETPOST(
'backtopage',
'alpha');
104$backtopageforcancel =
GETPOST(
'backtopageforcancel',
'alpha');
110$origin =
GETPOST(
'origin',
'alpha');
114$ref_client =
GETPOST(
'ref_client',
'alpha');
115$inputReasonId =
GETPOSTINT(
'input_reason_id');
118$selectedLines =
GETPOST(
'toselect',
'array:int');
131$extrafields->fetch_name_optionals_label(
$object->table_element);
134$total_global_ttc = 0;
135$displayWarranty =
false;
136$statusreplacement = 0;
138$price_base_type =
'';
139$array_options = array();
142if ($id > 0 || !empty($ref)) {
143 if ($action !=
'add') {
145 $fetch_situation =
false;
147 $fetch_situation =
true;
149 $ret =
$object->fetch($id, $ref,
'', 0, $fetch_situation);
150 if ($ret > 0 && isset(
$object->fk_project)) {
151 $ret =
$object->fetchProject();
157$hookmanager->initHooks(array(
'invoicecard',
'globalcard'));
160$usercanread = $user->hasRight(
"facture",
"lire");
161$usercancreate = $user->hasRight(
"facture",
"creer");
162$usercanissuepayment = $user->hasRight(
"facture",
"paiement");
163$usercandelete = $user->hasRight(
"facture",
"supprimer") || ($usercancreate && isset(
$object->status) &&
$object->status == $object::STATUS_DRAFT);
164$usercancreatecontract = $user->hasRight(
"contrat",
"creer");
167$usercanvalidate = ((!
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $user->hasRight(
'facture',
'invoice_advance',
'validate')));
168$usercansend = ((!
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $usercanread) || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $user->hasRight(
'facture',
'invoice_advance',
'send')));
169$usercanreopen = ((!
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $user->hasRight(
'facture',
'invoice_advance',
'reopen')));
171 $usercanreopen =
false;
173$usercanunvalidate = ((!
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !empty($usercancreate)) || (
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $user->hasRight(
'facture',
'invoice_advance',
'unvalidate')));
174$usermustrespectpricemin = ((
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && !$user->hasRight(
'produit',
'ignore_price_min_advance')) || !
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS'));
177$usercancreatemargin = $user->hasRight(
'margins',
'creer');
178$usercanreadallmargin = $user->hasRight(
'margins',
'liretous');
179$usercancreatewithdrarequest = $user->hasRight(
'prelevement',
'bons',
'creer');
181$permissionnote = $usercancreate;
182$permissiondellink = $usercancreate;
183$permissiontoedit = $usercancreate;
184$permissiontoadd = $usercancreate;
185$permissiontoeditextra = $usercancreate;
186if (
GETPOST(
'attribute',
'aZ09') && isset($extrafields->attributes[
$object->table_element][
'perms'][
GETPOST(
'attribute',
'aZ09')])) {
188 $permissiontoeditextra =
dol_eval((
string) $extrafields->attributes[
$object->table_element][
'perms'][
GETPOST(
'attribute',
'aZ09')]);
192$retainedWarrantyInvoiceAvailableType = array();
194 $retainedWarrantyInvoiceAvailableType = explode(
'+',
getDolGlobalString(
'INVOICE_USE_RETAINED_WARRANTY'));
199 $socid = $user->socid;
212$parameters = array(
'socid' => $socid);
213$reshook = $hookmanager->executeHooks(
'doActions', $parameters, $object, $action);
215 setEventMessages($hookmanager->error, $hookmanager->errors,
'errors');
218if (empty($reshook)) {
219 $backurlforlist =
dolBuildUrl(DOL_URL_ROOT.
'/compta/facture/list.php');
221 if (empty($backtopage) || ($cancel && empty($id))) {
222 if (empty($backtopage) || ($cancel && strpos($backtopage,
'__ID__'))) {
223 if (empty($id) && (($action !=
'add' && $action !=
'create') || $cancel)) {
224 $backtopage = $backurlforlist;
226 $backtopage =
dolBuildUrl(DOL_URL_ROOT.
'/compta/facture/card.php', [
'id' => ((!empty($id) && $id > 0) ? $id :
'__ID__')]);
232 if (!empty($backtopageforcancel)) {
233 header(
"Location: ".$backtopageforcancel);
235 } elseif (!empty($backtopage)) {
236 header(
"Location: ".$backtopage);
242 include DOL_DOCUMENT_ROOT.
'/core/actions_setnotes.inc.php';
244 include DOL_DOCUMENT_ROOT.
'/core/actions_dellink.inc.php';
246 include DOL_DOCUMENT_ROOT.
'/core/actions_lineupdown.inc.php';
249 if ($action ==
'confirm_clone' && $confirm ==
'yes' && $permissiontoadd) {
251 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'IdThirdParty')),
null,
'errors');
254 '@phan-var-force Facture $objectutil';
257 $objectutil->socid = $socid;
258 $result = $objectutil->createFromClone($user, $id, (
GETPOSTISSET(
'entity') ?
GETPOSTINT(
'entity') : null));
260 $warningMsgLineList = array();
262 foreach ($objectutil->lines as $line) {
263 if (!is_object($line->product)) {
264 $line->fetch_product();
266 if (is_object($line->product) && $line->product->id > 0) {
267 if (empty($line->product->status)) {
268 $warningMsgLineList[$line->id] = $langs->trans(
'WarningLineProductNotToSell', $line->product->ref);
272 if (!empty($warningMsgLineList)) {
273 setEventMessages(
'', $warningMsgLineList,
'warnings');
276 header(
"Location: " . $_SERVER[
'PHP_SELF'] .
'?facid=' . $result);
279 $langs->load(
"errors");
280 setEventMessages($objectutil->error, $objectutil->errors,
'errors');
284 } elseif ($action ==
'reopen' && $usercanreopen) {
288 $result =
$object->setUnpaid($user);
290 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
296 } elseif ($action ==
'confirm_delete' && $confirm ==
'yes' && $usercandelete) {
301 $idwarehouse =
GETPOST(
'idwarehouse');
303 $qualified_for_stock_change = 0;
305 $qualified_for_stock_change =
$object->hasProductsOrServices(2);
307 $qualified_for_stock_change =
$object->hasProductsOrServices(1);
310 $isErasable =
$object->is_erasable();
312 if (($isErasable > 0) || ($usercancreate && $isErasable == 1)) {
314 $result =
$object->delete($user, 0, (
int) $idwarehouse);
316 header(
'Location: '.DOL_URL_ROOT.
'/compta/facture/list.php?restore_lastsearch_values=1');
323 } elseif ($action ==
'confirm_deleteline' && $confirm ==
'yes' && $usercancreate) {
333 $outputlangs = $langs;
339 $newlang =
$object->thirdparty->default_lang;
341 if (!empty($newlang)) {
343 $outputlangs->setDefaultLang($newlang);
344 $outputlangs->load(
'products');
348 $result =
$object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
351 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
358 } elseif ($action ==
'confirm_delete_subtotalline' && $confirm ==
'yes' && $usercancreate) {
363 $result =
$object->deleteSubtotalLine($langs,
GETPOSTINT(
'lineid'), (
bool)
GETPOST(
'deletecorrespondingsubtotalline'));
368 $outputlangs = $langs;
374 $newlang =
$object->thirdparty->default_lang;
376 if (!empty($newlang)) {
378 $outputlangs->setDefaultLang($newlang);
379 $outputlangs->load(
'products');
383 $result =
$object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
386 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
393 } elseif ($action ==
'unlinkdiscount' && $usercancreate) {
396 $result = $discount->fetch(
GETPOSTINT(
"discountid"));
398 if ($result > 0 && $discount->fk_facture ==
$object->id) {
399 $discount->unlink_invoice();
401 if (
$object->paye == 1 && (
float)
$object->getRemainToPay() > 0) {
405 setEventMessages($langs->trans(
"ErrorRecordNotFound"),
null,
'errors');
407 } elseif ($action ==
'valid' && $usercancreate) {
411 if ((preg_match(
'/^[\(]?PROV/i',
$object->ref) || empty(
$object->ref)) &&
418 $last_of_type =
$object->willBeLastOfSameType(
true);
419 if (empty(
$object->date_validation) && !$last_of_type[0]) {
426 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"DatePointOfTax")).
' ('.$langs->trans(
"ForbiddenBySetupRules").
')',
null,
'errors');
434 setEventMessages($langs->trans(
"ErrorInvoiceAvoirMustBeNegative"),
null,
'errors');
443 setEventMessages($langs->trans(
"ErrorInvoiceOfThisTypeMustBePositive"),
null,
'errors');
452 $array_of_total_ht_per_vat_rate = array();
453 $array_of_total_ht_devise_per_vat_rate = array();
454 foreach (
$object->lines as $line) {
456 $vat_src_code_for_line =
'';
457 if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line])) {
458 $array_of_total_ht_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line] = 0;
460 if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line])) {
461 $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line] = 0;
463 $array_of_total_ht_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line] += $line->total_ht;
464 $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.
'_'.$vat_src_code_for_line] += $line->multicurrency_total_ht;
468 foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) {
469 $tmp_total_ht =
price2num($array_of_total_ht_per_vat_rate[$vatrate]);
470 $tmp_total_ht_devise =
price2num($array_of_total_ht_devise_per_vat_rate[$vatrate]);
472 if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) {
473 if (
$object->type == $object::TYPE_DEPOSIT) {
474 $langs->load(
"errors");
476 setEventMessages($langs->trans(
"ErrorLinesCantBeNegativeOnDeposits"),
null,
'errors');
480 $tmpvatratetoshow = explode(
'_', $vatrate);
481 $tmpvatratetoshow[0] = round((
float) $tmpvatratetoshow[0], 2);
483 if ($tmpvatratetoshow[0] != 0) {
484 $langs->load(
"errors");
485 setEventMessages($langs->trans(
"ErrorLinesCantBeNegativeForOneVATRate", (
string) $tmpvatratetoshow[0]),
null,
'errors');
493 } elseif ($action ==
'classin' && $usercancreate) {
499 } elseif ($action ==
'setposinfo' && $usercancreate) {
503 $result =
$object->update($user);
507 } elseif ($action ==
'regeneratepaymentref' && $usercancreate) {
511 include_once DOL_DOCUMENT_ROOT.
'/core/lib/paymentref.lib.php';
513 if ($newpaymentref ==
'') {
514 setEventMessages($langs->trans(
"WarningPaymentRefNotGenerated"),
null,
'warnings');
517 } elseif ($action ==
'setmode' && $usercancreate) {
523 } elseif ($action ==
'setretainedwarrantyconditions' && $usercancreate) {
526 $object->retained_warranty_fk_cond_reglement = 0;
527 $result =
$object->setRetainedWarrantyPaymentTerms(
GETPOSTINT(
'retained_warranty_fk_cond_reglement'));
532 $old_rw_date_lim_reglement =
$object->retained_warranty_date_limit;
533 $new_rw_date_lim_reglement =
$object->calculate_date_lim_reglement(
$object->retained_warranty_fk_cond_reglement);
534 if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) {
535 $object->retained_warranty_date_limit = $new_rw_date_lim_reglement;
540 $result =
$object->update($user);
544 } elseif ($action ==
'setretainedwarranty' && $usercancreate) {
550 } elseif ($action ==
'setretainedwarrantydatelimit' && $usercancreate) {
552 $result =
$object->setRetainedWarrantyDateLimit(
GETPOSTDATE(
'retained_warranty_date_limit'));
556 } elseif ($action ==
'setmulticurrencycode' && $usercancreate) {
557 $result =
$object->setMulticurrencyCode(
GETPOST(
'multicurrency_code',
'alpha'));
558 } elseif ($action ==
'setmulticurrencyrate' && $usercancreate) {
559 if (!in_array(
GETPOSTINT(
'calculation_mode'), array(1, 2))) {
560 $langs->load(
"compta");
561 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"CalculationMode")),
null,
'errors');
562 $action =
'editmulticurrencyrate';
566 } elseif ($action ==
'setinvoicedate' && $usercancreate) {
568 $old_date_lim_reglement =
$object->date_lim_reglement;
570 if (empty($newdate)) {
571 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
572 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.
$id.
'&action=editinvoicedate&token='.
newToken());
577 setEventMessages($langs->trans(
"WarningInvoiceDateInFuture"),
null,
'warnings');
579 setEventMessages($langs->trans(
"WarningInvoiceDateTooFarInFuture"),
null,
'warnings');
584 $new_date_lim_reglement =
$object->calculate_date_lim_reglement();
585 if ($new_date_lim_reglement) {
586 $object->date_lim_reglement = $new_date_lim_reglement;
591 $result =
$object->update($user);
594 $action =
'editinvoicedate';
596 } elseif ($action ==
'setdate_pointoftax' && $usercancreate) {
601 $object->date_pointoftax = $date_pointoftax;
602 $result =
$object->update($user);
606 } elseif ($action ==
'setconditions' && $usercancreate) {
608 $object->cond_reglement_code = 0;
609 $object->cond_reglement_id = 0;
622 $old_date_lim_reglement =
$object->date_lim_reglement;
623 $new_date_lim_reglement =
$object->calculate_date_lim_reglement();
624 if ($new_date_lim_reglement) {
625 $object->date_lim_reglement = $new_date_lim_reglement;
630 $result =
$object->update($user);
642 } elseif ($action ==
'setpaymentterm' && $usercancreate) {
646 $object->date_lim_reglement =
$object->calculate_date_lim_reglement();
647 setEventMessages($langs->trans(
"DatePaymentTermCantBeLowerThanObjectDate"),
null,
'warnings');
649 $result =
$object->update($user);
653 } elseif ($action ==
'setrevenuestamp' && $usercancreate) {
656 $result =
$object->update($user);
664 $outputlangs = $langs;
667 $newlang =
GETPOST(
'lang_id',
'aZ09');
670 $newlang =
$object->thirdparty->default_lang;
672 if (!empty($newlang)) {
674 $outputlangs->setDefaultLang($newlang);
675 $outputlangs->load(
'products');
680 $result =
$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
686 } elseif ($action ==
'set_incoterms' &&
isModEnabled(
'incoterm') && $usercancreate) {
691 } elseif ($action ==
'set_dispute_status' && $usercancreate) {
692 $result =
$object->setStatut(
GETPOSTINT(
'dispute_status'),
null,
'facture',
'FACTURE_MODIFY',
'dispute_status');
696 } elseif ($action ==
'settags' &&
isModEnabled(
'category') && $usercancreate) {
701 } elseif ($action ==
'setbankaccount' && $usercancreate) {
706 } elseif ($action ==
'setremisepercent' && $usercancreate) {
712 } elseif ($action ==
'setabsolutediscount' && $usercancreate) {
724 $usemccompare =
false;
726 if ($discount->fetch($idremise) > 0) {
730 && !empty($discount->multicurrency_code) && !empty(
$object->multicurrency_code)
731 && $discount->multicurrency_code ==
$object->multicurrency_code &&
$object->multicurrency_code !=
$conf->currency);
732 $maxtoabsorb = (float)
price2num($usemccompare ?
$object->getRemainToPay(1) :
$object->getRemainToPay(0),
'MT');
733 $discountamountforcompare = (float)
price2num($usemccompare ? $discount->multicurrency_amount_ttc : $discount->amount_ttc,
'MT');
734 if ($discountamountforcompare > $maxtoabsorb) {
735 if ($maxtoabsorb <= 0) {
738 setEventMessages($langs->trans(
"ErrorDiscountLargerThanRemainToPaySplitItBefore"),
null,
'errors');
741 $depositeur = (float) $discount->amount_ttc;
742 $depositdev = (float) $discount->multicurrency_amount_ttc;
743 if ($usemccompare && $depositdev != 0) {
744 $applydev = $maxtoabsorb;
748 $creditrate = !empty($discount->multicurrency_tx) ? (float) $discount->multicurrency_tx : 0;
749 if ($creditrate > 0) {
750 $applyeur = (float)
price2num($applydev / $creditrate,
'MT');
752 $applyeur = (float)
price2num($applydev / $depositdev * $depositeur,
'MT');
755 $applyeur = $maxtoabsorb;
756 $applydev = ($depositeur != 0 ? (float)
price2num($applyeur / $depositeur * $depositdev,
'MT') : 0);
758 $splitparts = $discount->splitAmount($applyeur, (
float)
price2num($depositeur - $applyeur,
'MT'));
759 $applypart = $splitparts[0];
760 $remainpart = $splitparts[1];
762 if (!empty($discount->multicurrency_code) && $depositdev != 0) {
764 $remaindev = (float)
price2num($depositdev - $applydev,
'MT');
765 $applypart->multicurrency_amount_ttc = $applydev;
766 $applypart->multicurrency_amount_ht =
price2num($applydev / (1 + (
float) $applypart->tva_tx / 100),
'MT');
767 $applypart->multicurrency_amount_tva =
price2num($applydev - (
float) $applypart->multicurrency_amount_ht);
768 $remainpart->multicurrency_amount_ttc = $remaindev;
769 $remainpart->multicurrency_amount_ht =
price2num($remaindev / (1 + (
float) $remainpart->tva_tx / 100),
'MT');
770 $remainpart->multicurrency_amount_tva =
price2num($remaindev - (
float) $remainpart->multicurrency_amount_ht);
772 $discount->fk_facture_source = 0;
773 $discount->fk_invoice_supplier_source = 0;
774 $resdelete = $discount->delete($user);
775 $newidapply = $applypart->create($user);
776 $newidremain = $remainpart->create($user);
777 if ($resdelete > 0 && $newidapply > 0 && $newidremain > 0) {
778 $idremise = $newidapply;
779 $splitappliedmsg =
price($applyeur, 0, $langs, 1, -1, -1,
$conf->currency);
780 $splitremainmsg =
price((
float)
price2num($depositeur - $applyeur,
'MT'), 0, $langs, 1, -1, -1,
$conf->currency);
781 if (!empty($discount->multicurrency_code) && $depositdev != 0) {
782 $splitappliedmsg .=
' / '.price($applydev, 0, $langs, 1, -1, -1, $discount->multicurrency_code);
783 $splitremainmsg .=
' / '.price($remaindev, 0, $langs, 1, -1, -1, $discount->multicurrency_code);
785 setEventMessages($langs->trans(
'DepositSplitAutomaticallyApplied', $splitappliedmsg, $splitremainmsg),
null,
'warnings');
788 setEventMessages($langs->trans(
"Error"),
null,
'errors');
795 $result =
$object->insert_discount($idremise);
799 if ($result > 0 && $usemccompare) {
806 $foreigncredits = 0.0;
807 $companycredits = 0.0;
808 foreach (
$object->lines as $creditline) {
809 if (empty($creditline->fk_remise_except)) {
810 $foreigngoods += (float) $creditline->multicurrency_total_ttc;
812 $foreigncredits -= (float) $creditline->multicurrency_total_ttc;
813 $companycredits -= (float) $creditline->total_ttc;
816 $targetcompany = ((float)
$object->multicurrency_tx > 0 ? ($foreigngoods - $foreigncredits) / (float)
$object->multicurrency_tx : 0) + $companycredits;
817 if ($foreigngoods > 0 && $targetcompany > 0) {
818 $neweffectivetx = (float)
price2num($foreigngoods / $targetcompany,
'CR');
819 if (abs($neweffectivetx - (
float)
$object->multicurrency_tx) >= 0.00000001) {
820 $resrate =
$object->setMulticurrencyRate($neweffectivetx, 1);
825 setEventMessages($langs->trans(
'InvoiceRateRealigned',
price2num($neweffectivetx,
'CR')),
null,
'mesgs');
838 $newremaintopay =
$object->getRemainToPay(0);
839 if ($newremaintopay == 0) {
846 if (
GETPOSTINT(
"remise_id_for_payment") > 0) {
847 require_once DOL_DOCUMENT_ROOT.
'/core/class/discount.class.php';
849 $discount->fetch(
GETPOSTINT(
"remise_id_for_payment"));
856 && !empty($discount->multicurrency_code) && !empty(
$object->multicurrency_code)
857 && $discount->multicurrency_code ==
$object->multicurrency_code &&
$object->multicurrency_code !=
$conf->currency);
858 $remaintopay = $usemccompare ?
$object->getRemainToPay(1) :
$object->getRemainToPay(0);
859 $discountamountforcompare = $usemccompare ? $discount->multicurrency_amount_ttc : $discount->amount_ttc;
860 $discounttolink = $discount;
861 $depositwassplit =
false;
862 $splitappliedmsg =
'';
863 $splitremainmsg =
'';
865 if ((
float) $remaintopay <= 0) {
867 setEventMessages($langs->trans(
"ErrorDiscountLargerThanRemainToPaySplitItBefore"),
null,
'errors');
870 $depositeur = (float) $discount->amount_ttc;
871 $depositdev = (float) $discount->multicurrency_amount_ttc;
872 if ($usemccompare && $depositdev != 0) {
873 $applydev = (float) $remaintopay;
877 $creditrate = !empty($discount->multicurrency_tx) ? (float) $discount->multicurrency_tx : 0;
878 if ($creditrate > 0) {
879 $applyeur = (float)
price2num($applydev / $creditrate,
'MT');
881 $applyeur = (float)
price2num($applydev / $depositdev * $depositeur,
'MT');
884 $applyeur = (float) $remaintopay;
885 $applydev = ($depositeur != 0 ? (float)
price2num($applyeur / $depositeur * $depositdev,
'MT') : 0);
887 $splitparts = $discount->splitAmount($applyeur, (
float)
price2num($depositeur - $applyeur,
'MT'));
888 $applypart = $splitparts[0];
889 $remainpart = $splitparts[1];
891 if (!empty($discount->multicurrency_code) && $depositdev != 0) {
892 $remaindev = (float)
price2num($depositdev - $applydev,
'MT');
893 $applypart->multicurrency_amount_ttc = $applydev;
894 $applypart->multicurrency_amount_ht =
price2num($applydev / (1 + (
float) $applypart->tva_tx / 100),
'MT');
895 $applypart->multicurrency_amount_tva =
price2num($applydev - (
float) $applypart->multicurrency_amount_ht);
896 $remainpart->multicurrency_amount_ttc = $remaindev;
897 $remainpart->multicurrency_amount_ht =
price2num($remaindev / (1 + (
float) $remainpart->tva_tx / 100),
'MT');
898 $remainpart->multicurrency_amount_tva =
price2num($remaindev - (
float) $remainpart->multicurrency_amount_ht);
900 $discount->fk_facture_source = 0;
901 $discount->fk_invoice_supplier_source = 0;
902 $resdelete = $discount->delete($user);
903 $newidapply = $applypart->create($user);
904 $newidremain = $remainpart->create($user);
905 if ($resdelete > 0 && $newidapply > 0 && $newidremain > 0) {
907 $discounttolink->fetch($newidapply);
909 $depositwassplit =
true;
910 $splitappliedmsg =
price($applyeur, 0, $langs, 1, -1, -1,
$conf->currency);
911 $splitremainmsg =
price((
float)
price2num($depositeur - $applyeur,
'MT'), 0, $langs, 1, -1, -1,
$conf->currency);
912 if (!empty($discount->multicurrency_code) && $depositdev != 0) {
913 $splitappliedmsg .=
' / '.price($applydev, 0, $langs, 1, -1, -1, $discount->multicurrency_code);
914 $splitremainmsg .=
' / '.price($remaindev, 0, $langs, 1, -1, -1, $discount->multicurrency_code);
918 setEventMessages($langs->trans(
"Error"),
null,
'errors');
924 $result = $discounttolink->link_to_invoice(0, $id);
927 setEventMessages($discounttolink->error, $discounttolink->errors,
'errors');
937 $newremaintopay = $usemccompare ?
$object->getRemainToPay(1) :
$object->getRemainToPay(0);
938 if ($newremaintopay == 0) {
942 if ($depositwassplit) {
943 setEventMessages($langs->trans(
'DepositSplitAutomaticallyApplied', $splitappliedmsg, $splitremainmsg),
null,
'warnings');
955 $outputlangs = $langs;
958 $newlang =
GETPOST(
'lang_id',
'aZ09');
962 $newlang =
$object->thirdparty->default_lang;
964 if (!empty($newlang)) {
966 $outputlangs->setDefaultLang($newlang);
970 $result =
$object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
975 } elseif ($action ==
'setref' && $usercancreate) {
977 $object->setValueFrom(
'ref',
GETPOST(
'ref'),
'', 0,
'',
'', $user,
'BILL_MODIFY');
981 } elseif ($action ==
'setref_client' && $usercancreate) {
983 $result =
$object->set_ref_client(
GETPOST(
'ref_client',
'alpha'));
987 } elseif ($action ==
'setdemandreason' && $usercancreate) {
988 $result =
$object->setInputReason($inputReasonId);
992 } elseif ($action ==
'confirm_valid' && $confirm ==
'yes' && $usercanvalidate) {
1001 $qualified_for_stock_change = 0;
1003 $qualified_for_stock_change =
$object->hasProductsOrServices(2);
1005 $qualified_for_stock_change =
$object->hasProductsOrServices(1);
1008 if ($qualified_for_stock_change) {
1009 if (!$idwarehouse || $idwarehouse == - 1) {
1011 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
"Warehouse")),
null,
'errors');
1018 $result =
$object->validate($user,
'', $idwarehouse);
1022 $outputlangs = $langs;
1025 $newlang =
GETPOST(
'lang_id',
'aZ09');
1028 $newlang =
$object->thirdparty->default_lang;
1030 if (!empty($newlang)) {
1032 $outputlangs->setDefaultLang($newlang);
1033 $outputlangs->load(
'products');
1039 $result =
$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1046 setEventMessages(
null,
$object->errors,
'errors');
1052 } elseif ($action ==
'confirm_modif' && $usercanunvalidate && !
getDolGlobalString(
'INVOICE_CAN_NEVER_BE_EDITED')) {
1061 $qualified_for_stock_change = 0;
1063 $qualified_for_stock_change =
$object->hasProductsOrServices(2);
1065 $qualified_for_stock_change =
$object->hasProductsOrServices(1);
1068 if ($qualified_for_stock_change) {
1069 if (!$idwarehouse || $idwarehouse == -1) {
1071 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
"Warehouse")),
null,
'errors');
1080 $sql =
'SELECT pf.amount';
1081 $sql .=
' FROM ' . MAIN_DB_PREFIX .
'paiement_facture as pf';
1082 $sql .=
' WHERE pf.fk_facture = ' . ((int)
$object->id);
1084 $result = $db->query($sql);
1087 $num = $db->num_rows($result);
1090 $objp = $db->fetch_object($result);
1091 $totalpaid += $objp->amount;
1095 dol_print_error($db,
'');
1098 $resteapayer =
$object->total_ttc - $totalpaid;
1101 $ventilExportCompta =
$object->getVentilExportCompta();
1104 if ($ventilExportCompta == 0) {
1107 $result =
$object->setDraft($user, $idwarehouse);
1114 $outputlangs = $langs;
1117 $newlang =
GETPOST(
'lang_id',
'aZ09');
1120 $newlang =
$object->thirdparty->default_lang;
1122 if (!empty($newlang)) {
1124 $outputlangs->setDefaultLang($newlang);
1125 $outputlangs->load(
'products');
1130 $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1136 } elseif ($action ==
'confirm_paid' && $confirm ==
'yes' && $usercanissuepayment) {
1139 $result =
$object->setPaid($user);
1143 } elseif ($action ==
'confirm_paid_partially' && $confirm ==
'yes' && $usercanissuepayment) {
1146 $close_code =
GETPOST(
"close_code",
'restricthtml');
1147 $close_note =
GETPOST(
"close_note",
'restricthtml');
1150 if (
isModEnabled(
'tax') && $close_code == $object::CLOSECODE_WITHHOLDINGTAX) {
1151 require_once DOL_DOCUMENT_ROOT.
'/compta/tva/class/tva.class.php';
1153 $amount = (float) ($resteapayer > 0 ? $resteapayer * -1 : $resteapayer);
1156 $tempTva =
new Tva($db);
1157 $tempTva->datev =
$object->date;
1158 $tempTva->datep =
$object->date;
1159 $tempTva->amount = $amount;
1160 $tempTva->label = $langs->trans(
'WithholdingTax') .
' - ' .
$object->ref;
1162 $valid = $tempTva->getIdForLabel($tempTva->label);
1164 $ret = $tempTva->create($user);
1168 $tempTva->setPaid($user);
1170 if (empty($error)) {
1173 setEventMessages($tempTva->error, $tempTva->errors,
'errors');
1178 setEventMessages($langs->trans(
'LabelWithholdingExist'), $tempTva->errors,
'errors');
1184 $result =
$object->setPaid($user, $close_code, $close_note);
1192 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Reason")),
null,
'errors');
1194 } elseif ($action ==
'confirm_canceled' && $confirm ==
'yes' && $usercancreate) {
1197 $close_code =
GETPOST(
"close_code",
'restricthtml');
1198 $close_note =
GETPOST(
"close_note",
'restricthtml');
1200 $result =
$object->setCanceled($user, $close_code, $close_note);
1207 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Reason")),
null,
'errors');
1209 } elseif ($action ==
'confirm_converttoreduc' && $confirm ==
'yes' && $usercancreate) {
1217 $result = $discountcheck->fetch(0,
$object->id);
1221 $sumofpaymentforconvert = (float)
$object->getSommePaiement();
1224 $sumofpaymentallforconvert = $sumofpaymentforconvert + (float)
$object->getSumCreditNotesUsed() + (float)
$object->getSumDepositsUsed();
1239 $amount_ht = $amount_tva = $amount_ttc = $amount_localtax1 = $amount_localtax2 = array();
1240 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
1244 foreach (
$object->lines as $line) {
1245 if ($line->product_type < 9 && $line->total_ht != 0) {
1246 $keyforvatrate = $line->tva_tx.($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
1248 if (!isset($amount_ht[$keyforvatrate])) {
1249 $amount_ht[$keyforvatrate] = 0;
1251 $amount_ht[$keyforvatrate] += $line->total_ht;
1252 if (!isset($amount_tva[$keyforvatrate])) {
1253 $amount_tva[$keyforvatrate] = 0;
1255 $amount_tva[$keyforvatrate] += $line->total_tva;
1256 if (!isset($amount_localtax1[$keyforvatrate])) {
1257 $amount_localtax1[$keyforvatrate] = 0;
1259 $amount_localtax1[$keyforvatrate] += $line->total_localtax1;
1260 if (!isset($amount_localtax2[$keyforvatrate])) {
1261 $amount_localtax2[$keyforvatrate] = 0;
1263 $amount_localtax2[$keyforvatrate] += $line->total_localtax2;
1264 if (!isset($amount_ttc[$keyforvatrate])) {
1265 $amount_ttc[$keyforvatrate] = 0;
1267 $amount_ttc[$keyforvatrate] += $line->total_ttc;
1268 if (!isset($multicurrency_amount_ht[$keyforvatrate])) {
1269 $multicurrency_amount_ht[$keyforvatrate] = 0;
1271 $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
1272 if (!isset($multicurrency_amount_tva[$keyforvatrate])) {
1273 $multicurrency_amount_tva[$keyforvatrate] = 0;
1275 $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
1276 if (!isset($multicurrency_amount_ttc[$keyforvatrate])) {
1277 $multicurrency_amount_ttc[$keyforvatrate] = 0;
1279 $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
1283 '@phan-var-force array<string,float> $amount_ht
1284 @phan-var-force array<string,float> $amount_tva
1285 @phan-var-force array<string,float> $amount_ttc
1286 @phan-var-force array<string,float> $amount_localtax1
1287 @phan-var-force array<string,float> $amount_localtax2
1288 @phan-var-force array<string,float> $multicurrency_amount_ht
1289 @phan-var-force array<string,float> $multicurrency_amount_tva
1290 @phan-var-force array<string,float> $multicurrency_amount_ttc';
1294 $alreadypaid =
$object->getSommePaiement();
1295 if ($alreadypaid && abs($alreadypaid) < abs(
$object->total_ttc)) {
1296 $ratio = abs((
$object->total_ttc - $alreadypaid) /
$object->total_ttc);
1297 foreach ($amount_ht as $vatrate => $val) {
1298 $amount_ht[$vatrate] =
price2num($amount_ht[$vatrate] * $ratio,
'MU');
1299 $amount_tva[$vatrate] =
price2num($amount_tva[$vatrate] * $ratio,
'MU');
1300 $amount_ttc[$vatrate] =
price2num($amount_ttc[$vatrate] * $ratio,
'MU');
1301 $amount_localtax1[$vatrate] =
price2num($amount_localtax1[$vatrate] * $ratio,
'MU');
1302 $amount_localtax2[$vatrate] =
price2num($amount_localtax2[$vatrate] * $ratio,
'MU');
1303 $multicurrency_amount_ht[$vatrate] =
price2num($multicurrency_amount_ht[$vatrate] * $ratio,
'MU');
1304 $multicurrency_amount_tva[$vatrate] =
price2num($multicurrency_amount_tva[$vatrate] * $ratio,
'MU');
1305 $multicurrency_amount_ttc[$vatrate] =
price2num($multicurrency_amount_ttc[$vatrate] * $ratio,
'MU');
1314 $discount->description =
'(CREDIT_NOTE)';
1316 $discount->description =
'(DEPOSIT)';
1318 $discount->description =
'(EXCESS RECEIVED)';
1320 setEventMessages($langs->trans(
'CantConvertToReducAnInvoiceOfThisType'),
null,
'errors');
1322 $discount->fk_soc =
$object->socid;
1323 $discount->socid =
$object->socid;
1324 $discount->fk_facture_source =
$object->id;
1328 $discount->multicurrency_code =
$object->multicurrency_code;
1329 $discount->multicurrency_tx =
$object->multicurrency_tx;
1339 $discount->description =
'(EXCESS RECEIVED)';
1342 $sql =
'SELECT SUM(pf.amount) as total_paiements';
1343 $sql .=
' FROM '.MAIN_DB_PREFIX.
'paiement_facture as pf, '.MAIN_DB_PREFIX.
'paiement as p';
1344 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as c ON p.fk_paiement = c.id';
1345 $sql .=
' WHERE pf.fk_facture = '.((int)
$object->id);
1346 $sql .=
' AND pf.fk_paiement = p.rowid';
1347 $sql .=
' AND p.entity IN ('.getEntity(
'invoice').
')';
1348 $resql = $db->query($sql);
1350 dol_print_error($db);
1353 $res = $db->fetch_object($resql);
1354 $total_paiements = $res->total_paiements;
1357 $total_creditnote_and_deposit = 0;
1358 $sql =
"SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1359 $sql .=
" re.description, re.fk_facture_source";
1360 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe_remise_except as re";
1361 $sql .=
" WHERE fk_facture = ".((int)
$object->id);
1362 $resql = $db->query($sql);
1363 if (!empty($resql)) {
1364 while ($obj = $db->fetch_object($resql)) {
1365 $total_creditnote_and_deposit += $obj->amount_ttc;
1368 dol_print_error($db);
1371 $discount->amount_ttc =
price2num($total_paiements + $total_creditnote_and_deposit -
$object->total_ttc,
'MT');
1372 $discount->amount_tva = 0;
1373 $discount->amount_ht = $discount->amount_ttc;
1374 $discount->tva_tx = 0;
1375 $discount->localtax1_tx = 0;
1376 $discount->localtax1_type = 0;
1377 $discount->localtax2_tx = 0;
1378 $discount->localtax2_type = 0;
1379 $discount->vat_src_code =
'';
1381 if ($discount->amount_ttc > 0) {
1382 $result = $discount->create($user);
1392 $discount->description =
'(CREDIT_NOTE)';
1394 $discount->description =
'(DEPOSIT)';
1397 foreach ($amount_ht as $tva_tx => $xxx) {
1402 $discount->amount_ht = -((float) $amount_ht[$tva_tx]);
1403 $discount->amount_tva = -((float) $amount_tva[$tva_tx]);
1404 $discount->amount_ttc = -((float) $amount_ttc[$tva_tx]);
1405 $discount->total_ht = -((float) $amount_ht[$tva_tx]);
1406 $discount->total_tva = -((float) $amount_tva[$tva_tx]);
1407 $discount->total_localtax1 = -((float) $amount_localtax1[$tva_tx]);
1408 $discount->total_localtax2 = -((float) $amount_localtax2[$tva_tx]);
1409 $discount->total_ttc = -((float) $amount_ttc[$tva_tx]);
1410 $discount->multicurrency_amount_ht = -((float) $multicurrency_amount_ht[$tva_tx]);
1411 $discount->multicurrency_amount_tva = -((float) $multicurrency_amount_tva[$tva_tx]);
1412 $discount->multicurrency_amount_ttc = -((float) $multicurrency_amount_ttc[$tva_tx]);
1413 $discount->multicurrency_total_ht = -((float) $multicurrency_amount_ht[$tva_tx]);
1414 $discount->multicurrency_total_tva = -((float) $multicurrency_amount_tva[$tva_tx]);
1415 $discount->multicurrency_total_ttc = -((float) $multicurrency_amount_ttc[$tva_tx]);
1418 $discount->amount_ht = abs((
float) $amount_ht[$tva_tx]);
1419 $discount->amount_tva = abs((
float) $amount_tva[$tva_tx]);
1420 $discount->amount_ttc = abs((
float) $amount_ttc[$tva_tx]);
1421 $discount->total_ht = abs((
float) $amount_ht[$tva_tx]);
1422 $discount->total_tva = abs((
float) $amount_tva[$tva_tx]);
1423 $discount->total_localtax1 = abs((
float) $amount_localtax1[$tva_tx]);
1424 $discount->total_localtax2 = abs((
float) $amount_localtax2[$tva_tx]);
1425 $discount->total_ttc = abs((
float) $amount_ttc[$tva_tx]);
1426 $discount->multicurrency_amount_ht = abs((
float) $multicurrency_amount_ht[$tva_tx]);
1427 $discount->multicurrency_amount_tva = abs((
float) $multicurrency_amount_tva[$tva_tx]);
1428 $discount->multicurrency_amount_ttc = abs((
float) $multicurrency_amount_ttc[$tva_tx]);
1429 $discount->multicurrency_total_ht = abs((
float) $multicurrency_amount_ht[$tva_tx]);
1430 $discount->multicurrency_total_tva = abs((
float) $multicurrency_amount_tva[$tva_tx]);
1431 $discount->multicurrency_total_ttc = abs((
float) $multicurrency_amount_ttc[$tva_tx]);
1437 if (preg_match(
'/\((.*)\)/', $tva_tx, $reg)) {
1438 $vat_src_code = $reg[1];
1439 $tva_tx = preg_replace(
'/\s*\(.*\)/',
'', $tva_tx);
1442 $discount->tva_tx = abs((
float) $tva_tx);
1443 $discount->localtax1_tx = !empty($taxes[
'localtax1']) ? $taxes[
'localtax1'] : 0;
1444 $discount->localtax1_type = !empty($taxes[
'localtax1_type']) ? $taxes[
'localtax1_type'] : 0;
1445 $discount->localtax2_tx = !empty($taxes[
'localtax2']) ? $taxes[
'localtax2'] : 0;
1446 $discount->localtax2_type = !empty($taxes[
'localtax2_type']) ? $taxes[
'localtax2_type'] : 0;
1447 $discount->vat_src_code = $vat_src_code;
1449 $result = $discount->create($user);
1457 if (empty($error)) {
1467 $result =
$object->setPaid($user);
1477 setEventMessages($discount->error, $discount->errors,
'errors');
1480 } elseif (empty($discountcheck->id)) {
1481 setEventMessages($langs->trans(
'ErrorInvoiceCantBeConvertedToDiscountInThisState'),
null,
'errors');
1483 } elseif ($action ==
'confirm_delete_paiement' && $confirm ==
'yes' && $usercanissuepayment) {
1488 $result = $paiement->fetch(
GETPOSTINT(
'paiement_id'));
1489 $paymentbills = ($result > 0) ? $paiement->getBillsArray() : array();
1490 if ($result > 0 && is_array($paymentbills) && in_array(
$object->id, $paymentbills)) {
1491 $result = $paiement->delete($user);
1493 header(
"Location: ".$_SERVER[
'PHP_SELF'].
"?id=".$id);
1497 setEventMessages($paiement->error, $paiement->errors,
'errors');
1500 setEventMessages($langs->trans(
"ErrorRecordNotFound"),
null,
'errors');
1503 } elseif ($action ==
'add' && $usercancreate) {
1510 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Type")),
null,
'errors');
1516 $object->demand_reason_id = $inputReasonId;
1519 $ret = $extrafields->setOptionalsFromPost(
null, $object);
1532 if (empty($dateinvoice)) {
1534 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
1538 setEventMessages($langs->trans(
"ErrorDateIsInFuture"),
null,
'errors');
1544 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"ReplaceInvoice")),
null,
'errors');
1554 $object->date_pointoftax = $date_pointoftax;
1555 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1556 $object->note_private = trim(
GETPOST(
'note_private',
'restricthtml'));
1565 $object->location_incoterms =
GETPOST(
'location_incoterms',
'alpha');
1566 $object->multicurrency_code =
GETPOST(
'multicurrency_code',
'alpha');
1583 if (!($sourceinvoice > 0) && !
getDolGlobalString(
'INVOICE_CREDIT_NOTE_STANDALONE')) {
1585 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceAvoirAskCombo")),
null,
'errors');
1589 if (empty($dateinvoice)) {
1591 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
1595 setEventMessages($langs->trans(
"ErrorDateIsInFuture"),
null,
'errors');
1601 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceSubtype")),
null,
'errors');
1606 if (!empty($originentity)) {
1607 $object->entity = $originentity;
1613 $object->date_pointoftax = $date_pointoftax;
1614 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1615 $object->note_private = trim(
GETPOST(
'note_private',
'restricthtml'));
1620 $object->cond_reglement_id = 0;
1624 $object->location_incoterms =
GETPOST(
'location_incoterms',
'alpha');
1625 $object->multicurrency_code =
GETPOST(
'multicurrency_code',
'alpha');
1629 $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice :
'';
1632 $facture_source =
new Facture($db);
1633 if (
$object->fk_facture_source > 0 && $facture_source->fetch(
$object->fk_facture_source) > 0) {
1634 if ($facture_source->isSituationInvoice()) {
1635 $object->situation_counter = $facture_source->situation_counter;
1636 $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
1637 $facture_source->fetchPreviousNextSituationInvoice();
1640 $object->pos_source = $facture_source->pos_source;
1641 $object->module_source = $facture_source->module_source;
1649 if (
$object->copy_linked_contact($facture_source,
'internal') < 0) {
1651 } elseif ($facture_source->socid ==
$object->socid) {
1653 if (
$object->copy_linked_contact($facture_source,
'external') < 0) {
1664 if (
GETPOSTINT(
'invoiceAvoirWithLines') == 1 && $id > 0) {
1665 if (!empty($facture_source->lines)) {
1666 $fk_parent_line = 0;
1668 foreach ($facture_source->lines as $line) {
1670 if (method_exists($line,
'fetch_optionals')) {
1672 $line->fetch_optionals();
1676 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1677 $fk_parent_line = 0;
1681 if ($facture_source->isSituationInvoice()) {
1682 $source_fk_prev_id = $line->fk_prev_id;
1683 $line->fk_prev_id = $line->id;
1688 if (
getDolGlobalInt(
'INVOICE_USE_SITUATION') == 1 && !empty($facture_source->tab_previous_situation_invoice)) {
1691 $tab_jumped_credit_notes = array();
1692 $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
1693 $searchPreviousInvoice =
true;
1694 while ($searchPreviousInvoice) {
1695 if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type ==
Facture::TYPE_SITUATION || $lineIndex < 1) {
1696 $searchPreviousInvoice =
false;
1700 $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
1706 $maxPrevSituationPercent = 0;
1707 foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
1708 if ($prevLine->id == $source_fk_prev_id) {
1709 $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
1712 $line->total_ht -= $prevLine->total_ht;
1713 $line->total_tva -= $prevLine->total_tva;
1714 $line->total_ttc -= $prevLine->total_ttc;
1715 $line->total_localtax1 -= $prevLine->total_localtax1;
1716 $line->total_localtax2 -= $prevLine->total_localtax2;
1718 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
1719 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
1720 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
1721 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
1726 $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
1731 $maxPrevSituationPercent = 0;
1732 foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
1733 foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
1734 if ($prevLine->fk_prev_id == $source_fk_prev_id) {
1735 $maxPrevSituationPercent = $prevLine->situation_percent;
1737 $line->total_ht -= $prevLine->total_ht;
1738 $line->total_tva -= $prevLine->total_tva;
1739 $line->total_ttc -= $prevLine->total_ttc;
1740 $line->total_localtax1 -= $prevLine->total_localtax1;
1741 $line->total_localtax2 -= $prevLine->total_localtax2;
1743 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
1744 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
1745 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
1746 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
1752 $line->situation_percent += $maxPrevSituationPercent;
1758 $line->fk_facture =
$object->id;
1759 $line->fk_parent_line = $fk_parent_line;
1761 $line->subprice = -$line->subprice;
1762 $line->subprice_ttc = -$line->subprice_ttc;
1764 $line->total_ht = -$line->total_ht;
1765 $line->total_tva = -$line->total_tva;
1766 $line->total_ttc = -$line->total_ttc;
1767 $line->total_localtax1 = -$line->total_localtax1;
1768 $line->total_localtax2 = -$line->total_localtax2;
1770 $line->multicurrency_subprice = -$line->multicurrency_subprice;
1771 $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
1772 $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
1773 $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
1775 $line->context[
'createcreditnotefrominvoice'] = 1;
1776 $result = $line->insert(0, 1);
1781 if ($result > 0 && $line->product_type == 9) {
1782 $fk_parent_line = $result;
1790 if (
GETPOSTINT(
'invoiceAvoirWithPaymentRestAmount') == 1 && $id > 0) {
1791 if ($facture_source->fetch(
$object->fk_facture_source) > 0) {
1792 $totalpaid = $facture_source->getSommePaiement();
1793 $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
1794 $totaldeposits = $facture_source->getSumDepositsUsed();
1795 $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
1797 if (
getDolGlobalString(
'INVOICE_VAT_TO_USE_ON_CREDIT_NOTE_WHEN_GENERATED_FROM_REMAIN_TO_PAY') ==
'default') {
1798 if ((empty(
$object->thirdparty) || !is_object(
$object->thirdparty) || get_class(
$object->thirdparty) !=
'Societe')) {
1801 if (!empty(
$object->thirdparty) && is_object(
$object->thirdparty) && get_class(
$object->thirdparty) ==
'Societe') {
1806 } elseif ((
float)
getDolGlobalString(
'INVOICE_VAT_TO_USE_ON_CREDIT_NOTE_WHEN_GENERATED_FROM_REMAIN_TO_PAY') > 0) {
1807 $tva_tx = (float)
getDolGlobalString(
'INVOICE_VAT_TO_USE_ON_CREDIT_NOTE_WHEN_GENERATED_FROM_REMAIN_TO_PAY');
1814 $object->addline($langs->trans(
'invoiceAvoirLineWithPaymentRestAmount'), 0, 1, $tva_tx, 0, 0, 0, 0,
'',
'', 0, 0, 0,
'TTC', -$remain_to_pay);
1819 if (!empty(
$object->fk_facture_source) &&
$id > 0) {
1820 $facture_source->fetch(
$object->fk_facture_source);
1821 $facture_source->fetchObjectLinked();
1823 if (!empty($facture_source->linkedObjectsIds)) {
1824 foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
1825 $object->add_object_linked($sourcetype, current($TIds));
1834 if (empty($dateinvoice)) {
1836 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
1840 setEventMessages($langs->trans(
"ErrorDateIsInFuture"),
null,
'errors');
1847 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceSubtype")),
null,
'errors');
1857 $object->date_pointoftax = $date_pointoftax;
1858 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1859 $object->note_private = trim(
GETPOST(
'note_private',
'restricthtml'));
1870 $object->location_incoterms =
GETPOST(
'location_incoterms',
'alpha');
1871 $object->multicurrency_code =
GETPOST(
'multicurrency_code',
'alpha');
1887 $typeamount =
GETPOST(
'typedeposit',
'aZ09');
1888 $valuestandardinvoice =
price2num(str_replace(
'%',
'',
GETPOST(
'valuestandardinvoice',
'alpha')),
'MU');
1889 $valuedeposit =
price2num(str_replace(
'%',
'',
GETPOST(
'valuedeposit',
'alpha')),
'MU');
1893 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Customer")),
null,
'errors');
1897 if (empty($dateinvoice)) {
1899 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date")),
null,
'errors');
1903 setEventMessages($langs->trans(
"ErrorDateIsInFuture"),
null,
'errors');
1909 if ($valuestandardinvoice < 0 || $valuestandardinvoice > 100) {
1910 setEventMessages($langs->trans(
"ErrorAPercentIsRequired"),
null,
'errors');
1915 if ($typeamount && !empty($origin) && !empty($originid)) {
1916 if ($typeamount ==
'amount' && $valuedeposit <= 0) {
1917 setEventMessages($langs->trans(
"ErrorAnAmountWithoutTaxIsRequired"),
null,
'errors');
1921 if ($typeamount ==
'variable' && ($valuedeposit <= 0 || $valuedeposit > 100)) {
1922 setEventMessages($langs->trans(
"ErrorAPercentIsRequired"),
null,
'errors');
1926 if ($typeamount ==
'variablealllines' && ($valuedeposit <= 0 || $valuedeposit > 100)) {
1927 setEventMessages($langs->trans(
"ErrorAPercentIsRequired"),
null,
'errors');
1937 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceSubtype")),
null,
'errors');
1947 $object->date_pointoftax = $date_pointoftax;
1948 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
1949 $object->note_private = trim(
GETPOST(
'note_private',
'restricthtml'));
1959 $object->location_incoterms =
GETPOST(
'location_incoterms',
'alpha');
1960 $object->multicurrency_code =
GETPOST(
'multicurrency_code',
'alpha');
1964 $object->situation_counter = 1;
1969 if (in_array(
$object->type, $retainedWarrantyInvoiceAvailableType)) {
1971 $object->retained_warranty_fk_cond_reglement =
GETPOSTINT(
'retained_warranty_fk_cond_reglement');
1973 $object->retained_warranty = 0;
1974 $object->retained_warranty_fk_cond_reglement = 0;
1977 $retained_warranty_date_limit =
GETPOST(
'retained_warranty_date_limit');
1978 if (!empty($retained_warranty_date_limit) &&
dol_stringtotime($retained_warranty_date_limit)) {
1981 $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);
1986 if (!empty($origin) && !empty($originid)) {
1989 $element = $subelement = $origin;
1990 if (preg_match(
'/^([^_]+)_([^_]+)/i', $origin, $regs)) {
1991 $element = $regs[1];
1992 $subelement = $regs[2];
1996 if ($element ==
'order') {
1997 $element = $subelement =
'commande';
1999 if ($element ==
'propal') {
2000 $element =
'comm/propal';
2001 $subelement =
'propal';
2003 if ($element ==
'contract') {
2004 $element = $subelement =
'contrat';
2006 if ($element ==
'inter') {
2007 $element = $subelement =
'fichinter';
2009 if ($element ==
'shipping') {
2010 $element = $subelement =
'expedition';
2014 $object->origin_type = $origin;
2015 $object->origin_id = $originid;
2020 if (
$object->origin ==
'shipping') {
2021 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
2023 $exp->fetch(
$object->origin_id);
2024 $exp->fetchObjectLinked();
2025 if (is_array($exp->linkedObjectsIds[
'commande']) && count($exp->linkedObjectsIds[
'commande']) > 0) {
2026 foreach ($exp->linkedObjectsIds[
'commande'] as $key => $value) {
2027 $object->linked_objects[
'commande'] = $value;
2033 $object->linked_objects = array_merge(
$object->linked_objects,
GETPOST(
'other_linked_objects',
'array:int'));
2041 $classname = ucfirst($subelement);
2042 $srcobject =
new $classname($db);
2043 '@phan-var-force CommonObject $srcobject';
2045 dol_syslog(
"Try to find source object origin_type=".
$object->origin_type.
" origin_id=".
$object->origin_id.
" to add lines or deposit lines");
2046 $result = $srcobject->fetch(
$object->origin_id);
2052 $amountdeposit = array();
2055 if ($typeamount ==
'amount') {
2056 $amount = (float) $valuedeposit;
2058 $amount = $srcobject->total_ttc * ((float) $valuedeposit / 100);
2061 $TTotalByTva = array();
2062 foreach ($srcobject->lines as &$line) {
2063 if (empty($line->qty)) {
2066 if (!empty($line->special_code)) {
2070 $vatkey = $line->tva_tx.($line->vat_src_code ?
' ('.$line->vat_src_code.
')' :
'');
2071 if (!isset($TTotalByTva[$vatkey])) {
2072 $TTotalByTva[$vatkey] = 0;
2074 $TTotalByTva[$vatkey] += $line->total_ttc;
2077 '@phan-var-force array<string,float> $TTotalByTva';
2079 $amount_ttc_diff = 0.;
2080 foreach ($TTotalByTva as $tva => &$total) {
2081 if (empty($amountdeposit[$tva])) {
2082 $amountdeposit[$tva] = 0;
2084 $coef = ($srcobject->total_ttc != 0 ? $total / $srcobject->total_ttc : 0);
2085 $am = $amount * $coef;
2086 $amount_ttc_diff += $am;
2087 $amountdeposit[$tva] += $am / (1 + (float) preg_replace(
'/\s*\(.*\)/',
'', (
string) $tva) / 100);
2091 if ($typeamount ==
'amount') {
2092 $amountdeposit[0] = $valuedeposit;
2093 } elseif ($typeamount ==
'variable') {
2096 $lines = $srcobject->lines;
2097 $numlines = count($lines);
2098 for ($i = 0; $i < $numlines; $i++) {
2100 if (empty($lines[$i]->qty)) {
2103 if (!empty($lines[$i]->special_code)) {
2107 $totalamount += $lines[$i]->total_ht;
2108 $tva_tx = $lines[$i]->tva_tx;
2110 if (empty($amountdeposit[$tva_tx])) {
2111 $amountdeposit[$tva_tx] = 0;
2113 $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * (float) $valuedeposit) / 100;
2117 if ($totalamount == 0) {
2118 $amountdeposit[0] = 0;
2121 setEventMessages($srcobject->error, $srcobject->errors,
'errors');
2127 if ($typeamount ==
'variable') {
2128 $amount_ttc_diff = (float)
price2num($srcobject->total_ttc * ((
float) $valuedeposit / 100),
'MT');
2130 $amount_ttc_diff = $amountdeposit[0];
2134 foreach ($amountdeposit as $tva => $amount) {
2135 if (empty($amount)) {
2140 'amount' =>
'FixAmount',
2141 'variable' =>
'VarAmount'
2143 $descline =
'(DEPOSIT)';
2145 if ($typeamount ==
'amount') {
2146 $descline .=
' ('.price($valuedeposit, 0, $langs, 0, - 1, - 1, (!empty(
$object->multicurrency_code) ?
$object->multicurrency_code :
$conf->currency)).
')';
2147 } elseif ($typeamount ==
'variable') {
2148 $descline .=
' ('.$valuedeposit.
'%)';
2151 $descline .=
' - '.$srcobject->ref;
2164 isset($lines[$i]) ? $lines[$i]->info_bits : 0,
2170 isset($lines[$i]) ? $lines[$i]->special_code : 0,
2189 $diff =
$object->total_ttc - $amount_ttc_diff;
2191 if ((
float)
price2num($diff,
'MT') != 0) {
2195 foreach (
$object->lines as $line) {
2196 if (empty($line->special_code)) {
2197 $targetLine = $line;
2201 if ($targetLine !==
null) {
2202 $subprice_diff = $targetLine->subprice - $diff / (1 + $targetLine->tva_tx / 100);
2204 $tva_tx_with_code = $targetLine->tva_tx.($targetLine->vat_src_code ?
' ('.$targetLine->vat_src_code.
')' :
'');
2205 $object->updateline($targetLine->id, $targetLine->desc, $subprice_diff, $targetLine->qty, $targetLine->remise_percent, $targetLine->date_start, $targetLine->date_end, $tva_tx_with_code, 0, 0,
'HT', $targetLine->info_bits, $targetLine->product_type, 0, 0, 0, $targetLine->pa_ht, $targetLine->label, 0, array(), 100);
2215 $lines = $srcobject->lines;
2216 if (empty($lines) && method_exists($srcobject,
'fetch_lines')) {
2217 $srcobject->fetch_lines();
2218 $lines = $srcobject->lines;
2223 if (is_array($lines)) {
2224 foreach ($lines as $line) {
2226 $line->qty = (float)
price2num((
float) $line->qty * (float) $valuestandardinvoice / 100,
'MS');
2232 if (is_array($lines)) {
2233 foreach ($lines as $line) {
2235 $line->qty = (float)
price2num((
float) $line->qty * (float) $valuedeposit / 100,
'MS');
2240 $fk_parent_line = 0;
2241 $num = count($lines);
2243 for ($i = 0; $i < $num; $i++) {
2244 if (!in_array($lines[$i]->
id, $selectedLines)) {
2249 if ($srcobject->element ==
'shipping' &&
getDolGlobalString(
'SHIPMENT_GETS_ALL_ORDER_PRODUCTS') && $lines[$i]->qty == 0) {
2253 if (!isset(
$conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) {
2254 $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE =
'5';
2256 if ($srcobject->element ==
'contrat' && in_array($lines[$i]->statut, explode(
',',
getDolGlobalString(
'CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE')))) {
2261 if ($srcobject->element ==
'shipping' && empty($srcobject->origin_id)) {
2262 require_once DOL_DOCUMENT_ROOT.
'/core/lib/sendings.lib.php';
2266 $label = (!empty($lines[$i]->label) ? $lines[$i]->label :
'');
2267 $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc :
'');
2269 if (
$object->situation_counter == 1) {
2270 $lines[$i]->situation_percent = 0;
2273 if ($lines[$i]->subprice < 0 && !
getDolGlobalString(
'INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN')) {
2276 $desc = $label ? $label : $langs->trans(
'Discount');
2280 $discount->fk_soc =
$object->socid;
2281 $discount->socid =
$object->socid;
2282 $discount->amount_ht = abs($lines[$i]->total_ht);
2283 $discount->amount_tva = abs($lines[$i]->total_tva);
2284 $discount->amount_ttc = abs($lines[$i]->total_ttc);
2285 $discount->total_ht = abs($lines[$i]->total_ht);
2286 $discount->total_tva = abs($lines[$i]->total_tva);
2287 $discount->total_ttc = abs($lines[$i]->total_ttc);
2288 $discount->tva_tx = $lines[$i]->tva_tx;
2289 $discount->localtax1_tx = $lines[$i]->localtax1_tx;
2290 $discount->localtax2_tx = $lines[$i]->localtax2_tx;
2291 $discount->localtax1_type = $lines[$i]->localtax1_type;
2292 $discount->localtax2_type = $lines[$i]->localtax2_type;
2293 $discount->total_localtax1 = abs($lines[$i]->total_localtax1);
2294 $discount->total_localtax2 = abs($lines[$i]->total_localtax2);
2295 $discount->fk_user = $user->id;
2296 $discount->description = $desc;
2297 $discount->multicurrency_subprice = abs($lines[$i]->multicurrency_subprice);
2298 $discount->multicurrency_amount_ht = abs($lines[$i]->multicurrency_total_ht);
2299 $discount->multicurrency_amount_tva = abs($lines[$i]->multicurrency_total_tva);
2300 $discount->multicurrency_amount_ttc = abs($lines[$i]->multicurrency_total_ttc);
2301 $discount->multicurrency_total_ht = abs($lines[$i]->multicurrency_total_ht);
2302 $discount->multicurrency_total_tva = abs($lines[$i]->multicurrency_total_tva);
2303 $discount->multicurrency_total_ttc = abs($lines[$i]->multicurrency_total_ttc);
2305 $discountid = $discount->create($user);
2306 if ($discountid > 0) {
2307 $result =
$object->insert_discount($discountid);
2309 setEventMessages($discount->error, $discount->errors,
'errors');
2320 if (isset($lines[$i]->date_debut_prevue)) {
2323 if (isset($lines[$i]->date_debut_reel)) {
2326 if (isset($lines[$i]->date_start)) {
2332 if (isset($lines[$i]->date_fin_prevue)) {
2333 $date_end = $lines[$i]->date_fin_prevue;
2335 if (isset($lines[$i]->date_fin_reel)) {
2336 $date_end = $lines[$i]->date_fin_reel;
2338 if (isset($lines[$i]->date_end)) {
2339 $date_end = $lines[$i]->date_end;
2343 if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
2344 $fk_parent_line = 0;
2347 $array_options = array();
2349 if (method_exists($lines[$i],
'fetch_optionals')) {
2350 $lines[$i]->fetch_optionals();
2351 $array_options = $lines[$i]->array_options;
2354 $tva_tx = $lines[$i]->tva_tx;
2355 if (!empty($lines[$i]->vat_src_code) && !preg_match(
'/\(/', (
string) $tva_tx)) {
2356 $tva_tx .=
' ('.$lines[$i]->vat_src_code.
')';
2365 $line_price_base_type = $lines[$i]->getPriceBaseType();
2368 $lines[$i]->subprice,
2373 $lines[$i]->fk_product,
2374 $lines[$i]->remise_percent,
2378 (
int) $lines[$i]->info_bits,
2379 isset($lines[$i]->fk_remise_except) ? $lines[$i]->fk_remise_except : null,
2380 $line_price_base_type,
2381 (float) $lines[$i]->subprice_ttc,
2384 $lines[$i]->special_code,
2388 isset($lines[$i]->fk_fournprice) ? $lines[$i]->fk_fournprice : null,
2392 $lines[$i]->situation_percent ?? 100,
2393 $lines[$i]->fk_prev_id ?? 0,
2394 $lines[$i]->fk_unit,
2401 foreach (
$object->lines as $line) {
2402 if ($line->id == $result) {
2403 $line->extraparams = $lines[$i]->extraparams;
2404 $line->setExtraParameters();
2416 if ($result > 0 && $lines[$i]->product_type == 9) {
2417 $fk_parent_line = $result;
2422 setEventMessages($srcobject->error, $srcobject->errors,
'errors');
2429 $object->line_order(
true,
'DESC');
2457 $parameters = array(
'origin_type' =>
$object->origin_type,
'origin_id' =>
$object->origin_id,
'objFrom' => $srcobject);
2458 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $object, $action);
2461 setEventMessages($hookmanager->error, $hookmanager->errors,
'errors');
2471 for ($i = 1; $i <= $NBLINES; $i++) {
2477 $result =
$object->addline($product->description, $product->price, (
float)
price2num(
GETPOST(
'qty'.$i),
'MS'), $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx,
GETPOSTINT(
'idprod'.$i), (
float)
price2num(
GETPOST(
'remise_percent'.$i),
'', 2), $startday, $endday, 0, 0, 0, $product->price_base_type, $product->price_ttc, $product->type, -1, 0,
'', 0, 0, 0, 0,
'', array(), 100, 0, $product->fk_unit, 0,
'', 1);
2488 if (empty($dateinvoice)) {
2490 $mesg = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Date"));
2491 setEventMessages($mesg,
null,
'errors');
2494 setEventMessages($langs->trans(
"ErrorDateIsInFuture"),
null,
'errors');
2500 $mesg = $langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"InvoiceSituation"));
2501 setEventMessages($mesg,
null,
'errors');
2510 if (!empty($origin) && !empty($originid)) {
2511 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
2514 $object->origin_type = $origin;
2515 $object->origin_id = $originid;
2519 $retained_warranty =
GETPOSTINT(
'retained_warranty');
2520 if (
price2num($retained_warranty) > 0) {
2524 if (
GETPOSTINT(
'retained_warranty_fk_cond_reglement') > 0) {
2525 $object->retained_warranty_fk_cond_reglement =
GETPOSTINT(
'retained_warranty_fk_cond_reglement');
2528 $retained_warranty_date_limit =
GETPOST(
'retained_warranty_date_limit');
2529 if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) {
2530 $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit);
2532 $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);
2535 foreach (
$object->lines as $i => &$line) {
2536 $line->fk_prev_id = $line->id;
2537 $line->fetch_optionals();
2539 $line->situation_percent = $line->get_prev_progress(
$object->id);
2541 $line->situation_percent = 0;
2545 $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, array(), $line->situation_percent);
2546 $line->total_ht = (float) $tabprice[0];
2547 $line->total_tva = (float) $tabprice[1];
2548 $line->total_ttc = (float) $tabprice[2];
2549 $line->total_localtax1 = (float) $tabprice[9];
2550 $line->total_localtax2 = (float) $tabprice[10];
2551 $line->multicurrency_total_ht = (float) $tabprice[16];
2552 $line->multicurrency_total_tva = (float) $tabprice[17];
2553 $line->multicurrency_total_ttc = (float) $tabprice[18];
2556 if ($line->fk_remise_except) {
2558 $result = $discount->fetch((
int) $line->fk_remise_except);
2561 if ($discount->fk_facture_line > 0) {
2562 $line->fk_remise_except = 0;
2571 $object->date_pointoftax = $date_pointoftax;
2572 $object->note_public = trim(
GETPOST(
'note_public',
'restricthtml'));
2586 $object->situation_counter += 1;
2591 $extrafields->fetch_name_optionals_label(
$object->table_element);
2592 $extrafields->setOptionalsFromPost(
null, $object);
2598 $nextSituationInvoice =
new Facture($db);
2599 $nextSituationInvoice->fetch($id);
2602 $parameters = array(
'origin_type' =>
$object->origin_type,
'origin_id' =>
$object->origin_id);
2603 $reshook = $hookmanager->executeHooks(
'createFrom', $parameters, $nextSituationInvoice, $action);
2606 setEventMessages($hookmanager->error, $hookmanager->errors,
'errors');
2614 if ($id > 0 && !$error) {
2616 $categories =
GETPOST(
'categories',
'array');
2617 if (method_exists($object,
'setCategories')) {
2618 $object->setCategories($categories);
2626 $outputlangs = $langs;
2629 $newlang =
GETPOST(
'lang_id',
'aZ09');
2632 if (empty(
$object->thirdparty)) {
2635 $newlang =
$object->thirdparty->default_lang;
2637 if (!empty($newlang)) {
2639 $outputlangs->setDefaultLang($newlang);
2640 $outputlangs->load(
'products');
2645 $result =
$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
2651 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
2656 $_GET[
"origin"] =
GETPOST(
"origin",
'alpha');
2660 } elseif ($action ==
'addline' &&
GETPOST(
'submitforalllines',
'aZ09') && (
GETPOST(
'alldate_start',
'alpha') ||
GETPOST(
'alldate_end',
'alpha')) && $usercancreate) {
2664 foreach (
$object->lines as $line) {
2665 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
2668 if ($line->product_type == 1) {
2670 $line_price_base_type = $line->getPriceBaseType();
2671 $line_pu = ($line_price_base_type ===
'TTC') ? (
float) $line->subprice_ttc : (float) $line->subprice;
2672 $result =
$object->updateline($line->id, $line->desc, $line_pu, $line->qty, $line->remise_percent, $alldate_start, $alldate_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line_price_base_type, $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);
2675 } elseif ($action ==
'addline' &&
GETPOST(
'submitforalllines',
'alpha') &&
GETPOST(
'vatforalllines',
'alpha') !==
'' && $usercancreate) {
2677 $vat_rate = (
GETPOST(
'vatforalllines') ?
GETPOST(
'vatforalllines') : 0);
2678 $vat_rate = str_replace(
'*',
'', $vat_rate);
2681 foreach (
$object->lines as $line) {
2682 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
2686 $line_price_base_type = $line->getPriceBaseType();
2687 $line_pu = ($line_price_base_type ===
'TTC') ? (
float) $line->subprice_ttc : (float) $line->subprice;
2688 $result =
$object->updateline($line->id, $line->desc, $line_pu, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vat_rate, $localtax1_rate, $localtax2_rate, $line_price_base_type, $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);
2690 } elseif ($action ==
'addline' &&
GETPOST(
'submitforalllines',
'alpha') &&
GETPOST(
'remiseforalllines',
'alpha') !==
'' && $usercancreate) {
2692 $remise_percent = (
GETPOST(
'remiseforalllines') ?
GETPOST(
'remiseforalllines') : 0);
2693 $remise_percent = str_replace(
'*',
'', $remise_percent);
2694 foreach (
$object->lines as $line) {
2695 if ($line->special_code == SUBTOTALS_SPECIAL_CODE || !empty($line->fk_remise_except)) {
2698 $tvatx = $line->tva_tx;
2699 if (!empty($line->vat_src_code)) {
2700 $tvatx .=
' ('.$line->vat_src_code.
')';
2703 $line_price_base_type = $line->getPriceBaseType();
2704 $line_pu = ($line_price_base_type ===
'TTC') ? (
float) $line->subprice_ttc : (float) $line->subprice;
2705 $result =
$object->updateline($line->id, $line->desc, $line_pu, $line->qty, (
float) $remise_percent, $line->date_start, $line->date_end, $tvatx, $line->localtax1_tx, $line->localtax2_tx, $line_price_base_type, $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);
2707 } elseif ($action ==
'addline' &&
GETPOST(
'submitforalllines',
'alpha') &&
GETPOST(
'progressforalllines',
'alpha') !==
'' && $usercancreate &&
$object->situation_cycle_ref) {
2710 if ($all_progress > 100) {
2711 $all_progress = 100;
2714 foreach (
$object->lines as $line) {
2715 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
2719 $percent = $line->get_prev_progress(
$object->id);
2721 $percent = $line->getAllPrevProgress(
$object->id);
2723 if (
$object->type != $object::TYPE_CREDIT_NOTE && (
float) $all_progress < (
float) $percent) {
2724 $mesg = $langs->trans(
"Line").
' '.$line->rang.
' : '.$langs->trans(
"CantBeLessThanMinPercent");
2725 setEventMessages($mesg,
null,
'warnings');
2726 } elseif (
$object->type == $object::TYPE_CREDIT_NOTE && (
float) $all_progress > (
float) $percent) {
2727 $mesg = $langs->trans(
"Line").
' '.$line->rang.
' : '.$langs->trans(
"CantBeMoreThanMinPercent");
2728 setEventMessages($mesg,
null,
'warnings');
2730 $object->update_percent($line, $all_progress,
false);
2734 } elseif ($action ==
'confirm_addtextline' && $usercancreate) {
2737 $langs->load(
'subtotals');
2739 $desc =
GETPOST(
'subtotaltextcontent',
'restricthtml');
2742 $result =
$object->addSubtotalLine($langs, $desc, 0, array());
2753 $outputlangs = $langs;
2754 $newlang =
GETPOST(
'lang_id',
'alpha');
2756 $newlang =
$object->thirdparty->default_lang;
2758 if (!empty($newlang)) {
2760 $outputlangs->setDefaultLang($newlang);
2763 $object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2768 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
2770 } elseif ($action ==
'confirm_addtitleline' && $usercancreate) {
2773 $langs->load(
'subtotals');
2775 $desc =
GETPOST(
'subtotallinedesc',
'alphanohtml');
2776 $depth =
GETPOSTINT(
'subtotallinelevel') ?? 1;
2778 $subtotal_options = array();
2780 foreach (Facture::$TITLE_OPTIONS as $option) {
2781 $value =
GETPOST($option,
'alphanohtml');
2783 $subtotal_options[$option] = $value ==
'on' ? 1 : $value;
2788 $result =
$object->addSubtotalLine($langs, $desc, (
int) $depth, $subtotal_options);
2799 $outputlangs = $langs;
2800 $newlang =
GETPOST(
'lang_id',
'alpha');
2802 $newlang =
$object->thirdparty->default_lang;
2804 if (!empty($newlang)) {
2806 $outputlangs->setDefaultLang($newlang);
2809 $object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2814 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
2816 } elseif ($action ==
'confirm_addsubtotalline' && $usercancreate) {
2819 $langs->load(
'subtotals');
2821 $choosen_line =
GETPOST(
'subtotaltitleline',
'alphanohtml');
2822 foreach (
$object->lines as $line) {
2823 if ($line->desc == $choosen_line && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
2824 $desc = $line->desc;
2825 $depth = -$line->qty;
2829 $subtotal_options = array();
2831 foreach (Facture::$SUBTOTAL_OPTIONS as $option) {
2832 $value =
GETPOST($option,
'alphanohtml');
2834 $subtotal_options[$option] = $value ==
'on' ? 1 : $value;
2839 if (isset($desc) && isset($depth)) {
2840 $result =
$object->addSubtotalLine($langs, $desc, (
int) $depth, $subtotal_options);
2843 $object->errors[] = $langs->trans(
"CorrespondingTitleNotFound");
2852 $outputlangs = $langs;
2853 $newlang =
GETPOST(
'lang_id',
'alpha');
2855 $newlang =
$object->thirdparty->default_lang;
2857 if (!empty($newlang)) {
2859 $outputlangs->setDefaultLang($newlang);
2862 $object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2867 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
2869 } elseif ($action ==
'addline' &&
GETPOST(
'updateallvatlinesblock',
'alpha') &&
GETPOST(
'vatforblocklines',
'alpha') !==
'' && $usercancreate) {
2870 $tx_tva =
GETPOST(
'vatforblocklines') ?
GETPOST(
'vatforblocklines') : 0;
2871 $object->updateSubtotalLineBlockLines($langs,
$object->getRangOfLine($lineid),
'tva', $tx_tva);
2872 } elseif ($action ==
'addline' &&
GETPOST(
'updatealldiscountlinesblock',
'alpha') &&
GETPOST(
'discountforblocklines',
'alpha') !==
'' && $usercancreate) {
2873 $discount =
GETPOST(
'discountforblocklines') ?
GETPOST(
'discountforblocklines') : 0;
2874 $object->updateSubtotalLineBlockLines($langs,
$object->getRangOfLine($lineid),
'discount', $discount);
2875 } elseif ($action ==
'addline' && !
GETPOST(
'submitforalllines',
'alpha') && !
GETPOST(
'submitforallmargins',
'alpha') && !
GETPOST(
'submitforallmark',
'alpha') && $usercancreate) {
2876 $langs->load(
'errors');
2884 $price_ht_devise =
'';
2886 $price_ttc_devise =
'';
2889 $price_min_ttc =
'';
2891 if (
GETPOST(
'price_ht') !==
'') {
2894 if (
GETPOST(
'multicurrency_price_ht') !==
'') {
2897 if (
GETPOST(
'price_ttc') !==
'') {
2900 if (
GETPOST(
'multicurrency_price_ttc') !==
'') {
2901 $price_ttc_devise =
price2num(
GETPOST(
'multicurrency_price_ttc'),
'CU', 2);
2904 $prod_entry_mode =
GETPOST(
'prod_entry_mode',
'aZ09');
2905 if ($prod_entry_mode ==
'free') {
2911 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"ProductOrService")),
null,
'errors');
2916 $tva_tx =
GETPOST(
'tva_tx',
'alpha');
2920 if (empty($remise_percent)) {
2921 $remise_percent = 0;
2925 $extralabelsline = $extrafields->fetch_name_optionals_label(
$object->table_element_line);
2926 $array_options = $extrafields->getOptionalsFromPost(
$object->table_element_line, $predef);
2928 if (is_array($extralabelsline)) {
2930 foreach ($extralabelsline as $key => $value) {
2931 unset($_POST[
"options_".$key.$predef]);
2935 if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
2936 setEventMessages($langs->trans(
'ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv(
'UnitPriceHT'), $langs->transnoentitiesnoconv(
'Qty')),
null,
'errors');
2939 if (!$prod_entry_mode) {
2941 setEventMessages($langs->trans(
'ErrorChooseBetweenFreeEntryOrPredefinedProduct'),
null,
'errors');
2945 if ($prod_entry_mode ==
'free' && (empty($idprod) || $idprod < 0) &&
GETPOST(
'type') < 0) {
2946 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Type')),
null,
'errors');
2951 if ($prod_entry_mode ==
'free' && (empty($idprod) || $idprod < 0)
2952 && (((
float) $price_ht < 0 && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) || $price_ht ===
'')
2953 && (((
float) $price_ht_devise < 0 && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) || $price_ht_devise ===
'')
2954 && ((
float) $price_ttc < 0 && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES') || $price_ttc ===
'')
2955 && ((
float) $price_ttc_devise < 0 && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES') || $price_ttc_devise ===
'')
2956 &&
$object->type != $object::TYPE_CREDIT_NOTE) {
2957 if (((
float) $price_ht < 0 || (
float) $price_ttc < 0) && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) {
2958 $langs->load(
"errors");
2959 if (
$object->type == $object::TYPE_DEPOSIT) {
2961 setEventMessages($langs->trans(
"ErrorLinesCantBeNegativeOnDeposits"),
null,
'errors');
2963 setEventMessages($langs->trans(
"ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv(
"UnitPriceHT"), $langs->transnoentitiesnoconv(
"CustomerAbsoluteDiscountShort")),
null,
'errors');
2968 if ($prod_entry_mode ==
'free' && (empty($idprod) || $idprod < 0) &&
GETPOST(
'price_ht') ===
'' &&
GETPOST(
'price_ttc') ===
'' && $price_ht_devise ===
'') {
2969 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'UnitPrice')),
null,
'errors');
2973 if ($prod_entry_mode ==
'free' && (empty($idprod) || $idprod < 0) && empty($line_desc)) {
2974 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Description')),
null,
'errors');
2978 setEventMessages($langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Qty')),
null,
'errors');
2982 $langs->load(
"errors");
2983 setEventMessages($langs->trans(
'ErrorQtyForCustomerInvoiceCantBeNegative'),
null,
'errors');
2987 if (!$error &&
isModEnabled(
'variants') && $prod_entry_mode !=
'free') {
2988 if ($combinations =
GETPOST(
'combinations',
'array:alphanohtml')) {
2992 if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
2993 $idprod = $res->fk_product_child;
2995 setEventMessages($langs->trans(
'ErrorProductCombinationNotFound'),
null,
'errors');
3001 $price_base_type =
null;
3002 if (!$error && (!empty($line_desc) || (!empty($idprod) && $idprod > 0))) {
3005 dol_print_error($db,
$object->error);
3008 $ret =
$object->fetch_thirdparty();
3013 $price_base_type = (
GETPOST(
'price_base_type',
'alpha') ?
GETPOST(
'price_base_type',
'alpha') :
'HT');
3024 if (!empty($idprod) && $idprod > 0) {
3026 $prod->fetch($idprod);
3028 $label = ((
GETPOST(
'product_label') &&
GETPOST(
'product_label') != $prod->label) ?
GETPOST(
'product_label') :
'');
3033 $datapriceofproduct = $prod->getSellPrice(
$mysoc,
$object->thirdparty, $pqp);
3035 $pu_ht = $datapriceofproduct[
'pu_ht'];
3036 $pu_ttc = $datapriceofproduct[
'pu_ttc'];
3037 $price_min = $datapriceofproduct[
'price_min'];
3038 $price_min_ttc = (isset($datapriceofproduct[
'price_min_ttc'])) ? $datapriceofproduct[
'price_min_ttc'] : null;
3039 $price_base_type = empty($datapriceofproduct[
'price_base_type']) ?
'HT' : $datapriceofproduct[
'price_base_type'];
3043 $tmpvat = (float)
price2num(preg_replace(
'/\s*\(.*\)/',
'', $tva_tx));
3044 $tmpprodvat =
price2num(preg_replace(
'/\s*\(.*\)/',
'', (
string) $prod->tva_tx));
3049 if (!empty($price_ht) || $price_ht ===
'0') {
3051 $pu_ttc =
price2num((
float) $pu_ht * (1 + ($tmpvat / 100)),
'MU');
3052 $price_base_type =
'HT';
3053 } elseif (!empty($price_ht_devise) || $price_ht_devise ===
'0') {
3054 $pu_ht_devise =
price2num($price_ht_devise,
'MU');
3055 $pu_ttc_devise = (float)
price2num((
float) $pu_ht_devise * (1 + ((float) $tmpvat / 100)),
'MU');
3058 $price_base_type =
'HT';
3059 } elseif (!empty($price_ttc) || $price_ttc ===
'0') {
3061 $pu_ht =
price2num((
float) $pu_ttc / (1 + ($tmpvat / 100)),
'MU');
3062 $price_base_type =
'TTC';
3063 } elseif (!empty($price_ttc_devise) || (
string) $price_ttc_devise ===
'0') {
3064 $pu_ttc_devise = (float)
price2num($price_ttc_devise,
'MU');
3065 $pu_ht_devise = (float)
price2num((
float) $pu_ttc_devise / (1 + ((float) $tmpvat / 100)),
'MU');
3068 $price_base_type =
'TTC';
3069 } elseif ($tmpvat != $tmpprodvat) {
3071 if ($price_base_type !=
'HT') {
3072 $pu_ht =
price2num($pu_ttc / (1 + ($tmpvat / 100)),
'MU');
3074 $pu_ttc =
price2num($pu_ht * (1 + ($tmpvat / 100)),
'MU');
3078 $outputlangs = $langs;
3084 if (
GETPOST(
'lang_id',
'aZ09')) {
3085 $newlang =
GETPOST(
'lang_id',
'aZ09');
3087 if (empty($newlang)) {
3088 $newlang =
$object->thirdparty->default_lang;
3090 if (!empty($newlang)) {
3092 $outputlangs->setDefaultLang($newlang);
3093 $outputlangs->load(
'products');
3096 $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] [
"description"])) ? $prod->multilangs [$outputlangs->defaultlang] [
"description"] : $prod->
description;
3098 $desc = $prod->description;
3110 if (!
getDolGlobalString(
'MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE') && (!empty($prod->customcode) || !empty($prod->country_code))) {
3114 if (!empty($prod->customcode)) {
3115 $tmptxt .= $outputlangs->transnoentitiesnoconv(
"CustomsCode").
': '.$prod->customcode;
3117 if (!empty($prod->customcode) && !empty($prod->country_code)) {
3120 if (!empty($prod->country_code)) {
3121 $tmptxt .= $outputlangs->transnoentitiesnoconv(
"CountryOrigin").
': '.
getCountry($prod->country_code,
'', $db, $outputlangs, 0);
3124 if (!empty($prod->customcode)) {
3125 $tmptxt .= $langs->transnoentitiesnoconv(
"CustomsCode").
': '.$prod->customcode;
3127 if (!empty($prod->customcode) && !empty($prod->country_code)) {
3130 if (!empty($prod->country_code)) {
3131 $tmptxt .= $langs->transnoentitiesnoconv(
"CountryOrigin").
': '.
getCountry($prod->country_code,
'', $db, $langs, 0);
3138 $type = $prod->type;
3139 $fk_unit = $prod->fk_unit;
3141 if (!empty($price_ht)) {
3146 if (!empty($price_ttc)) {
3151 $tva_npr = (preg_match(
'/\*/', $tva_tx) ? 1 : 0);
3152 $tva_tx = str_replace(
'*',
'', $tva_tx);
3153 if (empty($tva_tx)) {
3156 $label = (
GETPOST(
'product_label') ?
GETPOST(
'product_label') :
'');
3159 $fk_unit =
GETPOST(
'units',
'alpha');
3161 if ($pu_ttc && !$pu_ht) {
3162 $price_base_type =
'TTC';
3176 $pu_ht_devise =
price2num($price_ht_devise,
'', 2);
3177 $pu_ttc_devise =
price2num($price_ttc_devise,
'', 2);
3180 $pu_equivalent = $pu_ht;
3181 $pu_equivalent_ttc = $pu_ttc;
3183 $currency_tx =
$object->multicurrency_tx;
3187 if ($pu_ht ==
'' && $pu_ht_devise !=
'' && $currency_tx !=
'' && !empty((
float) $currency_tx)) {
3188 $pu_equivalent = (float) $pu_ht_devise / (
float) $currency_tx;
3190 if ($pu_ttc ==
'' && $pu_ttc_devise !=
'' && $currency_tx !=
'' && !empty((
float) $currency_tx)) {
3191 $pu_equivalent_ttc = (float) $pu_ttc_devise / (
float) $currency_tx;
3206 $fournprice = (int) (
GETPOST(
'fournprice'.$predef) ?
GETPOST(
'fournprice'.$predef) :
'');
3211 $price2num_remise_percent =
price2num($remise_percent);
3212 $price2num_price_min =
price2num($price_min);
3213 $price2num_price_min_ttc =
price2num($price_min_ttc);
3214 if (empty($price2num_pu_ht)) {
3215 $price2num_pu_ht = 0;
3217 if (empty($price2num_remise_percent)) {
3218 $price2num_remise_percent = 0;
3220 if (empty($price2num_price_min)) {
3221 $price2num_price_min = 0;
3223 if (empty($price2num_price_min_ttc)) {
3224 $price2num_price_min_ttc = 0;
3229 if ($pu_equivalent && $price_min && (((
float)
price2num($pu_equivalent) * (1 - $remise_percent / 100)) < (
float)
price2num($price_min)) && $price_base_type ==
'HT') {
3230 $mesg = $langs->trans(
"CantBeLessThanMinPrice",
price(
price2num($price_min,
'MU'), 0, $langs, 0, 0, -1,
$conf->currency));
3231 setEventMessages($mesg,
null,
'errors');
3233 } elseif ($pu_equivalent_ttc && $price_min_ttc && (((
float)
price2num($pu_equivalent_ttc) * (1 - $remise_percent / 100)) < (
float)
price2num($price_min_ttc)) && $price_base_type ==
'TTC') {
3234 $mesg = $langs->trans(
"CantBeLessThanMinPriceInclTax",
price(
price2num($price_min_ttc,
'MU'), 0, $langs, 0, 0, -1,
$conf->currency));
3235 setEventMessages($mesg,
null,
'errors');
3254 if ($price_ht ===
'' && $price_ttc ===
'' && $price_ht_devise ===
'' && $price_ttc_devise !==
'') {
3257 $price_base_type =
'TTC';
3258 $pu_ht_devise =
price2num($price_ttc_devise,
'MU');
3264 $result =
$object->addline($desc, $pu_ht, (
float) $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent,
$date_start, $date_end, 0, $info_bits, 0, $price_base_type, $pu_ttc, $type, min($rank, count(
$object->lines) + 1), $special_code,
'', 0,
GETPOSTINT(
'fk_parent_line'), (
int) $fournprice, $buyingprice, $label, $array_options, $situation_percent, 0, $fk_unit, (
float) $pu_ht_devise);
3271 $outputlangs = $langs;
3274 $newlang =
GETPOST(
'lang_id',
'aZ09');
3277 $newlang =
$object->thirdparty->default_lang;
3279 if (!empty($newlang)) {
3281 $outputlangs->setDefaultLang($newlang);
3282 $outputlangs->load(
'products');
3285 $result =
$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
3291 unset($_POST[
'prod_entry_mode']);
3292 unset($_POST[
'qty']);
3293 unset($_POST[
'type']);
3294 unset($_POST[
'remise_percent']);
3295 unset($_POST[
'price_ht']);
3296 unset($_POST[
'multicurrency_price_ht']);
3297 unset($_POST[
'price_ttc']);
3298 unset($_POST[
'tva_tx']);
3299 unset($_POST[
'product_ref']);
3300 unset($_POST[
'product_label']);
3301 unset($_POST[
'product_desc']);
3302 unset($_POST[
'fournprice']);
3303 unset($_POST[
'buying_price']);
3304 unset($_POST[
'np_marginRate']);
3305 unset($_POST[
'np_markRate']);
3306 unset($_POST[
'dp_desc']);
3307 unset($_POST[
'idprod']);
3308 unset($_POST[
'units']);
3309 unset($_POST[
'date_starthour']);
3310 unset($_POST[
'date_startmin']);
3311 unset($_POST[
'date_startsec']);
3312 unset($_POST[
'date_startday']);
3313 unset($_POST[
'date_startmonth']);
3314 unset($_POST[
'date_startyear']);
3315 unset($_POST[
'date_endhour']);
3316 unset($_POST[
'date_endmin']);
3317 unset($_POST[
'date_endsec']);
3318 unset($_POST[
'date_endday']);
3319 unset($_POST[
'date_endmonth']);
3320 unset($_POST[
'date_endyear']);
3321 unset($_POST[
'situations']);
3322 unset($_POST[
'progress']);
3324 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
3333 } elseif ($action ==
'addline' && $usercancreate && (
3334 (
GETPOST(
'submitforallmargins',
'alpha') &&
GETPOST(
'marginforalllines',
'alpha') !==
'') ||
3335 (
GETPOST(
'submitforallmark',
'alpha') &&
GETPOST(
'markforalllines',
'alpha') !==
'')
3338 $margin_rate =
GETPOSTISSET(
'marginforalllines') ?
GETPOST(
'marginforalllines',
'int') :
'';
3340 foreach (
$object->lines as &$line) {
3341 if ($line->subprice > 0) {
3342 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
3345 $subprice_multicurrency = $line->subprice;
3346 if (is_numeric($margin_rate) && $margin_rate > 0) {
3347 $line->subprice = (float)
price2num((
float) $line->pa_ht * (1 + (float) $margin_rate / 100),
'MU');
3348 } elseif (is_numeric($mark_rate) && $mark_rate > 0) {
3349 $line->subprice = (float) ($line->pa_ht / (1 - ((
float) $mark_rate / 100)));
3351 $line->subprice = (float) $line->pa_ht;
3354 if ($line->fk_product > 0) {
3356 $res = $prod->fetch($line->fk_product);
3358 if ($prod->price_min > $line->subprice) {
3359 $price_subprice =
price($line->subprice, 0, $outlangs, 1, -1, -1,
'auto');
3360 $price_price_min =
price($prod->price_min, 0, $outlangs, 1, -1, -1,
'auto');
3361 setEventMessages($prod->ref .
' - ' . $prod->label .
' (' . $price_subprice .
' < ' . $price_price_min .
' ' . strtolower($langs->trans(
"MinPrice")) .
')' .
"\n",
null,
'warnings');
3363 setEventMessages($prod->error, $prod->errors,
'errors');
3366 setEventMessages($prod->error, $prod->errors,
'errors');
3370 $multicurrency_subprice = (float) $line->subprice * $line->multicurrency_subprice / $subprice_multicurrency;
3372 $result =
$object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->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->product_ref, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $multicurrency_subprice);
3375 if (is_numeric($margin_rate) && empty($mark_rate)) {
3376 $line->marge_tx = $margin_rate;
3377 } elseif (is_numeric($mark_rate) && empty($margin_rate)) {
3378 $line->marque_tx = $mark_rate;
3380 $line->total_ht = $line->qty * (float) $line->subprice;
3381 $line->total_tva = $line->tva_tx * $line->qty * (float) $line->subprice;
3382 $line->total_ttc = (1 + $line->tva_tx) * $line->qty * (
float) $line->subprice;
3384 $line->multicurrency_total_ht = $line->qty * (float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
3385 $line->multicurrency_total_tva = $line->tva_tx * $line->qty * (float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
3386 $line->multicurrency_total_ttc = (1 + $line->tva_tx) * $line->qty * (
float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
3388 $line->multicurrency_subprice = $multicurrency_subprice;
3394 } elseif ($action ==
'updatetitleline' &&
GETPOSTISSET(
"save") && $usercancreate && !
GETPOST(
'cancel',
'alpha')) {
3397 $langs->load(
'subtotals');
3399 $desc =
GETPOST(
'line_desc',
'alphanohtml') ?? $langs->trans(
"Title");
3402 $subtotal_options = array();
3404 foreach (Facture::$TITLE_OPTIONS as $option) {
3405 $value =
GETPOST($option,
'alphanohtml');
3407 $subtotal_options[$option] = $value ==
'on' ? 1 : $value;
3412 $result =
$object->updateSubtotalLine($langs,
GETPOSTINT(
'lineid'), $desc, $depth, $subtotal_options);
3423 $outputlangs = $langs;
3424 $newlang =
GETPOST(
'lang_id',
'alpha');
3426 $newlang =
$object->thirdparty->default_lang;
3428 if (!empty($newlang)) {
3430 $outputlangs->setDefaultLang($newlang);
3433 $object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
3438 } elseif ($action ==
'updatetextline' &&
GETPOSTISSET(
"save") && $usercancreate && !
GETPOST(
'cancel',
'alpha')) {
3441 $langs->load(
'subtotals');
3443 $desc =
GETPOST(
'line_desc',
'restricthtml');
3446 $result =
$object->updateSubtotalLine($langs,
GETPOSTINT(
'lineid'), $desc, 0, array());
3457 $outputlangs = $langs;
3458 $newlang =
GETPOST(
'lang_id',
'alpha');
3460 $newlang =
$object->thirdparty->default_lang;
3462 if (!empty($newlang)) {
3464 $outputlangs->setDefaultLang($newlang);
3467 $object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
3472 } elseif ($action ==
'updatesubtotalline' &&
GETPOSTISSET(
"save") && $usercancreate && !
GETPOST(
'cancel',
'alpha')) {
3475 $langs->load(
'subtotals');
3477 $desc =
GETPOST(
'line_desc',
'alphanohtml');
3480 $subtotal_options = array();
3482 foreach (Facture::$SUBTOTAL_OPTIONS as $option) {
3483 $value =
GETPOST($option,
'alphanohtml');
3485 $subtotal_options[$option] = $value ==
'on' ? 1 : $value;
3490 $result =
$object->updateSubtotalLine($langs,
GETPOSTINT(
'lineid'), $desc, $depth, $subtotal_options);
3498 $outputlangs = $langs;
3499 $newlang =
GETPOST(
'lang_id',
'alpha');
3501 $newlang =
$object->thirdparty->default_lang;
3503 if (!empty($newlang)) {
3505 $outputlangs->setDefaultLang($newlang);
3508 $object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
3513 } elseif ($action ==
'updateline' && $usercancreate && !
GETPOST(
'cancel',
'alpha')) {
3514 if (!
$object->fetch($id) > 0) {
3515 dol_print_error($db);
3537 if (preg_match(
'/\*/', $vat_rate)) {
3542 $vat_rate = str_replace(
'*',
'', $vat_rate);
3547 $fournprice = (int) (
GETPOST(
'fournprice') ?
GETPOST(
'fournprice') :
'');
3551 $pu_equivalent = $pu_ht;
3552 $pu_equivalent_ttc = $pu_ttc;
3554 $currency_tx =
$object->multicurrency_tx;
3558 if ($pu_ht ==
'' && $pu_ht_devise !=
'' && $currency_tx !=
'' && !empty((
float) $currency_tx)) {
3559 $pu_equivalent = (float) $pu_ht_devise / (
float) $currency_tx;
3561 if ($pu_ttc ==
'' && $pu_ttc_devise !=
'' && $currency_tx !=
'' && !empty((
float) $currency_tx)) {
3562 $pu_equivalent_ttc = (float) $pu_ttc_devise / (
float) $currency_tx;
3577 $extralabelsline = $extrafields->fetch_name_optionals_label(
$object->table_element_line);
3578 $array_options = $extrafields->getOptionalsFromPost(
$object->table_element_line);
3580 if (is_array($extralabelsline)) {
3582 foreach ($extralabelsline as $key => $value) {
3583 unset($_POST[
"options_".$key]);
3589 if ($special_code == 3) {
3595 $percent = $line->get_prev_progress(
$object->id);
3600 if ($progress >= 0) {
3601 $mesg = $langs->trans(
"CantBeNullOrPositive");
3602 setEventMessages($mesg,
null,
'warnings');
3605 } elseif ($progress < $line->situation_percent) {
3606 $mesg = $langs->trans(
"CantBeLessThanMinPercent");
3607 setEventMessages($mesg,
null,
'warnings');
3610 } elseif ($progress < $percent) {
3611 $mesg =
'<div class="warning">'.$langs->trans(
"CantBeLessThanMinPercent").
'</div>';
3612 setEventMessages($mesg,
null,
'warnings');
3619 if (empty($remise_percent)) {
3620 $remise_percent = 0;
3627 $price_base_type =
'HT';
3628 if (empty($pu_ht) && !empty($pu_ttc)) {
3630 $price_base_type =
'TTC';
3631 } elseif (!empty($pu_ht) && !empty($pu_ttc)) {
3632 foreach (
$object->lines as $line_obj) {
3635 if ($line_obj->wasEnteredIncludingTax()) {
3637 $price_base_type =
'TTC';
3646 if (
GETPOST(
'price_ht') ===
'' &&
GETPOST(
'price_ttc') ===
'' &&
GETPOST(
'multicurrency_subprice') ===
'' &&
GETPOST(
'multicurrency_price_ttc') !==
'') {
3648 $price_base_type =
'TTC';
3649 $pu_ht_devise = $pu_ttc_devise;
3654 if (!empty($productid)) {
3656 $product->fetch($productid);
3658 $type = $product->type;
3660 $price_min = $product->price_min;
3662 $price_min = $product->multiprices_min[
$object->thirdparty->price_level];
3664 $price_min_ttc = $product->price_min_ttc;
3666 $price_min_ttc = $product->multiprices_min_ttc[
$object->thirdparty->price_level];
3673 if ($pu_equivalent && $price_min && (((
float)
price2num($pu_equivalent) * (1 - (
float) $remise_percent / 100)) < (float)
price2num($price_min)) && $price_base_type ==
'HT') {
3674 $mesg = $langs->trans(
"CantBeLessThanMinPrice",
price(
price2num($price_min,
'MU'), 0, $langs, 0, 0, -1,
$conf->currency));
3675 setEventMessages($mesg,
null,
'errors');
3677 $action =
'editline';
3678 } elseif ($pu_equivalent_ttc && $price_min_ttc && (((
float)
price2num($pu_equivalent_ttc) * (1 - (
float) $remise_percent / 100)) < (
float)
price2num($price_min_ttc)) && $price_base_type ==
'TTC') {
3679 $mesg = $langs->trans(
"CantBeLessThanMinPriceInclTax",
price(
price2num($price_min_ttc,
'MU'), 0, $langs, 0, 0, -1,
$conf->currency));
3680 setEventMessages($mesg,
null,
'errors');
3682 $action =
'editline';
3687 $label = (
GETPOST(
'product_label') ?
GETPOST(
'product_label') :
'');
3691 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"Type")),
null,
'errors');
3696 $langs->load(
"errors");
3697 setEventMessages($langs->trans(
'ErrorQtyForCustomerInvoiceCantBeNegative'),
null,
'errors');
3701 if (($pu_ht < 0 || $pu_ttc < 0) && !
getDolGlobalString(
'FACTURE_ENABLE_NEGATIVE_LINES')) {
3702 $langs->load(
"errors");
3703 if (
$object->type == $object::TYPE_DEPOSIT) {
3705 setEventMessages($langs->trans(
"ErrorLinesCantBeNegativeOnDeposits"),
null,
'errors');
3707 setEventMessages($langs->trans(
"ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv(
"UnitPriceHT"), $langs->transnoentitiesnoconv(
"CustomerAbsoluteDiscountShort")),
null,
'errors');
3711 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentitiesnoconv(
"UnitPriceHT")),
null,
'errors');
3720 $previousprogress = $line->getAllPrevProgress($line->fk_facture);
3723 if ($fullprogress < $previousprogress) {
3725 setEventMessages($langs->trans(
'CantBeLessThanMinPercent'),
null,
'errors');
3729 if ($fullprogress > 100) {
3730 $fullprogress = 100;
3732 $addprogress = $fullprogress - $previousprogress;
3737 $oldbuyingprice = array_column(
$object->lines,
'pa_ht',
'id')[$lineid] ??
null;
3739 if (empty($usercancreatemargin)) {
3740 foreach (
$object->lines as &$line) {
3742 $fournprice = $line->fk_fournprice;
3743 $buyingprice = $line->pa_ht;
3749 $result =
$object->updateline(
3754 (
float) $remise_percent,
3772 (
float) $pu_ht_devise
3780 $outputlangs = $langs;
3783 $newlang =
GETPOST(
'lang_id',
'aZ09');
3786 $newlang =
$object->thirdparty->default_lang;
3788 if (!empty($newlang)) {
3790 $outputlangs->setDefaultLang($newlang);
3791 $outputlangs->load(
'products');
3793 $object->generateDocument(
$object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
3796 unset($_POST[
'qty']);
3797 unset($_POST[
'type']);
3798 unset($_POST[
'productid']);
3799 unset($_POST[
'remise_percent']);
3800 unset($_POST[
'price_ht']);
3801 unset($_POST[
'multicurrency_price_ht']);
3802 unset($_POST[
'price_ttc']);
3803 unset($_POST[
'tva_tx']);
3804 unset($_POST[
'product_ref']);
3805 unset($_POST[
'product_label']);
3806 unset($_POST[
'product_desc']);
3807 unset($_POST[
'fournprice']);
3808 unset($_POST[
'buying_price']);
3809 unset($_POST[
'np_marginRate']);
3810 unset($_POST[
'np_markRate']);
3811 unset($_POST[
'dp_desc']);
3812 unset($_POST[
'idprod']);
3813 unset($_POST[
'units']);
3814 unset($_POST[
'date_starthour']);
3815 unset($_POST[
'date_startmin']);
3816 unset($_POST[
'date_startsec']);
3817 unset($_POST[
'date_startday']);
3818 unset($_POST[
'date_startmonth']);
3819 unset($_POST[
'date_startyear']);
3820 unset($_POST[
'date_endhour']);
3821 unset($_POST[
'date_endmin']);
3822 unset($_POST[
'date_endsec']);
3823 unset($_POST[
'date_endday']);
3824 unset($_POST[
'date_endmonth']);
3825 unset($_POST[
'date_endyear']);
3826 unset($_POST[
'situations']);
3827 unset($_POST[
'progress']);
3829 if (
$object->getLinkedBuyPriceDocuments($user, $lineid, $oldbuyingprice)) {
3830 $action =
'ask_updatelinkedbuyingprice';
3836 } elseif ($action ==
'updateline' && $usercancreate && !$cancel) {
3837 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?facid='.$id);
3839 } elseif ($action ==
'confirm_updatelinkedbuyingprice' && $confirm ==
'yes' && $usercancreate) {
3840 $result =
$object->updateLinkedBuyPrice($user, $lineid, array(
'propal' =>
GETPOST(
'updatelinked_propal'),
'commande' =>
GETPOST(
'updatelinked_commande'),
'facture' =>
GETPOST(
'updatelinked_facture')));
3841 setEventMessages(($result < 0 ? $object->error : $langs->trans(
'RecordsModified', $result)), null, ($result < 0 ?
'errors' :
'mesgs'));
3842 } elseif ($action ==
'confirm_situationout' && $confirm ==
'yes' && $usercancreate) {
3844 $object->fetch($id,
'',
'', 0,
true);
3847 &&
$object->isSituationInvoice()
3850 &&
$object->is_last_in_cycle()
3851 && $usercanunvalidate
3854 $newCycle =
$object->newCycle();
3855 if ($newCycle > 1) {
3857 $lastCycle =
$object->situation_cycle_ref;
3858 $lastSituationCounter =
$object->situation_counter;
3859 $linkedCreditNotesList = array();
3861 if (count(
$object->tab_next_situation_invoice) > 0) {
3862 foreach (
$object->tab_next_situation_invoice as $next_invoice) {
3864 && $next_invoice->situation_counter ==
$object->situation_counter
3865 && $next_invoice->fk_facture_source ==
$object->id
3867 $linkedCreditNotesList[] = $next_invoice->id;
3872 $object->situation_cycle_ref = $newCycle;
3873 $object->situation_counter = 1;
3875 if (
$object->update($user) > 0) {
3877 if (count($linkedCreditNotesList) > 0) {
3879 $sql =
'UPDATE '.MAIN_DB_PREFIX.
'facture';
3880 $sql .=
' SET situation_cycle_ref = '.((int) $newCycle);
3881 $sql .=
' , situation_final=0';
3882 $sql .=
' , situation_counter='.((int)
$object->situation_counter);
3883 $sql .=
' WHERE rowid IN ('.$db->sanitize(implode(
',', $linkedCreditNotesList)).
')';
3885 $resql = $db->query($sql);
3891 foreach (
$object->lines as $line) {
3893 if ($line->product_type == 9) {
3898 if (!empty(
$object->tab_previous_situation_invoice)) {
3900 $lineIndex = count(
$object->tab_previous_situation_invoice) - 1;
3901 $searchPreviousInvoice =
true;
3902 while ($searchPreviousInvoice) {
3903 if (
$object->tab_previous_situation_invoice[$lineIndex]->isSituationInvoice() || $lineIndex < 1) {
3904 $searchPreviousInvoice =
false;
3912 $maxPrevSituationPercent = 0;
3913 foreach (
$object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
3914 if ($prevLine->id == $line->fk_prev_id) {
3915 $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
3920 $line->situation_percent -= $maxPrevSituationPercent;
3922 if ($line->update() < 0) {
3930 setEventMessages($langs->trans(
'Updated'),
null,
'mesgs');
3931 header(
"Location: ".$_SERVER[
'PHP_SELF'].
"?id=".$id);
3933 setEventMessages($langs->trans(
'ErrorOutingSituationInvoiceCreditNote'), array(),
'errors');
3936 setEventMessages($langs->trans(
'ErrorOutingSituationInvoiceOnUpdate'), array(),
'errors');
3939 setEventMessages($langs->trans(
'ErrorFindNextSituationInvoice'), array(),
'errors');
3945 $fromElement =
GETPOST(
'fromelement',
'aZ09');
3946 $fromElementid =
GETPOST(
'fromelementid');
3947 $importLines =
GETPOST(
'line_checkbox');
3949 if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && !empty($fromElementid)) {
3950 $lineClassName =
'';
3951 if ($fromElement ==
'commande') {
3953 $lineClassName =
'OrderLine';
3954 } elseif ($fromElement ==
'propal') {
3955 dol_include_once(
'/comm/'.$fromElement.
'/class/'.$fromElement.
'.class.php');
3956 $lineClassName =
'PropaleLigne';
3958 $nextRang = count(
$object->lines) + 1;
3961 foreach ($importLines as $lineId) {
3962 if ($lineClassName ===
'') {
3966 dol_syslog(
'compta/facture/card - No lineClassName - skip import', LOG_ERR);
3973 $lineId = intval($lineId);
3974 $originLine =
new $lineClassName($db);
3975 if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
3976 $originLine->fetch_optionals();
3977 $desc = $originLine->desc;
3978 $pu_ht = $originLine->subprice;
3979 $qty = $originLine->qty;
3980 $txtva = $originLine->tva_tx;
3981 $txlocaltax1 = $originLine->localtax1_tx;
3982 $txlocaltax2 = $originLine->localtax2_tx;
3983 $fk_product = $originLine->fk_product;
3984 $remise_percent = $originLine->remise_percent;
3986 $date_end = $originLine->date_end;
3987 $fk_code_ventilation = 0;
3988 $info_bits = $originLine->info_bits;
3989 $fk_remise_except = $originLine->fk_remise_except;
3990 $price_base_type =
'HT';
3992 $type = $originLine->product_type;
3993 $rang = $nextRang++;
3994 $special_code = $originLine->special_code;
3995 $origin = $originLine->element;
3996 $origin_id = $originLine->id;
3997 $fk_parent_line = 0;
3998 $fk_fournprice = $originLine->fk_fournprice;
3999 $pa_ht = $originLine->pa_ht;
4000 $label = $originLine->label;
4001 $array_options = $originLine->array_options;
4002 if (
$object->isSituationInvoice()) {
4003 $situation_percent = 0;
4005 $situation_percent = 100;
4008 $fk_unit = $originLine->fk_unit;
4009 $pu_ht_devise = $originLine->multicurrency_subprice;
4011 $res =
$object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent,
$date_start, $date_end, $fk_code_ventilation, $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);
4024 setEventMessages($langs->trans(
'ErrorsOnXLines', $error),
null,
'errors');
4031 include DOL_DOCUMENT_ROOT.
'/core/actions_printing.inc.php';
4037 if (!empty(
$object->id) && $action ==
'send') {
4039 $object->getSommePaiement(-1);
4040 $object->getSumCreditNotesUsed(-1);
4041 $object->getSumDepositsUsed(-1);
4043 $triggersendname =
'BILL_SENTBYMAIL';
4045 $autocopy =
'MAIN_MAIL_AUTOCOPY_INVOICE_TO';
4046 $trackid =
'inv'.$object->id;
4047 include DOL_DOCUMENT_ROOT.
'/core/actions_sendmails.inc.php';
4051 $permissiontoadd = $usercancreate;
4052 include DOL_DOCUMENT_ROOT.
'/core/actions_builddoc.inc.php';
4055 if ($action ==
'update_extras' && $permissiontoeditextra) {
4058 $attribute_name =
GETPOST(
'attribute',
'aZ09');
4061 $ret = $extrafields->setOptionalsFromPost(
null, $object, $attribute_name);
4068 $result =
$object->updateExtraField($attribute_name,
'BILL_MODIFY');
4076 $action =
'edit_extras';
4081 if ($action ==
'addcontact' && $usercancreate) {
4082 $result =
$object->fetch($id);
4084 if ($result > 0 && $id > 0) {
4087 $result =
$object->add_contact($contactid, $typeid,
GETPOST(
"source",
'aZ09'));
4091 header(
"Location: ".$_SERVER[
'PHP_SELF'].
"?id=".
$object->id);
4094 if (
$object->error ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
4095 $langs->load(
"errors");
4096 setEventMessages($langs->trans(
"ErrorThisContactIsAlreadyDefinedAsThisType"),
null,
'errors');
4101 } elseif ($action ==
'swapstatut' && $usercancreate) {
4106 dol_print_error($db);
4108 } elseif ($action ==
'deletecontact' && $usercancreate) {
4111 $result =
$object->delete_contact($lineid);
4114 header(
"Location: ".$_SERVER[
'PHP_SELF'].
"?id=".
$object->id);
4117 dol_print_error($db);
4122 $action =
'edit_extras';
4132$form =
new Form($db);
4138$bankaccountstatic =
new Account($db);
4146$title =
$object->ref.
" - ".$langs->trans(
'Card');
4147if ($action ==
'create') {
4148 $title = $langs->trans(
"NewBill");
4150$help_url =
"EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
4156if ($action ==
'create') {
4157 $facturestatic =
new Facture($db);
4158 $extrafields->fetch_name_optionals_label($facturestatic->table_element);
4163 $res = $soc->fetch($socid);
4166 $currency_code =
$conf->currency;
4168 $cond_reglement_id =
GETPOSTINT(
'cond_reglement_id');
4169 $mode_reglement_id =
GETPOSTINT(
'mode_reglement_id');
4173 if (empty($dateinvoice)) {
4179 if (!empty($origin) && !empty($originid)) {
4181 $element = $subelement = $origin;
4183 if (preg_match(
'/^([^_]+)_([^_]+)/i', $origin, $regs)) {
4184 $element = $regs[1];
4185 $subelement = $regs[2];
4190 if ($element ==
'project') {
4191 $projectid = $originid;
4193 if (empty($cond_reglement_id)) {
4194 $cond_reglement_id = $soc->cond_reglement_id;
4196 if (empty($mode_reglement_id)) {
4197 $mode_reglement_id = $soc->mode_reglement_id;
4199 if (empty($fk_account)) {
4200 $fk_account = $soc->fk_account;
4204 if ($element ==
'order' || $element ==
'commande') {
4205 $element = $subelement =
'commande';
4207 if ($element ==
'propal') {
4208 $element =
'comm/propal';
4209 $subelement =
'propal';
4211 if ($element ==
'contract') {
4212 $element = $subelement =
'contrat';
4214 if ($element ==
'shipping') {
4215 $element = $subelement =
'expedition';
4220 $classname = ucfirst($subelement);
4221 $objectsrc =
new $classname($db);
4222 '@phan-var-force Commande|Propal|Contrat|Expedition|Facture $objectsrc';
4224 $objectsrc->fetch($originid);
4225 if (empty($objectsrc->lines) && method_exists($objectsrc,
'fetch_lines')) {
4226 $objectsrc->fetch_lines();
4228 $objectsrc->fetch_thirdparty();
4230 $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project);
4236 $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer :
''));
4240 if (empty($socid)) {
4241 $soc = $objectsrc->thirdparty;
4244 if ($element ==
'expedition') {
4245 $elem = $subelem = $objectsrc->origin_type;
4246 $expeoriginid = $objectsrc->origin_id;
4248 $classname = ucfirst($subelem);
4250 $expesrc =
new $classname($db);
4251 '@phan-var-force Expedition $expesrc';
4253 dol_syslog(
"Is type Facture|Commande or Expedition: $element...expesrc($classname)=".get_class($expesrc));
4254 $expesrc->fetch($expeoriginid);
4256 $cond_reglement_id = (!empty($expesrc->cond_reglement_id) ? $expesrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 1));
4257 $mode_reglement_id = (!empty($expesrc->mode_reglement_id) ? $expesrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
4258 $fk_account = (!empty($expesrc->fk_account) ? $expesrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
4261 $currency_code = (!empty($expesrc->multicurrency_code) ? $expesrc->multicurrency_code : (!empty($soc->multicurrency_code) ? $soc->multicurrency_code : $objectsrc->multicurrency_code));
4262 $currency_tx = (!empty($expesrc->multicurrency_tx) ? $expesrc->multicurrency_tx : (!empty($soc->multicurrency_tx) ? $soc->multicurrency_tx : $objectsrc->multicurrency_tx));
4266 $inputReasonId = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0));
4269 $expesrc->fetch_optionals();
4270 $object->array_options = $expesrc->array_options;
4272 $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : (!empty($cond_reglement_id) ? $cond_reglement_id : 0)));
4273 $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : (!empty($mode_reglement_id) ? $mode_reglement_id : 0)));
4274 $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : (!empty($fk_account) ? $fk_account : 0)));
4277 if (!empty($objectsrc->multicurrency_code)) {
4278 $currency_code = $objectsrc->multicurrency_code;
4280 if (
getDolGlobalString(
'MULTICURRENCY_USE_ORIGIN_TX') && !empty($objectsrc->multicurrency_tx)) {
4281 $currency_tx = $objectsrc->multicurrency_tx;
4286 $inputReasonId = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0));
4289 $objectsrc->fetch_optionals();
4290 $object->array_options = $objectsrc->array_options;
4294 $cond_reglement_id = empty($soc->cond_reglement_id) ? $cond_reglement_id : $soc->cond_reglement_id;
4295 $mode_reglement_id = empty($soc->mode_reglement_id) ? $mode_reglement_id : $soc->mode_reglement_id;
4296 $fk_account = empty($soc->fk_account) ? $fk_account : $soc->fk_account;
4297 $inputReasonId = empty($soc->demand_reason_id) ? $inputReasonId : $soc->demand_reason_id;
4299 if (
isModEnabled(
'multicurrency') && !empty($soc->multicurrency_code)) {
4300 $currency_code = $soc->multicurrency_code;
4305 if (!
GETPOST(
'changecompany')) {
4307 $cond_reglement_id =
GETPOSTINT(
'cond_reglement_id');
4310 $mode_reglement_id =
GETPOSTINT(
'mode_reglement_id');
4318 if (empty($cond_reglement_id)) {
4319 $cond_reglement_id =
GETPOSTINT(
"cond_reglement_id");
4323 if (empty($mode_reglement_id)) {
4324 $mode_reglement_id =
GETPOSTINT(
"mode_reglement_id");
4334 if (!empty($soc->id)) {
4335 $absolute_discount = $soc->getAvailableDiscounts();
4337 $note_public =
$object->getDefaultCreateValueFor(
'note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) &&
getDolGlobalString(
'FACTURE_REUSE_NOTES_ON_CREATE_FROM')) ? $objectsrc->note_public : null));
4338 $note_private =
$object->getDefaultCreateValueFor(
'note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) &&
getDolGlobalString(
'FACTURE_REUSE_NOTES_ON_CREATE_FROM')) ? $objectsrc->note_private : null));
4340 if (!empty(
$conf->use_javascript_ajax)) {
4341 require_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
4347 if ($origin ==
'contrat') {
4348 $langs->load(
"admin");
4349 $text = $langs->trans(
"ToCreateARecurringInvoice");
4350 $text .=
' '.$langs->trans(
"ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv(
"MenuFinancial"), $langs->transnoentitiesnoconv(
"BillsCustomers"), $langs->transnoentitiesnoconv(
"ListOfTemplates"));
4352 $text .=
' '.$langs->trans(
"ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv(
'Module2300Name'));
4354 print
info_admin($text, 0, 0,
'info',
'').
'<br>';
4357 print
'<form name="add" action="'.$_SERVER[
"PHP_SELF"].
'" method="POST" id="formtocreate" name="formtocreate">';
4358 print
'<input type="hidden" name="token" value="'.newToken().
'">';
4359 print
'<input type="hidden" name="action" id="formtocreateaction" value="add">';
4360 print
'<input type="hidden" name="changecompany" value="0">';
4362 print
'<input type="hidden" name="socid" value="'.$soc->id.
'">'.
"\n";
4364 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
4365 if ($backtopageforcancel) {
4366 print
'<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.
'">';
4368 print
'<input name="ref" type="hidden" value="provisoire">';
4369 print
'<input name="ref_client" type="hidden" value="'.$ref_client.
'">';
4370 print
'<input name="force_cond_reglement_id" type="hidden" value="0">';
4371 print
'<input name="force_mode_reglement_id" type="hidden" value="0">';
4372 print
'<input name="force_fk_account" type="hidden" value="0">';
4373 print
'<input type="hidden" name="origin" value="'.$origin.
'">';
4374 print
'<input type="hidden" name="originid" value="'.$originid.
'">';
4375 print
'<input type="hidden" name="originentity" value="'.GETPOSTINT(
'originentity').
'">';
4376 if (!empty($currency_tx)) {
4377 print
'<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.
'">';
4383 $parameters = array();
4385 $reshook = $hookmanager->executeHooks(
'tabContentCreateInvoice', $parameters, $object, $action);
4386 if (empty($reshook)) {
4387 print
'<table class="border centpercent">';
4389 $exampletemplateinvoice =
new FactureRec($db);
4391 if (empty($origin) && empty($originid) &&
GETPOSTINT(
'fac_rec') > 0) {
4392 $invoice_predefined->fetch(
GETPOSTINT(
'fac_rec'));
4405 if ($soc->id > 0 && (!
GETPOSTINT(
'fac_rec') || !empty($invoice_predefined->frequency))) {
4407 print
'<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans(
'Customer').
'</td>';
4408 print
'<td colspan="2">';
4409 print $soc->getNomUrl(1,
'customer');
4410 print
'<input type="hidden" name="socid" value="'.$soc->id.
'">';
4412 $arrayoutstandingbills = $soc->getOutstandingBills();
4413 $outstandingBills = $arrayoutstandingbills[
'opened'];
4414 print
' - <span class="opacitymedium valignmiddle">'.$langs->trans(
'CurrentOutstandingBill').
':</span> ';
4415 print
'<span class="amount valignmiddle">'.price($outstandingBills, 0, $langs, 0, 0, -1,
$conf->currency).
'</span>';
4416 if ($soc->outstanding_limit !=
'') {
4417 if ($outstandingBills > $soc->outstanding_limit) {
4418 print img_warning($langs->trans(
"OutstandingBillReached"));
4420 print
' / '.price($soc->outstanding_limit, 0, $langs, 0, 0, -1,
$conf->currency);
4425 print
'<tr><td class="fieldrequired">'.$langs->trans(
'Customer').
'</td>';
4426 print
'<td colspan="2">';
4427 $filter =
'((s.client:IN:1,2,3) AND (s.status:=:1))';
4428 print img_picto(
'',
'company',
'class="pictofixedwidth"').$form->select_company($soc->id,
'socid', $filter,
'SelectThirdParty', 1, 0, array(), 0,
'minwidth300 widthcentpercentminusxx maxwidth500');
4432 $(document).ready(function() {
4433 $("#socid").change(function() {
4435 console.log("Submit page");
4436 $(\'input[name="action"]\').val(\'create\');
4437 $(\'input[name="force_cond_reglement_id"]\').val(\'1\');
4438 $(\'input[name="force_mode_reglement_id"]\').val(\'1\');
4439 $(\'input[name="force_fk_account"]\').val(\'1\');
4440 $("#formtocreate").submit(); */
4442 // For company change, we must submit page with action=create instead of action=add
4443 console.log("We have changed the company - Resubmit page");
4444 jQuery("input[name=changecompany]").val("1");
4445 jQuery("#formtocreateaction").val("create");
4446 jQuery("#formtocreate").submit();
4452 print
' <a class="valignmiddle" href="'.DOL_URL_ROOT.
'/societe/card.php?action=create&customer=3&fournisseur=0&backtopage='.urlencode($_SERVER[
"PHP_SELF"].
'?action=create').
'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans(
"AddThirdParty").
'"></span></a>';
4459 if (empty($origin) && empty($originid) &&
GETPOSTINT(
'fac_rec') > 0) {
4461 foreach ($invoice_predefined->array_options as $key => $option) {
4462 if (!isset(
$object->array_options[$key])) {
4463 $object->array_options[$key] = $invoice_predefined->array_options[$key];
4467 $dateinvoice = $invoice_predefined->date_when;
4468 if (empty($projectid)) {
4469 $projectid = $invoice_predefined->fk_project;
4471 $cond_reglement_id = $invoice_predefined->cond_reglement_id;
4472 $mode_reglement_id = $invoice_predefined->mode_reglement_id;
4473 $fk_account = $invoice_predefined->fk_account;
4474 $note_public = $invoice_predefined->note_public;
4475 $note_private = $invoice_predefined->note_private;
4477 if (!empty($invoice_predefined->multicurrency_code)) {
4478 $currency_code = $invoice_predefined->multicurrency_code;
4480 if (!empty($invoice_predefined->multicurrency_tx)) {
4481 $currency_tx = $invoice_predefined->multicurrency_tx;
4484 $sql =
'SELECT r.rowid, r.titre as title, r.total_ttc';
4485 $sql .=
' FROM '.MAIN_DB_PREFIX.
'facture_rec as r';
4486 $sql .=
' WHERE r.fk_soc = '.((int) $invoice_predefined->socid);
4488 $resql = $db->query($sql);
4490 $num = $db->num_rows($resql);
4494 print
'<tr><td>'.$langs->trans(
'CreateFromRepeatableInvoice').
'</td><td>';
4496 print
'<select class="flat" id="fac_rec" name="fac_rec">';
4497 print
'<option value="0" selected></option>';
4499 $objp = $db->fetch_object($resql);
4500 print
'<option value="'.$objp->rowid.
'"';
4503 $exampletemplateinvoice->fetch(
GETPOSTINT(
'fac_rec'));
4505 print
'>'.$objp->title.
' ('.
price($objp->total_ttc).
' '.$langs->trans(
"TTC").
')</option>';
4514 print
'<script type="text/javascript">
4515 $(document).ready(function() {
4516 $("#fac_rec").change(function() {
4517 console.log("We have changed the template invoice - Reload page");
4518 var fac_rec = $(this).val();
4519 var socid = $(\'#socid\').val();
4520 // 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.
4521 window.location.href = "'.$_SERVER[
"PHP_SELF"].
'?action=create&socid="+socid+"&fac_rec="+fac_rec;
4530 dol_print_error($db);
4534 print
'<tr><td class="tdtop fieldrequired titlefieldcreate">'.$langs->trans(
'Type').
'</td><td colspan="2">';
4535 print
'<div class="listofinvoicetypetable">'.
"\n";
4538 print
'<div class="listofinvoicetype"><div class="">';
4539 $tmp =
'<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOSTINT(
'type') ?
'' :
' checked').
'> ';
4540 $tmp .=
'<label for="radio_standard" >'.$langs->trans(
"InvoiceStandardAsk");
4541 $tmp .=
' <span class="opacitymedium">'.$langs->trans(
"InvoiceStandardAsk2").
'</span>';
4544 $desc = $form->textwithpicto($tmp, $langs->transnoentities(
"InvoiceStandardDesc").
'<br><br>'.$langs->transnoentities(
"YouMustCreateStandardInvoiceFirstDesc"), 1,
'help',
'nowraponall', 0, 3,
'standardonsmartphone');
4546 if ((($origin ==
'propal') || ($origin ==
'commande')) && (!empty($originid))) {
4556 print
'<span class="opacitymedium marginleftonly">' . $langs->trans(
'PercentOfOriginalObject') .
'</span>:<input class="right" placeholder="100%" type="text" id="valuestandardinvoice" name="valuestandardinvoice" size="3" value="' . (
GETPOSTISSET(
'valuestandardinvoice') ?
GETPOST(
'valuestandardinvoice',
'alpha') :
'100%') .
'"/>';
4559 print
'</div></div>'.
"\n";
4561 if ((empty($origin)) || ((($origin ==
'propal') || ($origin ==
'commande')) && (!empty($originid)))) {
4564 print
'<div class="listofinvoicetype"><div class="">';
4565 $tmp =
'<input type="radio" id="radio_deposit" name="type" value="3"'.(GETPOSTINT(
'type') == 3 ?
' checked' :
'').
'> ';
4566 print
'<script type="text/javascript">
4567 jQuery(document).ready(function() {
4568 jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
4569 jQuery("#radio_standard").prop("checked", true);
4571 jQuery("#typedeposit, #valuedeposit").click(function() {
4572 jQuery("#radio_deposit").prop("checked", true);
4574 jQuery("#typedeposit").change(function() {
4575 console.log("We change type of down payment: "+jQuery("#typedeposit").val());
4577 if (jQuery("#typedeposit").val() == "amount") {
4578 jQuery("#valuedeposit").attr("placeholder", "'.$langs->getCurrencySymbol(
$conf->currency).
'");
4579 jQuery("#valuedeposit").val("");
4581 jQuery("#valuedeposit").attr("placeholder", "50%");
4582 jQuery("#valuedeposit").val("");
4585 jQuery("#radio_deposit").prop("checked", true);
4586 setRadioForTypeOfInvoice();
4588 jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_creditnote, #radio_template").change(function() {
4589 setRadioForTypeOfInvoice();
4592 function setRadioForTypeOfInvoice() {
4593 console.log("Change radio for type of invoice");
4594 if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
4595 jQuery("#checkforselects").prop("disabled", true);
4596 jQuery("#checkforselects").prop("checked", false);
4597 jQuery(".checkforselect").prop("disabled", true);
4598 jQuery(".checkforselect").prop("checked", false);
4600 jQuery("#checkforselects").prop("disabled", false);
4601 jQuery("#checkforselects").prop("checked", true);
4602 jQuery(".checkforselect").prop("disabled", false);
4603 jQuery(".checkforselect").prop("checked", true);
4609 $tmp = $tmp.
'<label for="radio_deposit">'.$langs->trans(
"InvoiceDeposit").
'</label>';
4611 $desc = $form->textwithpicto($tmp, $langs->transnoentities(
"InvoiceDepositDesc"), 1,
'help',
'', 0, 3,
'depositonsmartphone');
4613 if (($origin ==
'propal') || ($origin ==
'commande')) {
4616 'amount' => $langs->transnoentitiesnoconv(
'FixAmount', $langs->transnoentitiesnoconv(
'Deposit')),
4617 'variable' => $langs->transnoentitiesnoconv(
'VarAmountOneLine', $langs->transnoentitiesnoconv(
'Deposit')),
4618 'variablealllines' => $langs->transnoentitiesnoconv(
'VarAmountAllLines')
4622 'variablealllines' => $langs->transnoentitiesnoconv(
'VarAmountAllLines')
4626 $typedeposit =
GETPOST(
'typedeposit',
'aZ09');
4628 if (empty($typedeposit) && !empty($objectsrc->deposit_percent)) {
4629 $origin_payment_conditions_deposit_percent =
getDictionaryValue(
'c_payment_term',
'deposit_percent', $objectsrc->cond_reglement_id);
4630 if (!empty($origin_payment_conditions_deposit_percent)) {
4631 $typedeposit =
'variable';
4634 if (empty($valuedeposit) && $typedeposit ==
'variable' && !empty($objectsrc->deposit_percent)) {
4635 $valuedeposit = $objectsrc->deposit_percent;
4637 print
'<span class="marginleftonly">'.$form->selectarray(
'typedeposit', $arraylist, $typedeposit, 0, 0, 0,
'', 1).
'</span>';
4639 print
'<input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="'.($valuedeposit ? $valuedeposit :
'').
'"'.($valuedeposit ?
'' :
'placeholder="'.$langs->getCurrencySymbol(
$conf->currency).
'"').
'>';
4642 print
'</div></div>'.
"\n";
4649 print
'<div class="listofinvoicetype"><div class="">';
4650 $tmp =
'<input id="radio_situation" type="radio" name="type" value="5"'.(GETPOST(
'type') == 5 ?
' checked' :
'').
'> ';
4651 $tmp = $tmp.
'<label for="radio_situation" >'.$langs->trans(
"InvoiceFirstSituationAsk").
'</label>';
4653 $desc = $form->textwithpicto($tmp, $langs->transnoentities(
"InvoiceFirstSituationDesc"), 1,
'help',
'', 0, 3,
'firstsituationonsmartphone');
4657 $opt = $form->selectSituationInvoices((
string)
GETPOSTINT(
'originid'), $socid);
4660 print
'</div></div><div class="listofinvoicetype"><div>';
4662 $tmp =
'<input id="radio_situation_bis" type="radio" name="type" value="5"'.(GETPOST(
'type') == 5 &&
GETPOSTINT(
'originid') ?
' checked' :
'');
4663 if ($opt == (
'<option value="0" selected>'.$langs->trans(
'NoSituations').
'</option>') || (
GETPOST(
'origin') &&
GETPOST(
'origin') !=
'facture' &&
GETPOST(
'origin') !=
'commande')) {
4664 $tmp .=
' disabled';
4667 $text = $tmp.
'<label for="radio_situation_bis">'.$langs->trans(
"InvoiceSituationAsk").
'</label> ';
4669 $text .=
'<select class="flat minwidth125" id="situations" name="situations"';
4670 if ($opt == (
'<option value="0" selected>'.$langs->trans(
'NoSituations').
'</option>') || (
GETPOST(
'origin') &&
GETPOST(
'origin') !=
'facture' &&
GETPOST(
'origin') !=
'commande')) {
4671 $text .=
' disabled';
4675 $text .=
'</select>';
4676 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceSituationDesc"), 1,
'help',
'', 0, 3);
4678 print
'</div></div>'.
"\n";
4684 $facids = $facturestatic->list_replacable_invoices($soc->id);
4686 dol_print_error($db, $facturestatic->error, $facturestatic->errors);
4690 if (is_array($facids)) {
4691 foreach ($facids as $facparam) {
4692 $options .=
'<option value="'.$facparam [
'id'].
'"';
4693 if ($facparam[
'id'] ==
GETPOSTINT(
'fac_replacement')) {
4694 $options .=
' selected';
4696 $options .=
'>'.$facparam[
'ref'];
4697 $options .=
' ('.$facturestatic->LibStatut($facparam[
'paid'], $facparam[
'status'], 0, $facparam[
'alreadypaid']).
')';
4698 $options .=
'</option>';
4702 print
'<!-- replacement line -->';
4703 print
'<div class="listofinvoicetype"><div class="">';
4704 $tmp =
'<input type="radio" name="type" id="radio_replacement" value="1"'.(GETPOST(
'type') == 1 ?
' checked' :
'');
4705 if (!$options || $invoice_predefined->id > 0) {
4706 $tmp .=
' disabled';
4709 print
'<script type="text/javascript">
4710 jQuery(document).ready(function() {
4711 jQuery("#fac_replacement").change(function() {
4712 console.log("We change fac_replacement");
4713 jQuery("#radio_replacement").prop("checked", true);
4717 $text = $tmp.
'<label for="radio_replacement">'.$langs->trans(
"InvoiceReplacementAsk").
'</label>';
4718 $text .=
'<select class="flat" name="fac_replacement" id="fac_replacement"';
4719 if (!$options || $invoice_predefined->id > 0) {
4720 $text .=
' disabled';
4724 $text .=
'<option value="-1"> </option>';
4727 $text .=
'<option value="-1">'.$langs->trans(
"NoReplacableInvoice").
'</option>';
4729 $text .=
'</select>';
4730 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceReplacementDesc"), 1,
'help',
'', 0, 3);
4732 print
'</div></div>'.
"\n";
4736 print
'<div class="listofinvoicetype"><div class="">';
4737 $tmp =
'<input type="radio" name="type" id="radio_situation" value="0" disabled> ';
4738 $text = $tmp.
'<label class="opacitymedium">'.$langs->trans(
"InvoiceSituationAsk").
'</label> ';
4739 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceFirstSituationDesc").
'<br><br>'.$langs->trans(
"YouMustCreateInvoiceFromThird"), 1,
'help',
'nowraponall', 0, 3,
'firstsituationonsmartphone');
4741 print
'</div></div>'.
"\n";
4744 print
'<div class="listofinvoicetype"><div class="">';
4745 $tmp =
'<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
4746 $text = $tmp.
'<label for="radio_replacement" class="opacitymedium">'.$langs->trans(
"InvoiceReplacement").
'</label> ';
4747 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceReplacementDesc").
'<br><br>'.$langs->trans(
"YouMustCreateInvoiceFromThird"), 1,
'help',
'nowraponall', 0, 3,
'replacementonsmartphone');
4749 print
'</div></div>'.
"\n";
4752 if (empty($origin)) {
4757 $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
4759 dol_print_error($db, $facturestatic->error, $facturestatic->errors);
4763 $newinvoice_static =
new Facture($db);
4764 foreach ($facids as $key => $valarray) {
4765 $newinvoice_static->id = $key;
4766 $newinvoice_static->ref = $valarray [
'ref'];
4767 $newinvoice_static->statut = $valarray [
'status'];
4768 $newinvoice_static->status = $valarray [
'status'];
4769 $newinvoice_static->type = $valarray [
'type'];
4770 $newinvoice_static->paye = $valarray [
'paye'];
4771 $newinvoice_static->paid = $valarray [
'paye'];
4772 $newinvoice_static->multicurrency_code = (string) $valarray[
'multicurrency_code'];
4774 $optionsav .=
'<option value="'.$key.
'"';
4775 if ($key ==
GETPOST(
'fac_avoir')) {
4776 $optionsav .=
' selected';
4779 $newinvoice_static->fetch_optionals($key);
4780 $object->array_options = $newinvoice_static->array_options;
4783 $currency_code = $newinvoice_static->multicurrency_code;
4786 $optionsav .= $newinvoice_static->ref;
4787 $optionsav .=
' ('.$newinvoice_static->getLibStatut(1, $valarray [
'paymentornot']).
')';
4788 $optionsav .=
'</option>';
4791 print
'<div class="listofinvoicetype"><div class="">';
4792 $tmp =
'<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST(
'type') == 2 ?
' checked' :
'');
4793 if ((!$optionsav && !
getDolGlobalString(
'INVOICE_CREDIT_NOTE_STANDALONE')) || $invoice_predefined->id > 0) {
4794 $tmp .=
' disabled';
4798 print
'<script type="text/javascript">
4799 jQuery(document).ready(function() {
4800 if (jQuery("#radio_creditnote").is(":checked")) {
4801 jQuery("#radio_standard").prop("disabled", true);
4802 jQuery("#radio_deposit").prop("disabled", true);
4804 jQuery("#radio_standard").prop("disabled", false);
4805 jQuery("#radio_deposit").prop("disabled", false);
4807 if (! jQuery("#radio_creditnote").is(":checked")) {
4808 jQuery("#credit_note_options").hide();
4810 jQuery("#radio_creditnote").click(function() {
4811 jQuery("#credit_note_options").show();
4813 jQuery("#radio_standard, #radio_replacement, #radio_deposit, #radio_situation, #radio_situation_bis").click(function() {
4814 console.log("We click on a radio to close credit not options");
4815 jQuery("#credit_note_options").hide();
4819 $text =
'<label>'.$tmp.$langs->transnoentities(
"InvoiceAvoirAsk").
'</label> ';
4820 $text .=
'<select class="flat valignmiddle minwidth200" name="fac_avoir" id="fac_avoir"';
4821 if (!$optionsav || $invoice_predefined->id > 0) {
4822 $text .=
' disabled';
4826 $text .=
'<option value="-1">'.$langs->trans(
"InvoiceAvoirAskCombo").
'</option>';
4827 $text .= $optionsav;
4829 $text .=
'<option value="-1">'.$langs->trans(
"NoInvoiceToCorrect").
'</option>';
4831 $text .=
'</select>';
4832 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceAvoirDesc"), 1,
'help',
'', 0, 3);
4835 print
'<div id="credit_note_options" class="clearboth paddingtop marginbottomonly">';
4836 print
'<div class="marginleftlargeondesktop"><input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOSTINT(
'invoiceAvoirWithLines') > 0 ?
'checked' :
'').
' /> <label for="invoiceAvoirWithLines" class="small">'.$langs->trans(
'invoiceAvoirWithLines').
"</label></div>";
4837 print
'<div class="marginleftlargeondesktop"><input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOSTINT(
'invoiceAvoirWithPaymentRestAmount') > 0 ?
'checked' :
'').
' /> <label for="invoiceAvoirWithPaymentRestAmount" class="small">'.$langs->trans(
'invoiceAvoirWithPaymentRestAmount').
"</label></div>";
4842 print
'</div></div>'.
"\n";
4845 print
'<div class="listofinvoicetype"><div class="">';
4847 $tmp =
'<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
4849 $tmp =
'<input type="radio" name="type" id="radio_creditnote" value="2" > ';
4851 $text = $tmp.
'<label class="opacitymedium" for="radio_creditnote">'.$langs->trans(
"InvoiceAvoir").
'</label> ';
4853 $desc = $form->textwithpicto($text, $langs->transnoentities(
"InvoiceAvoirDesc").
'<br><br>'.$langs->trans(
"CreateCreditNoteWhenClientInvoiceExists"), 1,
'help',
'', 0, 3,
'creditnoteonsmartphone');
4855 print
'</div></div>'.
"\n";
4876 foreach ($listtType as $type) {
4877 $thisTypeConfName =
'FACTURE_ADDON_PDF_'.$type;
4879 $jsListType .= (!empty($jsListType) ?
',' :
'').
'"'.$type.
'":"'.$current.
'"';
4882 print
'<script type="text/javascript">
4883 $(document).ready(function() {
4884 var listType = {'.$jsListType.
'};
4885 $("[name=\'type\']").change(function() {
4886 console.log("change name=type");
4887 if ($( this ).prop("checked"))
4889 if(($( this ).val() in listType))
4891 $("#model").val(listType[$( this ).val()]).trigger("change");
4908 print
'<tr><td class="fieldrequired">'.$langs->trans(
'InvoiceSubtype').
'</td><td colspan="2">';
4909 print $form->getSelectInvoiceSubtype(
GETPOSTINT(
'subtype'),
'subtype', 1, 0,
'');
4915 print
'<tr><td>'.$langs->trans(
'DiscountStillRemaining').
'</td><td colspan="2">';
4919 $backtopage = $_SERVER[
"PHP_SELF"].
'?socid='.$thirdparty->id.
'&action='.$action.
'&origin='.urlencode((
string) (
GETPOST(
'origin'))).
'&originid='.urlencode((
string) (
GETPOSTINT(
'originid')));
4922 $defaulttpldir =
'/core/tpl';
4923 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
4924 foreach ($dirtpls as
$module => $reldir) {
4929 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/object_discounts.tpl.php';
4931 if (file_exists($tpl)) {
4932 if (empty(
$conf->file->strict_mode)) {
4933 $res = @include $tpl;
4935 $res = include $tpl;
4950 print
'<tr><td class="fieldrequired">'.$langs->trans(
'DateInvoice').
'</td><td colspan="2">';
4951 print img_picto(
'',
'action',
'class="pictofixedwidth"');
4952 print $form->selectDate($newdateinvoice ? $newdateinvoice : $dateinvoice,
'', 0, 0, 0,
"add", 1, 1);
4957 print
'<tr><td class="fieldrequired">'.$langs->trans(
'DatePointOfTax').
'</td><td colspan="2">';
4958 print img_picto(
'',
'action',
'class="pictofixedwidth"');
4959 print $form->selectDate($date_pointoftax ? $date_pointoftax : -1,
'date_pointoftax', 0, 0, 0,
"add", 1, 1);
4964 print
'<tr><td class="nowrap fieldrequired">'.$langs->trans(
'PaymentConditionsShort').
'</td><td colspan="2">';
4965 print img_picto(
'',
'payment',
'class="pictofixedwidth"');
4966 print $form->getSelectConditionsPaiements((
int) $cond_reglement_id,
'cond_reglement_id', -1, 1, 0,
'maxwidth500 widthcentpercentminusx');
4971 $rwStyle =
'display:none;';
4972 if (in_array(
GETPOSTINT(
'type'), $retainedWarrantyInvoiceAvailableType)) {
4976 $retained_warranty =
GETPOSTINT(
'retained_warranty');
4977 if (empty($retained_warranty)) {
4978 if ($objectsrc !==
null && property_exists($objectsrc,
'retained_warranty') && !empty($objectsrc->retained_warranty)) {
4980 $retained_warranty = $objectsrc->retained_warranty;
4983 $retained_warranty_js_default = !empty($retained_warranty) ? $retained_warranty :
getDolGlobalString(
'INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT');
4985 print
'<tr class="retained-warranty-line" style="'.$rwStyle.
'" ><td class="nowrap">'.$langs->trans(
'RetainedWarranty').
'</td><td colspan="2">';
4986 print
'<input id="new-situation-invoice-retained-warranty" name="retained_warranty" type="number" value="'.$retained_warranty.
'" step="0.01" min="0" max="100" />%';
4989 print
'<tr class="retained-warranty-line" style="'.$rwStyle.
'" ><td class="nowrap">'.$langs->trans(
'PaymentConditionsShortRetainedWarranty').
'</td><td colspan="2">';
4990 $retained_warranty_fk_cond_reglement =
GETPOSTINT(
'retained_warranty_fk_cond_reglement');
4991 if (empty($retained_warranty_fk_cond_reglement)) {
4992 $retained_warranty_fk_cond_reglement =
getDolGlobalString(
'INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID');
4993 if ($objectsrc instanceOf
Facture && !empty($objectsrc->retained_warranty_fk_cond_reglement)) {
4995 $retained_warranty_fk_cond_reglement = $objectsrc->retained_warranty_fk_cond_reglement;
4998 print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement,
'retained_warranty_fk_cond_reglement', -1, 1);
5001 print
'<script type="text/javascript">
5002 $(document).ready(function() {
5003 $("[name=\'type\']").change(function() {
5004 if($( this ).prop("checked") && $.inArray($( this ).val(), '.json_encode($retainedWarrantyInvoiceAvailableType).
' ) !== -1)
5006 $(".retained-warranty-line").show();
5007 $("#new-situation-invoice-retained-warranty").val("'.(float) $retained_warranty_js_default.
'");
5010 $(".retained-warranty-line").hide();
5011 $("#new-situation-invoice-retained-warranty").val("");
5015 $("[name=\'type\']:checked").trigger("change");
5021 print
'<tr><td>'.$langs->trans(
'PaymentMode').
'</td><td colspan="2">';
5022 print img_picto(
'',
'bank',
'class="pictofixedwidth"');
5023 print $form->select_types_paiements((
string) $mode_reglement_id,
'mode_reglement_id',
'CRDT', 0, 1, 0, 0, 1,
'maxwidth250 widthcentpercentminusx', 1);
5028 print
'<tr><td>'.$langs->trans(
'DefaultBankAccount').
'</td><td colspan="2">';
5029 print img_picto(
'',
'bank_account',
'class="pictofixedwidth"');
5030 print $form->select_comptes((
int) $fk_account,
'fk_account', 0,
'', 1,
'', 0,
'maxwidth250 widthcentpercentminusx', 1);
5036 print
'<tr><td>'.$langs->trans(
'Source').
'</td><td>';
5037 print img_picto(
'',
'question',
'class="pictofixedwidth"');
5038 $form->selectInputReason((
string) $inputReasonId,
'input_reason_id',
'', 1,
'maxwidth250 widthcentpercentminusx');
5041 print
'<input type="hidden" name="input_reason_id" value="'.((string) $inputReasonId).
'">';
5045 if (
isModEnabled(
'project') && is_object($formproject)) {
5046 $langs->load(
'projects');
5047 print
'<tr><td>'.$langs->trans(
'Project').
'</td><td colspan="2">';
5048 print img_picto(
'',
'project',
'class="pictofixedwidth"');
5050 print $formproject->select_projects((($socid > 0 && !
getDolGlobalString(
'PROJECT_CAN_ALWAYS_LINK_TO_ALL_CUSTOMERS')) ? $socid : -1), (string) $projectid,
'projectid', 0, 0, 1, 1, 0, 0, 0,
'', 1, 0,
'maxwidth500 widthcentpercentminusxx');
5051 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>';
5058 print
'<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans(
"IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms :
'', 1).
'</label></td>';
5059 print
'<td colspan="2" class="maxwidthonsmartphone">';
5060 $incoterm_id =
GETPOST(
'incoterm_id');
5061 $location_incoterms =
GETPOST(
'location_incoterms');
5062 if (empty($incoterm_id)) {
5063 $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
5064 $location_incoterms = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
5066 print img_picto(
'',
'incoterm',
'class="pictofixedwidth"');
5067 print $form->select_incoterms($incoterm_id, $location_incoterms);
5081 print
'<tr><td>'.$langs->trans(
"Categories").
'</td><td colspan="3">';
5082 print $form->selectCategories(Categorie::TYPE_INVOICE,
'categories', $object);
5087 $parameters = array(
'objectsrc' => !empty($objectsrc) ? $objectsrc : 0,
'colspan' =>
' colspan="2"',
'cols' =>
'2',
'socid' => $socid);
5088 $reshook = $hookmanager->executeHooks(
'formObjectOptions', $parameters, $object, $action);
5089 print $hookmanager->resPrint;
5090 if (empty($reshook)) {
5091 if (
getDolGlobalString(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE') && !empty($soc->id)) {
5094 $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
5095 if ($soc->fetch_optionals() > 0) {
5096 $object->array_options = array_merge(
$object->array_options, $soc->array_options);
5100 print
$object->showOptionals($extrafields,
'create', $parameters);
5104 include_once DOL_DOCUMENT_ROOT.
'/core/modules/facture/modules_facture.php';
5106 if (is_array($list) && count($list) > 0) {
5110 $paramkey =
'FACTURE_ADDON_PDF_'.$type;
5115 if (count($list) > 1) {
5116 print
'<tr><td>'.$langs->trans(
'Model').
'</td>';
5117 print
'<td colspan="2">';
5118 print img_picto(
'',
'pdf',
'class="pictofixedwidth"');
5119 print $form->selectarray(
'model', $list, $preselected, 0, 0, 0,
'', 0, 0, 0,
'',
'maxwidth200 widthcentpercentminusx', 1);
5122 print
'<input type="hidden" name="model" value="'.$preselected.
'">';
5129 print
'<td>'.$form->editfieldkey(
'Currency',
'multicurrency_code',
'', $object, 0).
'</td>';
5130 print
'<td colspan="2" class="maxwidthonsmartphone">';
5131 print img_picto(
'',
'currency',
'class="pictofixedwidth"');
5132 print $form->selectMultiCurrency(((
GETPOSTISSET(
'multicurrency_code') && !
GETPOST(
'changecompany')) ?
GETPOST(
'multicurrency_code') : $currency_code),
'multicurrency_code', 0,
'', false,
'maxwidth200 widthcentpercentminusx');
5139 $dateexample = ($newdateinvoice ? $newdateinvoice : $dateinvoice);
5140 if (empty($dateexample)) {
5143 $substitutionarray = array(
5144 '__TOTAL_HT__' => $langs->trans(
"AmountHT").
' ('.$langs->trans(
"Example").
': '.
price($exampletemplateinvoice->total_ht).
')',
5145 '__TOTAL_TTC__' => $langs->trans(
"AmountTTC").
' ('.$langs->trans(
"Example").
': '.
price($exampletemplateinvoice->total_ttc).
')',
5146 '__INVOICE_PREVIOUS_MONTH__' => $langs->trans(
"PreviousMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, -1,
'm'),
'%m').
')',
5147 '__INVOICE_MONTH__' => $langs->trans(
"MonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date($dateexample,
'%m').
')',
5148 '__INVOICE_NEXT_MONTH__' => $langs->trans(
"NextMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, 1,
'm'),
'%m').
')',
5149 '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans(
"TextPreviousMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, -1,
'm'),
'%B').
')',
5150 '__INVOICE_MONTH_TEXT__' => $langs->trans(
"TextMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date($dateexample,
'%B').
')',
5151 '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans(
"TextNextMonthOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, 1,
'm'),
'%B').
')',
5152 '__INVOICE_PREVIOUS_YEAR__' => $langs->trans(
"PreviousYearOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, -1,
'y'),
'%Y').
')',
5153 '__INVOICE_YEAR__' => $langs->trans(
"YearOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date($dateexample,
'%Y').
')',
5154 '__INVOICE_NEXT_YEAR__' => $langs->trans(
"NextYearOfInvoice").
' ('.$langs->trans(
"Example").
': '.
dol_print_date(
dol_time_plus_duree($dateexample, 1,
'y'),
'%Y').
')'
5157 $htmltext =
'<i>'.$langs->trans(
"FollowingConstantsWillBeSubstituted").
':<br>';
5158 foreach ($substitutionarray as $key => $val) {
5159 $htmltext .= $key.
' = '.$langs->trans($val).
'<br>';
5161 $htmltext .=
'</i>';
5166 print
'<td class="tdtop">';
5167 print $form->textwithpicto($langs->trans(
'NotePublic'), $htmltext);
5169 print
'<td valign="top" colspan="2">';
5170 $doleditor =
new DolEditor(
'note_public', (
string) $note_public,
'', 80,
'dolibarr_notes',
'In',
false,
false, !
getDolGlobalString(
'FCKEDITOR_ENABLE_NOTE_PUBLIC') ? 0 : 1, ROWS_3,
'90%');
5171 print $doleditor->Create(1);
5174 if (empty($user->socid)) {
5176 print
'<td class="tdtop">';
5177 print $form->textwithpicto($langs->trans(
'NotePrivate'), $htmltext);
5179 print
'<td valign="top" colspan="2">';
5180 $doleditor =
new DolEditor(
'note_private', (
string) $note_private,
'', 80,
'dolibarr_notes',
'In',
false,
false, !
getDolGlobalString(
'FCKEDITOR_ENABLE_NOTE_PRIVATE') ? 0 : 1, ROWS_3,
'90%');
5181 print $doleditor->Create(1);
5187 if (!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($classname)) {
5188 $langs->loadLangs(array(
'orders',
'propal'));
5191 if ($origin ==
'contrat') {
5192 '@phan-var-force Contrat $objectsrc';
5194 $objectsrc->update_price(1,
'auto', 1);
5197 print
"\n<!-- Show ref of origin ".$classname.
" -->\n";
5198 print
'<input type="hidden" name="amount" value="'.$objectsrc->total_ht.
'">'.
"\n";
5199 print
'<input type="hidden" name="total" value="'.$objectsrc->total_ttc.
'">'.
"\n";
5200 print
'<input type="hidden" name="tva" value="'.$objectsrc->total_tva.
'">'.
"\n";
5205 switch (get_class($objectsrc)) {
5207 $newclassname =
'CommercialProposal';
5210 $newclassname =
'Order';
5213 $newclassname =
'Sending';
5216 $newclassname =
'Contract';
5219 $newclassname =
'Intervention';
5222 $newclassname = get_class($objectsrc);
5226 print
'<tr><td>'.$langs->trans($newclassname).
'</td>';
5227 print
'<td colspan="2">';
5228 print $objectsrc->getNomUrl(1);
5230 $objectsrc->fetchObjectLinked($originid, $origin,
null,
'facture');
5231 if (isset($objectsrc->linkedObjects[
'facture']) && is_array($objectsrc->linkedObjects[
'facture']) && count($objectsrc->linkedObjects[
'facture']) >= 1) {
5232 setEventMessages(
'WarningBillExist',
null,
'warnings');
5233 echo
' - '.$langs->trans(
'LatestRelatedBill').
' '.end($objectsrc->linkedObjects[
'facture'])->getNomUrl(1);
5237 print
'<tr><td>'.$langs->trans(
'AmountHT').
'</td><td colspan="2">'.
price($objectsrc->total_ht, 1, $langs, 1, -1,
'',
$conf->currency).
'</td></tr>';
5238 print
'<tr><td>'.$langs->trans(
'AmountVAT').
'</td><td colspan="2">'.
price($objectsrc->total_tva, 1, $langs, 1, -1,
'',
$conf->currency).
"</td></tr>";
5239 if (
$mysoc->localtax1_assuj ==
"1" || $objectsrc->total_localtax1 != 0) {
5240 print
'<tr><td>'.$langs->transcountry(
"AmountLT1",
$mysoc->country_code).
'</td><td colspan="2">'.
price($objectsrc->total_localtax1, 1, $langs, 1, -1,
'',
$conf->currency).
"</td></tr>";
5243 if (
$mysoc->localtax2_assuj ==
"1" || $objectsrc->total_localtax2 != 0) {
5244 print
'<tr><td>'.$langs->transcountry(
"AmountLT2",
$mysoc->country_code).
'</td><td colspan="2">'.
price($objectsrc->total_localtax2, 1, $langs, 1, -1,
'',
$conf->currency).
"</td></tr>";
5246 print
'<tr><td>'.$langs->trans(
'AmountTTC').
'</td><td colspan="2">'.
price($objectsrc->total_ttc, 1, $langs, 1, -1,
'',
$conf->currency).
"</td></tr>";
5248 if (
isModEnabled(
'multicurrency') && $objectsrc->multicurrency_code !=
$conf->currency) {
5250 print
'<tr><td>'.$langs->trans(
'MulticurrencyAmountHT').
'</td><td colspan="2">'.
price($objectsrc->multicurrency_total_ht, 1, $langs, 1, -1,
'', $objectsrc->multicurrency_code).
'</td></tr>';
5251 print
'<tr><td>'.$langs->trans(
'MulticurrencyAmountVAT').
'</td><td colspan="2">'.
price($objectsrc->multicurrency_total_tva, 1, $langs, 1, -1,
'', $objectsrc->multicurrency_code).
"</td></tr>";
5252 print
'<tr><td>'.$langs->trans(
'MulticurrencyAmountTTC').
'</td><td colspan="2">'.
price($objectsrc->multicurrency_total_ttc, 1, $langs, 1, -1,
'', $objectsrc->multicurrency_code).
"</td></tr>";
5260 print $form->buttonsSaveCancel(
"CreateDraft");
5263 if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
5266 $title = $langs->trans(
'ProductsAndServices');
5269 print
'<div class="div-table-responsive-no-min">';
5270 print
'<table class="noborder centpercent">';
5272 $objectsrc->printOriginLinesList(
'', $selectedLines);
5279} elseif ($id > 0 || !empty($ref)) {
5281 $langs->load(
'errors');
5282 echo
'<div class="error">'.$langs->trans(
"ErrorRecordNotFound").
'</div>';
5291 if ($user->socid > 0 && $user->socid !=
$object->socid) {
5295 $result =
$object->fetch_thirdparty();
5297 $result = $soc->fetch(
$object->socid);
5299 dol_print_error($db);
5301 $selleruserevenustamp =
$mysoc->useRevenueStamp();
5303 $totalpaid =
$object->getSommePaiement();
5304 $totalcreditnotes =
$object->getSumCreditNotesUsed();
5305 $totaldeposits =
$object->getSumDepositsUsed();
5311 $resteapayer =
price2num(
$object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits,
'MT');
5315 $multicurrency_totalpaid =
$object->getSommePaiement(1);
5316 $multicurrency_totalcreditnotes =
$object->getSumCreditNotesUsed(1);
5317 $multicurrency_totaldeposits =
$object->getSumDepositsUsed(1);
5318 $multicurrency_resteapayer =
price2num(
$object->multicurrency_total_ttc - $multicurrency_totalpaid - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits,
'MT');
5322 if ($resteapayer == 0 && $multicurrency_resteapayer != 0 &&
$object->multicurrency_code !=
$conf->currency) {
5323 $resteapayer =
price2num((
float) $multicurrency_resteapayer /
$object->multicurrency_tx,
'MT');
5327 if (
$object->paye ||
$object->status == $object::STATUS_CLOSED) {
5330 $resteapayeraffiche = $resteapayer;
5333 $filterabsolutediscount =
"fk_facture_source IS NULL";
5334 $filtercreditnote =
"fk_facture_source IS NOT NULL";
5336 $filterabsolutediscount =
"fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
5337 $filtercreditnote =
"fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
5340 $absolute_discount = $soc->getAvailableDiscounts(
null, $filterabsolutediscount);
5341 $absolute_creditnote = $soc->getAvailableDiscounts(
null, $filtercreditnote);
5342 $absolute_discount =
price2num($absolute_discount,
'MT');
5343 $absolute_creditnote =
price2num($absolute_creditnote,
'MT');
5345 $nb_creditnote_notyetavailable = $soc->getOpenCreditNotesNotYetConvertedIntoDiscount(0);
5347 $author =
new User($db);
5348 if (
$object->user_creation_id) {
5349 $author->fetch(
$object->user_creation_id);
5352 $objectidnext =
$object->getIdReplacingInvoice();
5356 print
dol_get_fiche_head($head,
'compta', $langs->trans(
'InvoiceCustomer'), -1,
$object->picto, 0,
'',
'', 0,
'', 1);
5361 if ($action ==
'converttoreduc') {
5363 $type_fac =
'ExcessReceived';
5365 $type_fac =
'CreditNote';
5367 $type_fac =
'Deposit';
5371 $text = $langs->trans(
'ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac)));
5372 $text .=
'<br>'.$langs->trans(
'ConfirmConvertToReduc2');
5373 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, $langs->trans(
'ConvertToReduc'), $text,
'confirm_converttoreduc',
'',
"yes", 2);
5377 if ($action ==
'delete') {
5378 $text = $langs->trans(
'ConfirmDeleteBill',
$object->ref);
5379 $formquestion = array();
5382 $qualified_for_stock_change = 0;
5384 $qualified_for_stock_change =
$object->hasProductsOrServices(2);
5386 $qualified_for_stock_change =
$object->hasProductsOrServices(1);
5389 if ($qualified_for_stock_change) {
5390 $langs->load(
"stocks");
5391 require_once DOL_DOCUMENT_ROOT.
'/product/class/html.formproduct.class.php';
5395 if (
$conf->browser->name ==
'ie') {
5398 $formquestion = array(
5402 array(
'type' =>
'other',
'name' =>
'idwarehouse',
'label' => $label,
'value' => $formproduct->selectWarehouses(
GETPOST(
'idwarehouse') ?
GETPOST(
'idwarehouse') :
'ifone',
'idwarehouse',
'', 1, 0, 0, $langs->trans(
"NoStockAction"), 0, $forcecombo))
5404 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, $langs->trans(
'DeleteBill'), $text,
'confirm_delete', $formquestion,
"yes", 1);
5406 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, $langs->trans(
'DeleteBill'), $text,
'confirm_delete',
'',
'no', 1);
5409 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, $langs->trans(
'DeleteBill'), $text,
'confirm_delete',
'',
'no', 1);
5414 if ($action ==
'situationout') {
5415 $text = $langs->trans(
'ConfirmRemoveSituationFromCycle',
$object->ref);
5416 $label = $langs->trans(
"ConfirmOuting");
5417 $formquestion = array();
5422 &&
$object->is_last_in_cycle()
5423 && $usercanunvalidate
5425 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, $label, $text,
'confirm_situationout', $formquestion,
"yes", 1);
5430 if ($action ==
'valid') {
5432 $objectref = substr(
$object->ref, 1, 4);
5433 if ($objectref ==
'PROV') {
5437 $object->date_lim_reglement =
$object->calculate_date_lim_reglement();
5439 $numref =
$object->getNextNumRef($soc);
5442 $numref = (string)
$object->ref;
5445 $text = $langs->trans(
'ConfirmValidateBill', $numref);
5447 $text .=
'<br><br>';
5448 $text .= img_picto(
'',
'warning',
'class="pictofixedwidth"').
' '.$langs->trans(
'WarningInvoiceCanNeverBeEdited');
5451 require_once DOL_DOCUMENT_ROOT.
'/core/class/notify.class.php';
5452 $notify =
new Notify($db);
5454 $text .= $notify->confirmMessage(
'BILL_VALIDATE',
$object->socid, $object);
5456 $formquestion = array();
5459 $qualified_for_stock_change = 0;
5461 $qualified_for_stock_change =
$object->hasProductsOrServices(2);
5463 $qualified_for_stock_change =
$object->hasProductsOrServices(1);
5466 if ($qualified_for_stock_change) {
5467 $langs->load(
"stocks");
5468 require_once DOL_DOCUMENT_ROOT.
'/product/class/html.formproduct.class.php';
5469 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
5472 $warehouse_array = $warehouse->list_array();
5473 if (count($warehouse_array) == 1) {
5474 $label =
$object->type ==
Facture::TYPE_CREDIT_NOTE ? $langs->trans(
"WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans(
"WarehouseForStockDecrease", current($warehouse_array));
5475 $value =
'<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).
'">';
5478 $value = $formproduct->selectWarehouses(
GETPOST(
'idwarehouse') ?
GETPOST(
'idwarehouse') :
'ifone',
'idwarehouse',
'', 1);
5480 $formquestion = array(
5486 array(
'type' =>
'other',
'name' =>
'idwarehouse',
'label' => $label,
'value' => $value));
5490 $text .=
'<br>'.img_warning().
' '.$langs->trans(
"ErrorInvoiceOfThisTypeMustBePositive");
5495 foreach (
$object->lines as $line) {
5496 $res = $line->fetch_product();
5498 if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end))) {
5504 if ($nbMandated > 0) {
5506 setEventMessages($langs->trans(
"mandatoryPeriodNeedTobeSetMsgValidate"),
null,
'errors');
5509 $text .=
'<div><span class="clearboth nowraponall warning">'.img_warning().$langs->trans(
"mandatoryPeriodNeedTobeSetMsgValidate").
'</span></div>';
5514 $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, 0);
5519 if ($action ==
'modif') {
5522 $testvalue =
$object->isEditable();
5523 if ($testvalue < 0) {
5524 switch ($testvalue) {
5527 setEventMessages($langs->trans(
"DisabledBecauseDispatchedInBookkeeping"),
null,
'errors');
5531 setEventMessages($langs->trans(
"DisabledBecauseNotLastInvoice"),
null,
'errors');
5535 setEventMessages($langs->trans(
"DisabledBecauseNotLastSituationInvoice"),
null,
'errors');
5539 setEventMessages($langs->trans(
"DisabledBecauseThereIsAPayment"),
null,
'errors');
5543 setEventMessages($langs->trans(
"DisabledBecauseAlreadySentByEmail"),
null,
'errors');
5547 setEventMessages($langs->trans(
"DisabledBecauseAlreadyPrintedOnce"),
null,
'errors');
5551 setEventMessages($langs->trans(
"DisabledBecauseVersionProtected").(empty(
$object->error) ?
'' :
': '.
$object->error), null,
'errors');
5555 setEventMessages($langs->trans(
"DisabledBecauseNotEditable").(empty(
$object->error) ?
': UnknownReason' :
': '.
$object->error), null,
'errors');
5563 $text = $langs->trans(
'ConfirmUnvalidateBill',
$object->ref);
5564 $formquestion = array();
5567 $qualified_for_stock_change = 0;
5569 $qualified_for_stock_change =
$object->hasProductsOrServices(2);
5571 $qualified_for_stock_change =
$object->hasProductsOrServices(1);
5574 if ($qualified_for_stock_change) {
5575 $langs->load(
"stocks");
5576 require_once DOL_DOCUMENT_ROOT.
'/product/class/html.formproduct.class.php';
5577 require_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
5580 $warehouse_array = $warehouse->list_array();
5581 if (count($warehouse_array) == 1) {
5582 $label =
$object->type ==
Facture::TYPE_CREDIT_NOTE ? $langs->trans(
"WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans(
"WarehouseForStockIncrease", current($warehouse_array));
5583 $value =
'<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).
'">';
5586 $value = $formproduct->selectWarehouses(
GETPOST(
'idwarehouse') ?
GETPOST(
'idwarehouse') :
'ifone',
'idwarehouse',
'', 1);
5588 $formquestion = array(
5594 array(
'type' =>
'other',
'name' =>
'idwarehouse',
'label' => $label,
'value' => $value));
5598 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.
$object->id, $langs->trans(
'UnvalidateBill'), $text,
'confirm_modif', $formquestion,
"yes", 1);
5603 if ($action ==
'canceled') {
5607 $statusreplacement = 0;
5609 if ($objectidnext) {
5610 $facturereplacement =
new Facture($db);
5611 $facturereplacement->fetch($objectidnext);
5612 $statusreplacement = $facturereplacement->status;
5614 if ($objectidnext && $statusreplacement == 0) {
5615 print
'<div class="error">'.$langs->trans(
"ErrorCantCancelIfReplacementInvoiceNotValidated").
'</div>';
5619 $close[1][
'code'] =
'badcustomer';
5620 $close[2][
'code'] =
'abandon';
5622 $close[1][
'label'] = $langs->trans(
"ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
5623 $close[2][
'label'] = $langs->trans(
"ConfirmClassifyAbandonReasonOtherDesc");
5625 $close[1][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonBadCustomer",
$object->ref), $close[1][
'label'], 1);
5626 $close[2][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyAbandonReasonOther"), $close[2][
'label'], 1);
5629 $arrayreasons[$close[1][
'code']] = $close[1][
'reason'];
5630 $arrayreasons[$close[2][
'code']] = $close[2][
'reason'];
5633 $formquestion = array(
'text' => $langs->trans(
"ConfirmCancelBillQuestion"), 0 => array(
'type' =>
'radio',
'name' =>
'close_code',
'label' => $langs->trans(
"Reason"),
'values' => $arrayreasons), 1 => array(
'type' =>
'text',
'name' =>
'close_note',
'label' => $langs->trans(
"Comment"),
'value' =>
'',
'morecss' =>
'minwidth300'));
5635 $formconfirm = $form->formconfirm($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, $langs->trans(
'CancelBill'), $langs->trans(
'ConfirmCancelBill',
$object->ref),
'confirm_canceled', $formquestion,
"yes", 1, 300);
5640 if ($action ==
'paid' && ($resteapayer <= 0 || (
getDolGlobalString(
'INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') && $resteapayer ==
$object->total_ttc))) {
5641 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.
$object->id, $langs->trans(
'ClassifyPaid'), $langs->trans(
'ConfirmClassifyPaidBill',
$object->ref),
'confirm_paid',
'',
"yes", 1);
5643 if ($action ==
'paid' && $resteapayer > 0 && (!
getDolGlobalString(
'INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID') || $resteapayer !=
$object->total_ttc)) {
5647 $close[$i][
'code'] = $object::CLOSECODE_DISCOUNTVAT;
5649 $close[$i][
'code'] = $object::CLOSECODE_BADDEBT;
5651 $close[$i][
'code'] = $object::CLOSECODE_BANKCHARGE;
5653 $close[$i][
'code'] = $object::CLOSECODE_WITHHOLDINGTAX;
5655 $close[$i][
'code'] = $object::CLOSECODE_OTHER;
5659 $close[$i][
'label'] = $langs->trans(
"HelpEscompte").
'<br><br>'.$langs->trans(
"ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
5661 $close[$i][
'label'] = $langs->trans(
"ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
5663 $close[$i][
'label'] = $langs->trans(
"ConfirmClassifyPaidPartiallyReasonBankChargeDesc");
5665 $close[$i][
'label'] = $langs->trans(
"ConfirmClassifyPaidPartiallyReasonWithholdingTaxDesc");
5667 $close[$i][
'label'] = $langs->trans(
"Other");
5671 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans(
"Currency".$conf->currency)), $close[$i][
'label'], 1);
5673 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans(
"Currency".$conf->currency)), $close[$i][
'label'], 1);
5675 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonBankCharge", $resteapayer, $langs->trans(
"Currency".$conf->currency)), $close[$i][
'label'], 1);
5677 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"ConfirmClassifyPaidPartiallyReasonWithholdingTax"), $close[$i][
'label'], 1);
5679 $close[$i][
'reason'] = $form->textwithpicto($langs->transnoentities(
"Other"), $close[$i][
'label'], 1);
5683 foreach ($close as $key => $val) {
5684 $arrayreasons[$close[$key][
'code']] =
'<span class="small">'.$close[$key][
'reason'].
'</span>';
5688 $formquestion = array(
5689 'text' => $langs->trans(
"ConfirmClassifyPaidPartiallyQuestion"),
5690 0 => array(
'type' =>
'radio',
'name' =>
'close_code',
'label' =>
'',
'values' => $arrayreasons),
5691 1 => array(
'type' =>
'text',
'name' =>
'close_note',
'moreattr' =>
'placeholder = "'.$langs->trans(
"Comment").
'"',
'value' =>
'',
'morecss' =>
'minwidth300'),
5692 2 => array(
'type' =>
'separator')
5695 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&resteapayer='.((
float) $resteapayer), $langs->trans(
'ClassifyPaid'), $langs->trans(
'ConfirmClassifyPaidPartially',
$object->ref),
'confirm_paid_partially', $formquestion,
"yes", 1, 420, 600);
5698 if ($action ==
'deletepayment') {
5699 $payment_id =
GETPOST(
'paiement_id');
5700 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?id='.
$object->id.
'&paiement_id='.$payment_id, $langs->trans(
'DeletePayment'), $langs->trans(
'ConfirmDeletePayment'),
'confirm_delete_paiement',
'',
'no', 1);
5704 if ($action ==
'ask_deleteline') {
5705 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&lineid='.$lineid, $langs->trans(
'DeleteProductLine'), $langs->trans(
'ConfirmDeleteProductLine'),
'confirm_deleteline',
'',
'no', 1);
5709 if ($action ==
'ask_updatelinkedbuyingprice') {
5710 $langs->loadLangs(array(
'orders',
'propal'));
5711 $labels = array(
'propal' =>
'Proposal',
'commande' =>
'Order',
'facture' =>
'Invoice');
5712 $formquestion = array(array(
'type' =>
'hidden',
'name' =>
'lineid',
'value' => $lineid));
5713 foreach (
$object->getLinkedBuyPriceDocuments($user, $lineid) as $element => $document) {
5714 $formquestion[] = array(
'type' =>
'checkbox',
'name' =>
'updatelinked_'.$element,
'label' => $langs->trans($labels[$element]).
' '.
dol_escape_htmltag(implode(
', ', $document[
'refs'])),
'value' => ($element !=
'facture'));
5716 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.
$object->id, $langs->trans(
'UpdateLinkedBuyingPrice'), $langs->trans(
'UpdateLinkedBuyingPriceQuestion'),
'confirm_updatelinkedbuyingprice', $formquestion,
'yes', 1);
5720 if ($action ==
'ask_subtotal_deleteline') {
5721 $langs->load(
"subtotals");
5722 $title =
"DeleteSubtotalLine";
5723 $question =
"ConfirmDeleteSubtotalLine";
5724 if (
GETPOST(
'type') ==
'title') {
5725 $formconfirm = array(array(
'type' =>
'checkbox',
'name' =>
'deletecorrespondingsubtotalline',
'label' => $langs->trans(
"DeleteCorrespondingSubtotalLine"),
'value' => 0));
5726 $title =
"DeleteTitleLine";
5727 $question =
"ConfirmDeleteTitleLine";
5729 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&lineid='.$lineid, $langs->trans($title), $langs->trans($question),
'confirm_delete_subtotalline', $formconfirm,
'no', 1);
5733 if ($action ==
'clone') {
5734 $filter =
'(s.client:IN:1,2,3)';
5736 $formquestion = array(
5737 array(
'type' =>
'other',
'name' =>
'socid',
'label' => $langs->trans(
"SelectThirdParty"),
'value' => $form->select_company(
$object->socid,
'socid', $filter, 1)),
5738 array(
'type' =>
'date',
'name' =>
'newdate',
'label' => $langs->trans(
"Date"),
'value' =>
dol_now())
5741 $formconfirm = $form->formconfirm($_SERVER[
"PHP_SELF"].
'?facid='.
$object->id, $langs->trans(
'ToClone'), $langs->trans(
'ConfirmCloneInvoice',
$object->ref),
'confirm_clone', $formquestion,
'yes', 1, 0);
5745 if ($action ==
'add_title_line') {
5746 $langs->load(
'subtotals');
5748 $depth_array =
$object->getPossibleLevels($langs);
5750 } elseif ($action ==
'add_subtotal_line') {
5751 $langs->load(
'subtotals');
5753 $titles =
$object->getPossibleTitles();
5755 } elseif ($action ==
'add_text_line') {
5756 $langs->load(
'subtotals');
5761 if ($action ==
"remove_file_comfirm") {
5762 $file =
GETPOST(
'file',
'alpha');
5764 $formconfirm = $form->formconfirm(
5765 $_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&file='.urlencode($file),
5766 $langs->trans(
'DeleteFileHeader'),
5767 $langs->trans(
'DeleteFileText').
"<br><br>".$file,
5776 $parameters = array(
'formConfirm' => $formconfirm,
'lineid' => $lineid,
'remainingtopay' => &$resteapayer);
5777 $reshook = $hookmanager->executeHooks(
'formConfirm', $parameters, $object, $action);
5778 if (empty($reshook)) {
5779 $formconfirm .= $hookmanager->resPrint;
5780 } elseif ($reshook > 0) {
5781 $formconfirm = $hookmanager->resPrint;
5789 $linkback =
'<a href="'.DOL_URL_ROOT.
'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ?
'&socid='.$socid :
'').
'">'.$langs->trans(
"BackToList").
'</a>';
5791 $morehtmlref =
'<div class="refidno">';
5794 $morehtmlref .= $form->editfieldkey(
"Ref",
'ref',
$object->ref, $object, (
int) $usercancreate,
'string',
'', 0, 1);
5795 $morehtmlref .= $form->editfieldval(
"Ref",
'ref',
$object->ref, $object, (
int) $usercancreate,
'string',
'',
null,
null,
'', 1);
5796 $morehtmlref .=
'<br>';
5799 $morehtmlref .= $form->editfieldkey(
"RefCustomer",
'ref_client',
$object->ref_customer, $object, (
int) $usercancreate,
'string',
'', 0, 1);
5800 $morehtmlref .= $form->editfieldval(
"RefCustomer",
'ref_client',
$object->ref_customer, $object, (
int) $usercancreate,
'string'.(getDolGlobalString(
'THIRDPARTY_REF_INPUT_SIZE') ?
':' .
getDolGlobalString(
'THIRDPARTY_REF_INPUT_SIZE') :
''),
'', null, null,
'', 1);
5802 $morehtmlref .=
'<br>'.$object->thirdparty->getNomUrl(1,
'customer');
5804 $morehtmlref .=
' (<a href="'.DOL_URL_ROOT.
'/compta/facture/list.php?socid='.
$object->thirdparty->id.
'">'.$langs->trans(
"OtherBills").
'</a>)';
5808 $langs->load(
"projects");
5809 $morehtmlref .=
'<br>';
5810 if ($usercancreate) {
5811 $morehtmlref .= img_picto($langs->trans(
"Project"),
'project',
'class="pictofixedwidth"');
5812 if ($action !=
'classify') {
5813 $morehtmlref .=
'<a class="editfielda" href="'.dolBuildUrl($_SERVER[
'PHP_SELF'], [
'action' =>
'classify',
'id' =>
$object->id],
true).
'">'.img_edit($langs->transnoentitiesnoconv(
'SetProject')).
'</a> ';
5815 $morehtmlref .= $form->form_project($_SERVER[
'PHP_SELF'].
'?id='.
$object->id,
$object->socid, (
string)
$object->fk_project, ($action ==
'classify' ?
'projectid' :
'none'), 0, 0, 0, 1,
'',
'maxwidth300');
5817 if (!empty(
$object->fk_project)) {
5819 $proj->fetch(
$object->fk_project);
5820 $morehtmlref .= $proj->getNomUrl(1);
5822 $morehtmlref .=
'<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).
'</span>';
5827 $morehtmlref .=
'</div>';
5829 $object->totalpaid = $totalpaid;
5830 $object->totalcreditnotes = $totalcreditnotes;
5831 $object->totaldeposits = $totaldeposits;
5834 dol_banner_tab($object,
'ref', $linkback, 1,
'ref',
'ref', $morehtmlref,
'', 0,
'',
'');
5837 $parameters = array();
5839 $reshook = $hookmanager->executeHooks(
'tabContentViewInvoice', $parameters, $object, $action);
5840 if (empty($reshook)) {
5841 print
'<div class="fichecenter">';
5842 print
'<div class="fichehalfleft">';
5843 print
'<div class="underbanner clearboth"></div>';
5845 print
'<table class="border centpercent tableforfield">';
5848 print
'<tr><td class="fieldname_type">'.$langs->trans(
'Type').
'</td><td class="valuefield fieldname_type">';
5851 print
' '.$object->getSubtypeLabel(
'facture');
5854 $facreplaced =
new Facture($db);
5855 $facreplaced->fetch(
$object->fk_facture_source);
5856 print
' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities(
"ReplaceInvoice", $facreplaced->getNomUrl(1,
'', 32)).
'</span>';
5860 $facusing->fetch(
$object->fk_facture_source);
5861 print
' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities(
"CorrectInvoice", $facusing->getNomUrl(1,
'', 32)).
'</span>';
5865 $object->getListIdAvoirFromInvoice();
5867 if (!empty(
$object->creditnote_ids)) {
5868 print
' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities(
"InvoiceHasAvoir");
5870 foreach (
$object->creditnote_ids as $invoiceid) {
5876 $creditnote =
new Facture($db);
5877 $creditnote->fetch($invoiceid);
5878 print $creditnote->getNomUrl(1,
'', 32);
5882 if ($objectidnext > 0) {
5883 $facthatreplace =
new Facture($db);
5884 $facthatreplace->fetch($objectidnext);
5885 print
' <span class="opacitymediumbycolor paddingleft">'.str_replace(
'{s1}', $facthatreplace->getNomUrl(1), $langs->transnoentities(
"ReplacedByInvoice",
'{s1}')).
'</span>';
5890 $result = $discount->fetch(0,
$object->id);
5892 print
' <span class="opacitymediumbycolor paddingleft">';
5893 $s = $langs->trans(
"CreditNoteConvertedIntoDiscount",
'{s1}',
'{s2}');
5894 $s = str_replace(
'{s1}',
$object->getLibType(0), $s);
5895 $s = str_replace(
'{s2}', $discount->getNomUrl(1,
'discount'), $s);
5897 print
'</span><br>';
5901 if (
$object->fk_fac_rec_source > 0) {
5903 $result = $tmptemplate->fetch(
$object->fk_fac_rec_source);
5905 print
' <span class="opacitymediumbycolor paddingleft">';
5906 $s = $langs->transnoentities(
"GeneratedFromTemplate",
'{s1}');
5907 $s = str_replace(
'{s1}', $tmptemplate->getNomUrl(1,
'', 32), $s);
5911 print
' <span class="opacitymediumbycolor paddingleft">';
5912 print $langs->transnoentities(
"GeneratedFromTemplate", $langs->trans(
"ObjectDeleted"));
5920 $langs->load(
"cashdesk");
5921 print
'<tr><td class="fieldname_type">';
5922 print
'<table class="nobordernopadding centpercent"><tr><td>';
5923 print $form->textwithpicto($langs->trans(
'PointOfSale'), $langs->trans(
'POSInfo'));
5925 if ($action !=
'editposinfo' && $usercancreate) {
5926 print
'<td class="right"><a class="editfielda" href="'.$_SERVER[
"PHP_SELF"].
'?action=editposinfo&token='.
newToken().
'&facid='.
$object->id.
'">'.img_edit($langs->trans(
'SetPOSInfo'), 1).
'</a></td>';
5928 print
'</tr></table>';
5929 print
'</td><td class="valuefield fieldname_type">';
5930 print
'<form method="POST" action="'.$_SERVER[
"PHP_SELF"].
'?id='.
$object->id.
'" name="formposinfo">';
5931 print
'<input type="hidden" name="action" value="setposinfo">';
5932 print
'<input type="hidden" name="token" value="' .
newToken() .
'">';
5933 if ($action ==
'editposinfo') {
5934 print
'<input type="text" class="maxwidth150" name="posmodule" placeholder="'.$langs->trans(
"POSModule").
'" value="'.
$object->module_source.
'"> ';
5935 print
'<input type="text" class="maxwidth100" name="posterminal" placeholder="'.$langs->trans(
"Terminal").
'" value="'.
$object->pos_source.
'">';
5936 print
'<input type="submit" class="button" name="submitposinfo" value="'.$langs->trans(
"Submit").
'">';
5939 print
'<span class="opacitymediumbycolor paddingleft">'.dolPrintHTML(ucfirst(
$object->module_source).
' - '.$langs->transnoentitiesnoconv(
"Terminal").
' '.
$object->pos_source).
'</span>';
5947 print
'<!-- Discounts -->'.
"\n";
5948 print
'<tr><td>'.$langs->trans(
'DiscountStillRemaining').
'</td>';
5952 $backtopage = $_SERVER[
"PHP_SELF"].
'?facid='.
$object->id;
5953 $defaulttpldir =
'/core/tpl';
5955 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5956 foreach ($dirtpls as
$module => $reldir) {
5961 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/object_discounts.tpl.php';
5963 if (file_exists($tpl)) {
5964 if (empty(
$conf->file->strict_mode)) {
5965 $res = @include $tpl;
5967 $res = include $tpl;
5979 print
'<table class="nobordernopadding centpercent"><tr><td>';
5980 print $langs->trans(
'DateInvoice');
5982 if ($action !=
'editinvoicedate' &&
$object->status == $object::STATUS_DRAFT && $usercancreate && !
getDolGlobalString(
'FAC_FORCE_DATE_VALIDATION')) {
5983 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>';
5985 print
'</tr></table>';
5987 if ($action ==
'editinvoicedate') {
5988 $form->form_date($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id,
$object->date,
'invoicedate');
5990 print
'<span class="valuedate">'.dol_print_date(
$object->date,
'day').
'</span>';
6005 print
'<table class="nobordernopadding centpercent"><tr><td>';
6006 print $langs->trans(
'DatePointOfTax');
6009 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>';
6011 print
'</tr></table>';
6013 if ($action ==
'editdate_pointoftax' && $editable) {
6014 $form->form_date($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id,
$object->date_pointoftax,
'date_pointoftax');
6016 print
'<span class="valuedate">'.dol_print_date(
$object->date_pointoftax,
'day').
'</span>';
6024 print $form->editfieldkey(
'Source',
'input_reason',
'', $object, (
int) $usercancreate);
6025 print
'</td><td class="valuefield">';
6026 if ($action ==
'editinput_reason') {
6027 $form->formInputReason($_SERVER[
'PHP_SELF'].
'?id='.
$object->id, (
string)
$object->demand_reason_id,
'input_reason_id', 1,
'maxwidth250 widthcentpercentminusx');
6029 $form->formInputReason($_SERVER[
'PHP_SELF'].
'?id='.
$object->id, (
string)
$object->demand_reason_id,
'none');
6036 print
'<table class="nobordernopadding centpercent"><tr><td>';
6037 print $langs->trans(
'PaymentConditionsShort');
6040 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>';
6042 print
'</tr></table>';
6045 if ($action ==
'editconditions') {
6046 $form->form_conditions_reglement($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, (
string)
$object->cond_reglement_id,
'cond_reglement_id');
6048 $form->form_conditions_reglement($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, (
string)
$object->cond_reglement_id,
'none');
6055 print
'<table class="nobordernopadding centpercent"><tr><td>';
6056 print $langs->trans(
'DateMaxPayment');
6059 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>';
6061 print
'</tr></table>';
6064 if ($action ==
'editpaymentterm') {
6065 $form->form_date($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id,
$object->date_lim_reglement,
'paymentterm');
6067 print
'<span class="valuedate">'.dol_print_date(
$object->date_lim_reglement,
'day').
'</span>';
6069 print img_warning($langs->trans(
'Late'));
6077 print
'<table class="nobordernopadding centpercent"><tr><td>';
6078 print $langs->trans(
'PaymentMode');
6080 if ($action !=
'editmode' && $usercancreate) {
6081 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>';
6083 print
'</tr></table>';
6085 if ($action ==
'editmode') {
6086 $form->form_modes_reglement($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, (
string)
$object->mode_reglement_id,
'mode_reglement_id',
'CRDT', 1, 1);
6088 $form->form_modes_reglement($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, (
string)
$object->mode_reglement_id,
'none',
'CRDT');
6095 print
'<tr><td>'.$langs->trans(
'PaymentReference').
'</td><td>';
6096 if (!empty(
$object->payment_reference)) {
6097 print
'<span class="opacitymedium paddingright">'.dol_escape_htmltag(
$object->payment_reference).
'</span>';
6100 include_once DOL_DOCUMENT_ROOT.
'/core/lib/paymentref.lib.php';
6104 if ($previewpayref !=
'') {
6105 print
'<span class="opacitymedium">'.dol_escape_htmltag($previewpayref).
' ('.$langs->trans(
"Preview").
')</span>';
6107 print
'<span class="opacitymedium">'.$langs->trans(
"PaymentRefGeneratedOnValidation").
'</span>';
6110 print
'<span class="opacitymedium">'.$langs->trans(
"None").
'</span>';
6113 print
' <a class="paddingleft" href="'.$_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&action=regeneratepaymentref&token='.
newToken().
'">';
6114 print $langs->trans(
"GeneratePaymentReference");
6123 print
'<tr><td class="nowrap">';
6124 print
'<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
6125 print $langs->trans(
'DefaultBankAccount');
6127 if (($action !=
'editbankaccount') && $usercancreate) {
6128 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>';
6130 print
'</tr></table>';
6132 if ($action ==
'editbankaccount') {
6133 $form->formSelectAccount($_SERVER[
'PHP_SELF'].
'?id='.
$object->id, (
string)
$object->fk_account,
'fk_account', 1);
6135 $form->formSelectAccount($_SERVER[
'PHP_SELF'].
'?id='.
$object->id, (
string)
$object->fk_account,
'none');
6144 print
'<table class="nobordernopadding centpercent"><tr><td>';
6145 print $langs->trans(
'IncotermLabel');
6146 print
'<td><td class="right">';
6147 if ($usercancreate) {
6148 print
'<a class="editfielda" href="'.DOL_URL_ROOT.
'/compta/facture/card.php?facid='.
$object->id.
'&action=editincoterm&token='.
newToken().
'">'.img_edit().
'</a>';
6150 print
'</td></tr></table>';
6153 if ($action !=
'editincoterm') {
6154 print $form->textwithpicto(
$object->display_incoterms(),
$object->label_incoterms, 1);
6156 print $form->select_incoterms((!empty(
$object->fk_incoterms) ?
$object->fk_incoterms :
''), (!empty(
$object->location_incoterms) ?
$object->location_incoterms :
''), $_SERVER[
'PHP_SELF'].
'?id='.
$object->id);
6163 print
'<table class="nobordernopadding centpercent"><tr><td>';
6164 print $langs->trans(
'Dispute');
6165 print
'<td><td class="right">';
6166 if ($usercancreate) {
6167 print
'<a class="editfielda" href="'.DOL_URL_ROOT.
'/compta/facture/card.php?facid='.
$object->id.
'&action=editdispute_status&token='.
newToken().
'">'.img_edit().
'</a>';
6169 print
'</td></tr></table>';
6171 $liststatus = Facture::ARRAY_OF_DISPUTE_STATUS;
6172 if ($action !=
'editdispute_status') {
6173 if (
$object->dispute_status) {
6174 print $langs->trans($liststatus[
$object->dispute_status][
'label']);
6177 print
'<form enctype="multipart/form-data" action="'.DOL_URL_ROOT.
'/compta/facture/card.php" method="POST">';
6178 print
'<input type="hidden" name="action" value="set_dispute_status">';
6179 print
'<input type="hidden" name="token" value="'.newToken().
'">';
6180 print
'<input type="hidden" name="id" value="'.$object->id.
'">';
6181 print
'<input type="hidden" name="page_y" value="">';
6182 print $form->selectarray(
'dispute_status', $liststatus,
$object->dispute_status, 0, 0, 0,
'', 1);
6183 print
'<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans(
"Save").
'">';
6191 print
'<table class="nobordernopadding centpercent"><tr><td>';
6192 print $langs->trans(
"Categories");
6193 print
'<td><td class="right">';
6194 if ($usercancreate) {
6195 print
'<a class="editfielda" href="'.DOL_URL_ROOT.
'/compta/facture/card.php?facid='.
$object->id.
'&action=edittags&token='.
newToken().
'">'.img_edit().
'</a>';
6199 print
'</td></tr></table>';
6202 if ($action ==
'edittags') {
6203 print
'<form method="POST" action="'.$_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'">';
6204 print
'<input type="hidden" name="action" value="settags">';
6205 print
'<input type="hidden" name="token" value="'.newToken().
'">';
6206 print $form->selectCategories(Categorie::TYPE_INVOICE,
'categories', $object);
6207 print
'<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans(
"Modify").
'">';
6210 print $form->showCategories(
$object->id, Categorie::TYPE_INVOICE, 1);
6215 $displayWarranty =
false;
6218 $displayWarranty =
true;
6219 if (!in_array(
$object->type, $retainedWarrantyInvoiceAvailableType) && empty(
$object->retained_warranty)) {
6220 $displayWarranty =
false;
6223 if ($displayWarranty) {
6225 print
'<tr class="retained-warranty-lines" ><td>';
6226 print
'<table id="retained-warranty-table" class="nobordernopadding centpercent"><tr><td>';
6227 print $langs->trans(
'RetainedWarranty');
6230 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>';
6233 print
'</tr></table>';
6236 print
'<form id="retained-warranty-form" method="POST" action="'.$_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'">';
6237 print
'<input type="hidden" name="action" value="setretainedwarranty">';
6238 print
'<input type="hidden" name="token" value="'.newToken().
'">';
6239 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
6240 print
'<input name="retained_warranty" type="number" step="0.01" min="0" max="100" value="'.$object->retained_warranty.
'" >';
6241 print
'<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans(
"Modify").
'">';
6249 print
'<tr class="retained-warranty-lines" ><td>';
6250 print
'<table id="retained-warranty-cond-reglement-table" class="nobordernopadding" width="100%"><tr><td>';
6251 print $langs->trans(
'PaymentConditionsShortRetainedWarranty');
6253 if ($action !=
'editretainedwarrantypaymentterms' && $user->hasRight(
'facture',
'creer') &&
$object->status ==
Facture::STATUS_DRAFT) {
6254 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>';
6257 print
'</tr></table>';
6259 $defaultDate = !empty(
$object->retained_warranty_date_limit) ?
$object->retained_warranty_date_limit : strtotime(
'-1 years',
$object->date_lim_reglement);
6260 if (
$object->date > $defaultDate) {
6266 print
'<form method="POST" action="'.$_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'">';
6267 print
'<input type="hidden" name="action" value="setretainedwarrantyconditions">';
6268 print
'<input type="hidden" name="token" value="'.newToken().
'">';
6269 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
6270 $retained_warranty_fk_cond_reglement =
GETPOSTINT(
'retained_warranty_fk_cond_reglement');
6271 $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement :
$object->retained_warranty_fk_cond_reglement;
6272 $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement :
getDolGlobalString(
'INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID');
6273 print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement,
'retained_warranty_fk_cond_reglement', -1, 1);
6274 print
'<input type="submit" class="button valignmiddle" value="'.$langs->trans(
"Modify").
'">';
6277 $form->form_conditions_reglement($_SERVER[
'PHP_SELF'].
'?facid='.
$object->id, (
string)
$object->retained_warranty_fk_cond_reglement,
'none');
6278 if (!$displayWarranty) {
6279 print img_picto($langs->trans(
'RetainedWarrantyNeed100Percent'),
'warning',
'class="pictowarning valignmiddle" ');
6285 print
'<tr class="retained-warranty-lines" ><td>';
6286 print
'<table id="retained-warranty-date-limit-table" class="nobordernopadding" width="100%"><tr><td>';
6287 print $langs->trans(
'RetainedWarrantyDateLimit');
6290 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>';
6293 print
'</tr></table>';
6295 $defaultDate = !empty(
$object->retained_warranty_date_limit) ?
$object->retained_warranty_date_limit : strtotime(
'-1 years',
$object->date_lim_reglement);
6296 if (
$object->date > $defaultDate) {
6301 print
'<form method="POST" action="'.$_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'">';
6302 print
'<input type="hidden" name="action" value="setretainedwarrantydatelimit">';
6303 print
'<input type="hidden" name="token" value="'.newToken().
'">';
6304 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
6306 print $form->selectDate($defaultDate,
'retained_warranty_date_limit');
6307 print
'<input type="submit" class="button valignmiddle" value="'.$langs->trans(
"Modify").
'">';
6319 include DOL_DOCUMENT_ROOT.
'/core/tpl/extrafields_view.tpl.php';
6324 print
'<div class="fichehalfright">';
6326 print
'<!-- amounts -->'.
"\n";
6327 print
'<div class="underbanner clearboth"></div>'.
"\n";
6329 print
'<table class="border tableforfield centpercent">';
6331 include DOL_DOCUMENT_ROOT.
'/core/tpl/object_currency_amount.tpl.php';
6339 print
'<td class="titlefieldmiddle">' . $langs->trans(
'AmountHT') .
'</td>';
6340 print
'<td class="nowraponall amountcard right" data-dol-field="total_ht">' .
price($sign *
$object->total_ht, 0, $langs, 0, -1, -1,
$conf->currency) .
'</td>';
6343 print
'<td class="nowraponall amountcard right" data-dol-field="multicurrency_total_ht">' .
price($sign *
$object->multicurrency_total_ht, 0, $langs, 0, -1, -1,
$object->multicurrency_code) .
'</td>';
6349 print
'<td>' . $langs->trans(
'AmountVAT') .
'</td>';
6350 print
'<td class="nowraponall amountcard right" data-dol-field="total_tva">' .
price($sign *
$object->total_tva, 0, $langs, 0, -1, -1,
$conf->currency) .
'</td>';
6353 print
'<td class="nowraponall amountcard right" data-dol-field="multicurrency_total_tva">' .
price($sign *
$object->multicurrency_total_tva, 0, $langs, 0, -1, -1,
$object->multicurrency_code) .
'</td>';
6358 if ((
$mysoc->localtax1_assuj ==
"1" &&
$mysoc->useLocalTax(1)) ||
$object->total_localtax1 != 0) {
6360 print
'<td class="titlefieldmiddle">' . $langs->transcountry(
"AmountLT1",
$mysoc->country_code) .
'</td>';
6361 print
'<td class="nowraponall amountcard right" data-dol-field="total_localtax1">' .
price($sign *
$object->total_localtax1, 0, $langs, 0, -1, -1,
$conf->currency) .
'</td>';
6365 print
'<td class="nowraponall amountcard right" data-dol-field="multicurrency_total_localtax1">' .
price($sign *
$object->multicurrency_total_localtax1, 0, $langs, 0, -1, -1,
$object->multicurrency_code) .
'</td>';
6370 if ((
$mysoc->localtax2_assuj ==
"1" &&
$mysoc->useLocalTax(2)) ||
$object->total_localtax2 != 0) {
6372 print
'<td>' . $langs->transcountry(
"AmountLT2",
$mysoc->country_code) .
'</td>';
6373 print
'<td class="nowraponall amountcard right" data-dol-field="total_localtax2">' .
price($sign *
$object->total_localtax2, 0, $langs, 0, -1, -1,
$conf->currency) .
'</td>';
6377 print
'<td class="nowraponall amountcard right" data-dol-field="multicurrency_total_localtax2">' .
price($sign *
$object->multicurrency_total_localtax2, 0, $langs, 0, -1, -1,
$object->multicurrency_code) .
'</td>';
6383 if ($selleruserevenustamp) {
6384 print
'<tr><td class="titlefieldmiddle">';
6385 print
'<table class="nobordernopadding centpercent"><tr><td>';
6386 print $langs->trans(
'RevenueStamp');
6388 if ($action !=
'editrevenuestamp' &&
$object->status == $object::STATUS_DRAFT && $usercancreate) {
6389 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>';
6391 print
'</tr></table>';
6392 print
'</td><td class="nowrap amountcard right" data-dol-field="revenuestamp">';
6393 if ($action ==
'editrevenuestamp') {
6394 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?id='.
$object->id.
'" method="post">';
6395 print
'<input type="hidden" name="token" value="'.newToken().
'">';
6396 print
'<input type="hidden" name="action" value="setrevenuestamp">';
6397 print
'<input type="hidden" name="revenuestamp" id="revenuestamp_val" value="'.price2num(
$object->revenuestamp).
'">';
6398 print
'<input type="hidden" name="backtopage" value="'.$backtopage.
'">';
6399 print $formother->select_revenue_stamp(
'',
'revenuestamp_type',
$mysoc->country_code);
6400 print
' → <span id="revenuestamp_span"></span>';
6401 print
' <input type="submit" class="button buttongen button-save small" value="'.$langs->trans(
'Modify').
'">';
6404 $(document).ready(function(){
6405 js_recalculate_revenuestamp();
6406 $('select[name=revenuestamp_type]').on('change',function(){
6407 js_recalculate_revenuestamp();
6410 function js_recalculate_revenuestamp(){
6411 var valselected = $('select[name=revenuestamp_type]').val();
6412 console.log('Calculate revenue stamp from '+valselected);
6414 if (valselected.indexOf('%') == -1)
6416 revenue = valselected;
6420 var revenue_type = parseFloat(valselected);
6421 var amount_net = ".round(
$object->total_ht, 2).
";
6422 revenue = revenue_type * amount_net / 100;
6423 revenue = revenue.toFixed(2);
6425 $('#revenuestamp_val').val(revenue);
6426 $('#revenuestamp_span').html(revenue);
6437 print
'<td>' . $langs->trans(
'AmountTTC') .
'</td>';
6438 print
'<td class="nowraponall amountcard right" data-dol-field="total_ttc">' .
price($sign *
$object->total_ttc, 0, $langs, 0, -1, -1,
$conf->currency) .
'</td>';
6441 print
'<td class="nowrap amountcard right" data-dol-field="multicurrency_total_ttc">' .
price($sign *
$object->multicurrency_total_ttc, 0, $langs, 0, -1, -1,
$object->multicurrency_code) .
'</td>';
6456 if (
$mysoc->localtax1_assuj ==
"1" ||
$object->total_localtax1 != 0) {
6459 if (
$mysoc->localtax2_assuj ==
"1" ||
$object->total_localtax2 != 0) {
6462 if ($selleruserevenustamp) {
6472 $total_prev_ht = $total_prev_ttc = 0;
6473 $total_global_ht = $total_global_ttc = 0;
6477 print
'<!-- List of situation invoices -->';
6478 print
'<div class="div-table-responsive-no-min">';
6479 print
'<table class="noborder paymenttable centpercent situationstable">';
6481 print
'<tr class="liste_titre">';
6482 print
'<td>'.$langs->trans(
'ListOfSituationInvoices').
'</td>';
6484 print
'<td class="center">'.$langs->trans(
'Situation').
'</td>';
6487 print
'<td class="right"></td>';
6489 print
'<td class="right">'.$langs->trans(
'AmountHT').
'</td>';
6490 print
'<td class="right">'.$langs->trans(
'AmountTTC').
'</td>';
6491 print
'<td width="18"> </td>';
6494 if (count(
$object->tab_previous_situation_invoice) > 0) {
6497 $current_situation_counter = array();
6498 foreach (
$object->tab_previous_situation_invoice as $prev_invoice) {
6499 $tmptotalallpayments = $prev_invoice->getSommePaiement(0);
6500 $tmptotalallpayments += $prev_invoice->getSumDepositsUsed(0);
6501 $tmptotalallpayments += $prev_invoice->getSumCreditNotesUsed(0);
6503 $total_prev_ht += $prev_invoice->total_ht;
6504 $total_prev_ttc += $prev_invoice->total_ttc;
6506 $current_situation_counter[] = (($prev_invoice->type ==
Facture::TYPE_CREDIT_NOTE) ? -1 : 1) * $prev_invoice->situation_counter;
6507 print
'<tr class="oddeven">';
6508 print
'<td>'.$prev_invoice->getNomUrl(1).
'</td>';
6510 print
'<td align="center" >'.(($prev_invoice->type ==
Facture::TYPE_CREDIT_NOTE) ? $langs->trans(
'situationInvoiceShortcode_AS') : $langs->trans(
'situationInvoiceShortcode_S')).$prev_invoice->situation_counter.
'</td>';
6512 print
'<td class="right"></td>';
6514 print
'<td class="right"><span class="amount">'.price($prev_invoice->total_ht).
'</span></td>';
6515 print
'<td class="right"><span class="amount">'.price($prev_invoice->total_ttc).
'</span></td>';
6516 print
'<td class="right">'.$prev_invoice->getLibStatut(3, $tmptotalallpayments).
'</td>';
6521 $totalallpayments =
$object->getSommePaiement(0);
6522 $totalallpayments +=
$object->getSumCreditNotesUsed(0);
6523 $totalallpayments +=
$object->getSumDepositsUsed(0);
6525 $total_global_ht += $total_prev_ht;
6526 $total_global_ttc += $total_prev_ttc;
6527 $total_global_ht +=
$object->total_ht;
6528 $total_global_ttc +=
$object->total_ttc;
6532 print
'<tr class="oddeven">';
6533 print
'<td>'.$object->getNomUrl(1).
'</td>';
6535 print
'<td class="center">'.(($object->type ==
Facture::TYPE_CREDIT_NOTE) ? $langs->trans(
'situationInvoiceShortcode_AS') : $langs->trans(
'situationInvoiceShortcode_S')).
$object->situation_counter.
'</td>';
6537 print
'<td class="right"></td>';
6539 print
'<td class="right"><span class="amount">'.price(
$object->total_ht).
'</span></td>';
6540 print
'<td class="right"><span class="amount">'.price(
$object->total_ttc).
'</span></td>';
6541 print
'<td class="right">'.$object->getLibStatut(3, $totalallpayments).
'</td>';
6545 print
'<tr class="oddeven">';
6546 print
'<td colspan="2" class="left"><b>'.$langs->trans(
'SituationTotalAfterInvoice').
'</b></td>';
6549 foreach ($current_situation_counter as $sit) {
6550 $curSign = $sit > 0 ?
'+' :
'-';
6551 $curType = $sit > 0 ? $langs->trans(
'situationInvoiceShortcode_S') : $langs->trans(
'situationInvoiceShortcode_AS');
6553 print
' '.$curSign.
' ';
6555 print $curType.abs($sit);
6562 print
'<td class="right"><b>'.price($total_global_ht).
'</b></td>';
6563 print
'<td class="right"><b>'.price($total_global_ttc).
'</b></td>';
6564 print
'<td width="18"> </td>';
6568 if (count(
$object->tab_next_situation_invoice) > 0) {
6570 $total_next_ht = $total_next_ttc = 0;
6572 foreach (
$object->tab_next_situation_invoice as $next_invoice) {
6573 $next_totalpaid = $next_invoice->getSommePaiement(0);
6574 $next_totalcreditnotes = $next_invoice->getSumCreditNotesUsed(0);
6575 $next_totaldeposits = $next_invoice->getSumDepositsUsed(0);
6576 $total_next_ht += $next_invoice->total_ht;
6577 $total_next_ttc += $next_invoice->total_ttc;
6579 print
'<tr class="oddeven">';
6580 print
'<td>'.$next_invoice->getNomUrl(1).
'</td>';
6582 print
'<td class="center">'.(($next_invoice->type ==
Facture::TYPE_CREDIT_NOTE) ? $langs->trans(
'situationInvoiceShortcode_AS') : $langs->trans(
'situationInvoiceShortcode_S')).$next_invoice->situation_counter.
'</td>';
6584 print
'<td class="right"></td>';
6586 print
'<td class="right"><span class="amount">'.price($next_invoice->total_ht).
'</span></td>';
6587 print
'<td class="right"><span class="amount">'.price($next_invoice->total_ttc).
'</span></td>';
6588 print
'<td class="right">'.$next_invoice->getLibStatut(3, $next_totalpaid + $next_totalcreditnotes + $next_totaldeposits).
'</td>';
6592 $total_global_ht += $total_next_ht;
6593 $total_global_ttc += $total_next_ttc;
6595 print
'<tr class="oddeven">';
6596 print
'<td colspan="3" class="right"></td>';
6598 print
'<td class="right"></td>';
6600 print
'<td class="right"><b>'.price($total_global_ht).
'</b></td>';
6601 print
'<td class="right"><b>'.price($total_global_ttc).
'</b></td>';
6602 print
'<td width="18"> </td>';
6611 if (
$object->type == $object::TYPE_CREDIT_NOTE) {
6617 print
'<!-- List of payments already done -->';
6618 print
'<div class="div-table-responsive-no-min">';
6619 print
'<table class="noborder paymenttable centpercent" id="paymenttable">';
6621 print
'<tr class="liste_titre">';
6622 print
'<td class="liste_titre">'.($object->type ==
Facture::TYPE_CREDIT_NOTE ? $langs->trans(
"PaymentsBack") : $langs->trans(
'Payments')).
'</td>';
6623 print
'<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans(
'Date').
'</span></td>';
6624 print
'<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans(
'Type').
'</span></td>';
6626 print
'<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans(
'BankAccount').
'</span></td>';
6628 print
'<td class="liste_titre"></td>';
6629 print
'<td class="liste_titre right">'.$langs->trans(
'Amount').
'</td>';
6633 $sql =
'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
6634 $sql .=
' c.code as payment_code, c.libelle as payment_label,';
6635 $sql .=
' pf.amount,';
6636 $sql .=
' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal, ba.currency_code as bacurrency_code';
6637 $sql .=
' FROM '.MAIN_DB_PREFIX.
'paiement_facture as pf, '.MAIN_DB_PREFIX.
'paiement as p';
6638 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'c_paiement as c ON p.fk_paiement = c.id';
6639 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'bank as b ON p.fk_bank = b.rowid';
6640 $sql .=
' LEFT JOIN '.MAIN_DB_PREFIX.
'bank_account as ba ON b.fk_account = ba.rowid';
6641 $sql .=
' WHERE pf.fk_facture = '.((int)
$object->id).
' AND pf.fk_paiement = p.rowid';
6642 $sql .=
' AND p.entity IN ('.getEntity(
'invoice').
')';
6643 $sql .=
' ORDER BY p.datep, p.tms';
6645 $result = $db->query($sql);
6647 $num = $db->num_rows($result);
6652 $objp = $db->fetch_object($result);
6654 $paymentstatic->id = $objp->rowid;
6655 $paymentstatic->datepaye = $db->jdate($objp->dp);
6656 $paymentstatic->ref = $objp->ref;
6657 $paymentstatic->num_payment = $objp->num_payment;
6658 $paymentstatic->paiementcode = $objp->payment_code;
6660 print
'<tr class="oddeven">';
6661 print
'<td class="nowraponall">';
6662 print $paymentstatic->getNomUrl(1);
6665 $dateofpayment = $db->jdate($objp->dp);
6667 if ($tmparray[
'seconds'] == 0 && $tmparray[
'minutes'] == 0 && ($tmparray[
'hours'] == 0 || $tmparray[
'hours'] == 12)) {
6674 $label = ($langs->trans(
"PaymentType".$objp->payment_code) !=
"PaymentType".$objp->payment_code) ? $langs->trans(
"PaymentType".$objp->payment_code) : $objp->payment_label;
6675 print
'<td class="tdoverflowmax80" title="'.dol_escape_htmltag($label.
' '.$objp->num_payment).
'">'.
dol_escape_htmltag($label.
' '.$objp->num_payment).
'</td>';
6677 $bankaccountstatic->id = $objp->baid;
6678 $bankaccountstatic->ref = $objp->baref;
6679 $bankaccountstatic->label = $objp->baref;
6680 $bankaccountstatic->number = $objp->banumber;
6681 $bankaccountstatic->currency_code = $objp->bacurrency_code;
6684 $bankaccountstatic->account_number = $objp->account_number;
6687 $accountingjournal->fetch($objp->fk_accountancy_journal);
6688 $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1,
'', 1);
6691 print
'<td class="nowraponall">';
6692 if ($bankaccountstatic->id) {
6693 print $bankaccountstatic->getNomUrl(1,
'transactions');
6699 print
'<td class="center">';
6701 $paiement->fetch($objp->rowid);
6703 print
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.
$object->id.
'&action=deletepayment&token='.
newToken().
'&paiement_id='.$objp->rowid.
'">';
6710 print
'<td class="right"><span class="amount">'.price($sign * $objp->amount).
'</span></td>';
6719 dol_print_error($db);
6725 print
'<td colspan="'.($nbcols + 1).
'" class="right">';
6726 print
'<span class="opacitymedium">';
6728 print $langs->trans(
'AlreadyPaidNoCreditNotesNoDeposits');
6730 print $langs->trans(
'AlreadyPaid');
6732 print
'</span></td>';
6734 print
'<td class="right'.(($totalpaid > 0) ?
' amountalreadypaid' :
'').
'">'.
price($totalpaid).
'</td>';
6737 $resteapayeraffiche = $resteapayer;
6738 $cssforamountpaymentcomplete =
'amountpaymentcomplete';
6739 $cssforamountpaymentcompletenoresize =
'amountpaymentcompletenoresize';
6742 $creditnoteamount = 0;
6744 $sql =
"SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
6745 $sql .=
" re.description, re.fk_facture_source";
6746 $sql .=
" FROM ".MAIN_DB_PREFIX.
"societe_remise_except as re";
6747 $sql .=
" WHERE fk_facture = ".((int)
$object->id);
6748 $resql = $db->query($sql);
6750 $num = $db->num_rows($resql);
6754 $obj = $db->fetch_object($resql);
6755 $invoice->fetch($obj->fk_facture_source);
6757 print
'<td colspan="'.$nbcols.
'" class="right">';
6758 print
'<span class="opacitymedium">';
6760 print $langs->trans(
"CreditNote").
' ';
6763 print $langs->trans(
"Deposit").
' ';
6765 print $invoice->getNomUrl(0);
6769 print
'<td class="right">';
6770 print
'<a href="'.$_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&action=unlinkdiscount&token='.
newToken().
'&discountid='.$obj->rowid.
'">';
6771 print img_picto($langs->transnoentitiesnoconv(
"RemoveDiscount"),
'unlink');
6775 print
'<td class="right"><span class="amount">'.price($obj->amount_ttc).
'</span></td>';
6779 $creditnoteamount += $obj->amount_ttc;
6782 $depositamount += $obj->amount_ttc;
6786 dol_print_error($db);
6792 print
'<td colspan="'.$nbcols.
'" class="nowrap right">';
6793 print
'<span class="opacitymedium">';
6794 print $form->textwithpicto($langs->trans(
"Discount"), $langs->trans(
"HelpEscompte"), - 1);
6798 print
'<td class="right"><span class="amount">'.price(
price2num(
$object->total_ttc - $creditnoteamount - $depositamount - $totalpaid,
'MT')).
'</span></td>';
6800 $resteapayeraffiche = 0;
6801 $cssforamountpaymentcomplete =
'amountpaymentneutral';
6802 $cssforamountpaymentcompletenoresize =
'amountpaymentneutralnoresize';
6807 print
'<td colspan="'.($nbcols + 1).
'" class="nowrap right">';
6808 print
'<span class="opacitymedium">';
6809 print $form->textwithpicto($langs->trans(
"Abandoned"), $langs->trans(
"HelpAbandonBadCustomer"), - 1);
6813 print
'<td class="right">'.price(
price2num(
$object->total_ttc - $creditnoteamount - $depositamount - $totalpaid,
'MT')).
'</td>';
6816 $cssforamountpaymentcomplete =
'amountpaymentneutral';
6817 $cssforamountpaymentcompletenoresize =
'amountpaymentneutralnoresize';
6822 print
'<td colspan="'.($nbcols + 1).
'" class="nowrap right">';
6823 print
'<span class="opacitymedium">';
6824 print $form->textwithpicto($langs->trans(
"ProductReturned"), $langs->trans(
"HelpAbandonProductReturned"), - 1);
6828 print
'<td class="right"><span class="amount">'.price(
price2num(
$object->total_ttc - $creditnoteamount - $depositamount - $totalpaid,
'MT')).
'</span></td>';
6830 $resteapayeraffiche = 0;
6831 $cssforamountpaymentcomplete =
'amountpaymentneutral';
6832 $cssforamountpaymentcompletenoresize =
'amountpaymentneutralnoresize';
6837 print
'<td colspan="'.($nbcols + 1).
'" class="nowrap right">';
6838 $text = $langs->trans(
"HelpAbandonOther");
6840 $text .=
'<br><br><b>'.$langs->trans(
"Reason").
'</b>:'.
$object->close_note;
6842 print
'<span class="opacitymedium">';
6844 print $form->textwithpicto($langs->trans(
"Abandoned"), $text, - 1);
6848 print
'<td class="right"><span class="amount">'.price(
price2num(
$object->total_ttc - $creditnoteamount - $depositamount - $totalpaid,
'MT')).
'</span></td>';
6850 $resteapayeraffiche = 0;
6851 $cssforamountpaymentcomplete =
'amountpaymentneutral';
6852 $cssforamountpaymentcompletenoresize =
'amountpaymentneutralnoresize';
6857 print
'<td colspan="'.($nbcols + 1).
'" class="right">';
6858 print
'<span class="opacitymedium">';
6859 print $langs->trans(
"Billed");
6862 print
'<td class="right">'.price(
$object->total_ttc).
'</td>';
6867 print
'<td colspan="'.($nbcols + 1).
'" class="right">';
6868 print
'<span class="opacitymedium">';
6869 print $langs->trans(
'RemainderToPay');
6870 if ($resteapayeraffiche < 0) {
6871 print
' ('.$langs->trans(
'NegativeIfExcessReceived').
')';
6876 print
'<td class="right'.($resteapayeraffiche ?
' amountremaintopay' : (
' '.$cssforamountpaymentcomplete)).
'">'.
price($resteapayeraffiche).
'</td>';
6882 print
'<td colspan="'.($nbcols + 1).
'" class="right">';
6883 print
'<span class="opacitymedium">';
6884 print $langs->trans(
'RemainderToPayMulticurrency');
6885 if ($resteapayeraffiche < 0) {
6886 print
' ('.$langs->trans(
'NegativeIfExcessReceived').
')';
6891 print
'<td class="right'.($resteapayeraffiche ?
' amountremaintopaynoresize' : (
' '.$cssforamountpaymentcompletenoresize)).
'">';
6898 if (!empty(
$object->situation_final) && !empty(
$object->retained_warranty) && $displayWarranty) {
6900 if (
$object->isSituationInvoice()) {
6901 $retainedWarranty = $total_global_ttc *
$object->retained_warranty / 100;
6904 $retainedWarranty =
$object->total_ttc *
$object->retained_warranty / 100;
6907 $billedWithRetainedWarranty =
$object->total_ttc - $retainedWarranty;
6910 print
'<td colspan="'.($nbcols + 1).
'" class="right">'.$langs->trans(
"ToPayOn",
dol_print_date(
$object->date_lim_reglement,
'day')).
' :</td>';
6912 print
'<td class="right">'.price($billedWithRetainedWarranty).
'</td>';
6917 print
'<td colspan="'.($nbcols + 1).
'" class="right">';
6918 print $langs->trans(
"RetainedWarranty").
' ('.
$object->retained_warranty.
'%)';
6919 print !empty(
$object->retained_warranty_date_limit) ?
' '.$langs->trans(
"ToPayOn",
dol_print_date(
$object->retained_warranty_date_limit,
'day')) :
'';
6922 print
'<td class="right">'.price($retainedWarranty).
'</td>';
6926 $resteapayeraffiche = $resteapayer;
6927 $cssforamountpaymentcomplete =
'amountpaymentneutral';
6928 $cssforamountpaymentcompletenoresize =
'amountpaymentneutralnoresize';
6932 print
'<td colspan="'.($nbcols + 1).
'" class="right">';
6933 print
'<span class="opacitymedium">'.$langs->trans(
'AlreadyPaidBack').
'</span>';
6936 print
'<td class="right"><span class="amount">'.price($sign * $totalpaid).
'</span></td>';
6941 print
'<td colspan="'.($nbcols + 1).
'" class="right"><span class="opacitymedium">'.$langs->trans(
"Billed").
'</span></td>';
6943 print
'<td class="right">'.price($sign *
$object->total_ttc).
'</td>';
6947 print
'<tr><td colspan="'.($nbcols + 1).
'" class="right">';
6948 print
'<span class="opacitymedium">'.$langs->trans(
'RemainderToPayBack');
6949 if ($resteapayeraffiche > 0) {
6950 print
' ('.$langs->trans(
'NegativeIfExcessRefunded').
')';
6952 print
'</span></td>';
6954 print
'<td class="right'.($resteapayeraffiche ?
' amountremaintopayback' : (
' '.$cssforamountpaymentcomplete)).
'">'.
price($sign * $resteapayeraffiche);
6963 print
'<td colspan="'.($nbcols + 1).
'" class="right">';
6964 print
'<span class="opacitymedium">'.$langs->trans(
'RemainderToPayBackMulticurrency');
6965 if ($resteapayeraffiche > 0) {
6966 print
' ('.$langs->trans(
'NegativeIfExcessRefunded').
')';
6971 print
'<td class="right'.($resteapayeraffiche ?
' amountremaintopaybacknoresize' : (
' '.$cssforamountpaymentcompletenoresize)).
'">'.
price(
price2num($sign *
$object->multicurrency_tx * $resteapayeraffiche,
'MT'), 1, $langs, 1, -1, -1, (empty(
$object->multicurrency_code) ?
$conf->currency :
$object->multicurrency_code)).
'</td>';
6986 $formmargin->displayMarginInfos($object);
6992 print
'<div class="clearboth"></div><br>';
6995 $blocname =
'contacts';
6996 $title = $langs->trans(
'ContactsAddresses');
6997 include DOL_DOCUMENT_ROOT.
'/core/tpl/bloc_showhide.tpl.php';
7001 $blocname =
'notes';
7002 $title = $langs->trans(
'Notes');
7003 include DOL_DOCUMENT_ROOT.
'/core/tpl/bloc_showhide.tpl.php';
7007 $result =
$object->getLinesArray();
7011 global $inputalsopricewithtax;
7012 $inputalsopricewithtax = 1;
7014 print
' <form name="addproduct" id="addproduct" action="'.$_SERVER[
"PHP_SELF"].
'?id='.
$object->id.
'" method="POST">
7015 <input type="hidden" name="token" value="' .
newToken().
'">
7016 <input type="hidden" name="action" value="' . (($action !=
'editline') ?
'addline' :
'updateline').
'">
7017 <input type="hidden" name="mode" value="">
7018 <input type="hidden" name="page_y" value="">
7019 <input type="hidden" name="id" value="' .
$object->id.
'">
7020 <input type="hidden" name="backtopage" value="'.$backtopage.
'">
7023 if (!empty(
$conf->use_javascript_ajax) &&
$object->status == 0) {
7025 include DOL_DOCUMENT_ROOT.
'/core/tpl/subtotal_ajaxrow.tpl.php';
7027 include DOL_DOCUMENT_ROOT .
'/core/tpl/ajaxrow.tpl.php';
7031 print
'<div class="div-table-responsive-no-min">';
7032 print
'<table id="tablelines" class="noborder noshadow centpercent nomarginbottom">';
7036 $object->printObjectLines($action,
$mysoc, $soc, $lineid, 1);
7040 if (
$object->status == 0 && $usercancreate && $action !=
'valid') {
7041 if ($action !=
'editline' && $action !=
'selectlines') {
7044 $parameters = array();
7045 $reshook = $hookmanager->executeHooks(
'formAddObjectLine', $parameters, $object, $action);
7047 setEventMessages($hookmanager->error, $hookmanager->errors,
'errors');
7049 if (empty($reshook)) {
7053 $parameters = array();
7054 $reshook = $hookmanager->executeHooks(
'formEditObjectLine', $parameters, $object, $action);
7068 if ($action !=
'prerelance' && $action !=
'presend' && $action !=
'valid' && $action !=
'editline') {
7069 print
'<div class="tabsAction">';
7071 $parameters = array();
7072 $reshook = $hookmanager->executeHooks(
'addMoreActionsButtons', $parameters, $object, $action);
7073 if (empty($reshook)) {
7076 'class' =>
'classfortooltip',
7083 $ventilExportCompta =
$object->getVentilExportCompta();
7085 if ($ventilExportCompta == 0) {
7087 if (!$objectidnext &&
$object->is_last_in_cycle()) {
7088 if ($usercanunvalidate) {
7089 unset($params[
'attr'][
'title']);
7090 print dolGetButtonAction($langs->trans(
'Modify'),
'',
'default', $_SERVER[
'PHP_SELF'] .
'?facid=' .
$object->id .
'&action=modif&token=' .
newToken(),
'',
true, $params);
7092 $params[
'attr'][
'title'] = $langs->trans(
'NotEnoughPermissions');
7093 print dolGetButtonAction($langs->trans(
'Modify'),
'',
'default', $_SERVER[
'PHP_SELF'] .
'?facid=' .
$object->id .
'&action=modif&token=' .
newToken(),
'',
false, $params);
7095 } elseif (!
$object->is_last_in_cycle()) {
7096 $params[
'attr'][
'title'] = $langs->trans(
'NotLastInCycle');
7097 print dolGetButtonAction($langs->trans(
'Modify'),
'',
'default',
'#',
'',
false, $params);
7099 $params[
'attr'][
'title'] = $langs->trans(
'DisabledBecauseReplacedInvoice');
7100 print dolGetButtonAction($langs->trans(
'Modify'),
'',
'default',
'#',
'',
false, $params);
7104 $params[
'attr'][
'title'] = $langs->trans(
'DisabledBecauseDispatchedInBookkeeping');
7105 print dolGetButtonAction($langs->trans(
'Modify'),
'',
'default',
'#',
'',
false, $params);
7110 $result = $discount->fetch(0,
$object->id);
7118 && ((!
getDolGlobalString(
'MAIN_USE_ADVANCED_PERMS') && $usercancreate) || $usercanreopen)) {
7119 if (
$object->close_code !=
'replaced' || (!$objectidnext)) {
7120 unset($params[
'attr'][
'title']);
7121 print dolGetButtonAction($langs->trans(
'ReOpen'),
'',
'default', $_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'&action=reopen&token='.
newToken(),
'',
true, $params);
7123 $params[
'attr'][
'title'] = $langs->trans(
"DisabledBecauseReplacedInvoice");
7124 print dolGetButtonAction($langs->trans(
'ReOpen'),
'',
'default',
'#',
'',
false, $params);
7131 $langs->load(
"contracts");
7133 if ($usercancreatecontract) {
7134 print
'<a class="butAction" href="' . DOL_URL_ROOT .
'/contrat/card.php?action=create&origin=' .
$object->element .
'&originid=' .
$object->id .
'&socid=' .
$object->socid .
'">' . $langs->trans(
'AddContract') .
'</a>';
7142 $langs->load(
"subtotals");
7144 $url_button = array();
7146 $url_button[] = array(
7147 'lang' =>
'subtotals',
7149 'perm' => (
bool) $usercancreate,
7150 'label' => $langs->trans(
'AddTitleLine'),
7151 'url' =>
'/compta/facture/card.php?facid='.$object->id.
'&action=add_title_line&token='.
newToken()
7154 $url_button[] = array(
7155 'lang' =>
'subtotals',
7157 'perm' => (
bool) $usercancreate,
7158 'label' => $langs->trans(
'AddSubtotalLine'),
7159 'url' =>
'/compta/facture/card.php?facid='.$object->id.
'&action=add_subtotal_line&token='.
newToken()
7162 $url_button[] = array(
7163 'lang' =>
'subtotals',
7165 'perm' => (
bool) $usercancreate,
7166 'label' => $langs->trans(
'AddTextLine'),
7167 'url' =>
'/compta/facture/card.php?facid='.$object->id.
'&action=add_text_line&token='.
newToken()
7169 print dolGetButtonAction(
'', $langs->trans(
'SubTotal'),
'default', $url_button,
'',
true);
7176 if ($usercanvalidate) {
7177 unset($params[
'attr'][
'title']);
7178 print dolGetButtonAction($langs->trans(
'Validate'),
'',
'default', $_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&action=valid&token='.
newToken(),
'',
true, $params);
7183 if (empty($user->socid)) {
7185 if ($objectidnext) {
7186 $params[
'attr'][
'title'] = $langs->trans(
"DisabledBecauseReplacedInvoice");
7187 print dolGetButtonAction(
'', $langs->trans(
'SendMail'),
'email',
'#',
'',
false, $params);
7190 unset($params[
'attr'][
'title']);
7191 print dolGetButtonAction(
'', $langs->trans(
'SendMail'),
'email', $_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'&action=presend&mode=init#formmailbeforetitle',
'',
true, $params);
7193 unset($params[
'attr'][
'title']);
7194 print dolGetButtonAction(
'', $langs->trans(
'SendMail'),
'email',
'#',
'',
false, $params);
7202 if ($resteapayer > 0) {
7203 if ($usercancreatewithdrarequest) {
7204 if (!$objectidnext &&
$object->close_code !=
'replaced') {
7205 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/compta/facture/prelevement.php?facid='.
$object->id.
'" title="'.
dol_escape_htmltag($langs->trans(
"MakeWithdrawRequest")).
'">'.$langs->trans(
"MakeWithdrawRequest").
'</a>';
7207 print
'<span class="butActionRefused classfortooltip" title="'.$langs->trans(
"DisabledBecauseReplacedInvoice").
'">'.$langs->trans(
'MakeWithdrawRequest').
'</span>';
7219 $langs->load(
"cashdesk");
7220 $receipt_url = DOL_URL_ROOT.
"/takepos/receipt.php";
7221 print
'<a target="_blank" rel="noopener noreferrer" class="butAction" href="'.$receipt_url.
'?facid='.((int)
$object->id).
'">'.$langs->trans(
'POSTicket').
'</a>';
7226 if ($objectidnext) {
7227 print
'<span class="butActionRefused classfortooltip" title="'.$langs->trans(
"DisabledBecauseReplacedInvoice").
'">'.$langs->trans(
'DoPayment').
'</span>';
7231 $params[
'attr'][
'title'] = $langs->trans(
'DisabledBecauseRemainderToPayIsZero');
7232 print dolGetButtonAction($langs->trans(
'DoPayment'),
'',
'default',
'#',
'',
false, $params);
7236 unset($params[
'attr'][
'title']);
7237 print dolGetButtonAction($langs->trans(
'DoPayment'),
'',
'default', DOL_URL_ROOT.
'/compta/paiement.php?facid='.
$object->id.
'&action=create'.(
$object->fk_account > 0 ?
'&accountid='.$object->fk_account :
''),
'', true, $params);
7242 $sumofpayment = $totalpaid;
7243 $sumofpaymentall = $totalpaid + $totalcreditnotes + $totaldeposits;
7249 if ($resteapayer == 0) {
7250 print
'<span class="butActionRefused classfortooltip" title="'.$langs->trans(
"DisabledBecauseRemainderToPayIsZero").
'">'.$langs->trans(
'DoPaymentBack').
'</span>';
7252 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/compta/paiement.php?facid='.
$object->id.
'&action=create&accountid='.
$object->fk_account.
'">'.$langs->trans(
'DoPaymentBack').
'</a>';
7258 print
'<a class="butAction'.($conf->use_javascript_ajax ?
' reposition' :
'').
'" href="'.$_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&action=converttoreduc&token='.
newToken().
'">'.$langs->trans(
'ConvertExcessReceivedToReduc').
'</a>';
7262 && (
getDolGlobalString(
'INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED') || $sumofpayment == 0) &&
$object->total_ht < 0
7264 print
'<a class="butAction classfortooltip'.($conf->use_javascript_ajax ?
' reposition' :
'').
'" href="'.$_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&action=converttoreduc&token='.
newToken().
'" title="'.
dol_escape_htmltag($langs->trans(
"ConfirmConvertToReduc2")).
'">'.$langs->trans(
'ConvertToReduc').
'</a>';
7271 print
'<a class="butAction'.($conf->use_javascript_ajax ?
' reposition' :
'').
'" href="'.$_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&action=converttoreduc&token='.
newToken().
'">'.$langs->trans(
'ConvertToReduc').
'</a>';
7273 print
'<span class="butActionRefused classfortooltip" title="'.$langs->trans(
"AmountPaidMustMatchAmountOfDownPayment").
'">'.$langs->trans(
'ConvertToReduc').
'</span>';
7287 $params[
'attr'][
'title'] = $langs->trans(
'AmountPaidMustMatchAmountOfDownPayment');
7288 print dolGetButtonAction($langs->trans(
'ClassifyPaid'),
'',
'default',
'#',
'',
false, $params);
7290 unset($params[
'attr'][
'title']);
7291 print dolGetButtonAction($langs->trans(
'ClassifyPaid'),
'',
'default', $_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'&action=paid&token='.
newToken(),
'',
true, $params);
7297 if ($totalpaid > 0 || $totalcreditnotes > 0) {
7299 print
'<a class="butAction'.($conf->use_javascript_ajax ?
' reposition' :
'').
'" href="'.$_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'&action=paid&token='.
newToken().
'">'.$langs->trans(
'ClassifyPaidPartially').
'</a>';
7302 if ($objectidnext) {
7303 print
'<span class="butActionRefused classfortooltip" title="'.$langs->trans(
"DisabledBecauseReplacedInvoice").
'">'.$langs->trans(
'ClassifyCanceled').
'</span>';
7305 print
'<a class="butAction'.($conf->use_javascript_ajax ?
' reposition' :
'').
'" href="'.$_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'&action=canceled&token='.
newToken().
'">'.$langs->trans(
'ClassifyCanceled').
'</a>';
7313 if (
$object->is_last_in_cycle() &&
$object->situation_final != 1) {
7314 print
'<a class="butAction" href="'.$_SERVER[
'PHP_SELF'].
'?action=create&type=5&origin=facture&originid='.
$object->id.
'&socid='.
$object->socid.
'" >'.$langs->trans(
'CreateNextSituationInvoice').
'</a>';
7315 } elseif (!
$object->is_last_in_cycle()) {
7316 print
'<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans(
"DisabledBecauseNotLastInCycle").
'">'.$langs->trans(
'CreateNextSituationInvoice').
'</a>';
7318 print
'<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans(
"DisabledBecauseFinal").
'">'.$langs->trans(
'CreateNextSituationInvoice').
'</a>';
7324 if (!$objectidnext) {
7325 $blockedDeposit =
false;
7327 $resrem = $db->query(
"SELECT COALESCE(SUM(amount_ttc),0) as unused_credit_ttc FROM ".MAIN_DB_PREFIX.
"societe_remise_except WHERE fk_facture_source=".((
int)
$object->id).
" AND fk_facture IS NULL AND fk_facture_line IS NULL");
7328 $blockedDeposit = ($resrem && (float) $db->fetch_object($resrem)->unused_credit_ttc <= 0);
7330 if ($blockedDeposit) {
7331 $langs->load(
'bills');
7332 print
'<span class="butActionRefused classfortooltip" title="'.$langs->trans(
"DepositFullyApplied").
'">'.$langs->trans(
"CreateCreditNote").
'</span>';
7334 print
'<a class="butAction" href="'.$_SERVER[
'PHP_SELF'].
'?socid='.
$object->socid.
'&fac_avoir='.
$object->id.
'&action=create&type=2'.(
$object->fk_project > 0 ?
'&projectid='.$object->fk_project :
'').(
$object->entity > 0 ?
'&originentity='.$object->entity :
'').
'">'.$langs->trans(
"CreateCreditNote").
'</a>';
7341 &&
$object->isSituationInvoice()
7344 &&
$object->is_last_in_cycle()
7347 if ($usercanunvalidate) {
7348 print
'<a class="butAction" href="'.$_SERVER[
'PHP_SELF'].
'?socid='.
$object->socid.
'&fac_avoir='.
$object->id.
'&invoiceAvoirWithLines=1&action=create&type=2'.(
$object->fk_project > 0 ?
'&projectid='.$object->fk_project :
'').
'">'.$langs->trans(
"CreateCreditNote").
'</a>';
7350 print
'<span class="butActionRefused classfortooltip" title="'.$langs->trans(
"NotEnoughPermissions").
'">'.$langs->trans(
"CreateCreditNote").
'</span>';
7356 if (!$objectidnext && count(
$object->lines) > 0) {
7357 unset($params[
'attr'][
'title']);
7358 print dolGetButtonAction($langs->trans(
'ChangeIntoRepeatableInvoice'),
'',
'default', DOL_URL_ROOT.
'/compta/facture/card-rec.php?facid='.
$object->id.
'&action=create',
'',
true, $params);
7364 unset($params[
'attr'][
'title']);
7365 print dolGetButtonAction($langs->trans(
'ToClone'), $langs->trans(
'ToClone'),
'clone', $_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'&action=clone&object=invoice&token='.
newToken(),
'',
true, array(
'attr' => array(
'class' =>
'reposition')));
7370 &&
$object->isSituationInvoice()
7373 &&
$object->situation_counter > 1
7374 &&
$object->is_last_in_cycle()
7375 && $usercanunvalidate
7378 print
'<a id="butSituationOut" class="butAction" href="'.$_SERVER[
'PHP_SELF'].
'?facid='.
$object->id.
'&action=situationout&token='.
newToken().
'">'.$langs->trans(
"RemoveSituationFromCycle").
'</a>';
7380 print
'<a id="butSituationOutRefused" class="butActionRefused classfortooltip" href="#" title="'.$langs->trans(
"DisabledBecauseNotEnouthCreditNote").
'" >'.$langs->trans(
"RemoveSituationFromCycle").
'</a>';
7385 $isErasable =
$object->is_erasable();
7388 if ($isErasable == -6) {
7389 $htmltooltip = $langs->trans(
'DisabledBecauseAlreadySentByEmail');
7390 } elseif ($isErasable == -5) {
7391 $htmltooltip = $langs->trans(
'DisabledBecauseAlreadyPrintedOnce');
7392 } elseif ($isErasable == -4) {
7393 $htmltooltip = $langs->trans(
'DisabledBecausePayments');
7394 } elseif ($isErasable == -3) {
7395 $htmltooltip = $langs->trans(
'DisabledBecauseNotLastSituationInvoice');
7396 } elseif ($isErasable == -2) {
7397 $htmltooltip = $langs->trans(
'DisabledBecauseNotLastInvoice');
7398 } elseif ($isErasable == -1) {
7399 $htmltooltip = $langs->trans(
'DisabledBecauseDispatchedInBookkeeping');
7400 } elseif ($isErasable <= 0) {
7401 $htmltooltip = $langs->trans(
'DisabledBecauseNotErasable').(empty(
$object->error) ?
': UnknownReason' :
': '.$object->error);
7402 } elseif ($objectidnext) {
7403 $htmltooltip = $langs->trans(
'DisabledBecauseReplacedInvoice');
7405 if ($usercandelete || ($usercancreate && $isErasable == 1)) {
7406 $enableDelete =
false;
7408 if ($isErasable > 0 && ! $objectidnext) {
7409 $deleteHref = $_SERVER[
"PHP_SELF"].
'?facid='.
$object->id.
'&action=delete&token='.
newToken();
7410 $enableDelete =
true;
7412 unset($params[
'attr'][
'title']);
7413 print dolGetButtonAction($htmltooltip, $langs->trans(
'Delete'),
'delete', $deleteHref,
'', $enableDelete, array(
'attr' => array(
'class' =>
'reposition')));
7415 unset($params[
'attr'][
'title']);
7416 print dolGetButtonAction($htmltooltip, $langs->trans(
'Delete'),
'delete',
'#',
'',
false);
7423 if (
GETPOST(
'modelselected',
'alpha')) {
7424 $action =
'presend';
7426 if ($action !=
'prerelance' && $action !=
'presend') {
7427 print
'<div class="fichecenter"><div class="fichehalfleft">';
7428 print
'<a name="builddoc"></a>';
7433 $urlsource = $_SERVER[
'PHP_SELF'].
'?facid='.
$object->id;
7434 $genallowed = $usercanread;
7435 $delallowed = $usercancreate;
7436 $tooltipAfterComboOfModels =
'';
7438 $tooltipAfterComboOfModels = $langs->trans(
"AccordingToYourSetupTheFileWillBeConcatenated",
getDolGlobalString(
'MAIN_INFO_INVOICE_TERMSOFSALE'));
7441 print $formfile->showdocuments(
7461 'remove_file_comfirm',
7462 $tooltipAfterComboOfModels
7465 $somethingshown = $formfile->numoffiles;
7468 $tmparray = $form->showLinkToObjectBlock($object, array(), array(
'invoice'), 1);
7469 $linktoelem = $tmparray[
'linktoelem'];
7470 $htmltoenteralink = $tmparray[
'htmltoenteralink'];
7471 print $htmltoenteralink;
7473 $compatibleImportElementsList =
false;
7477 $compatibleImportElementsList = array(
'commande',
'propal',
'subscription');
7479 $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
7483 include_once DOL_DOCUMENT_ROOT.
'/core/lib/payments.lib.php';
7484 $validpaymentmethod = getValidOnlinePaymentMethods(
'');
7485 $useonlinepayment = count($validpaymentmethod);
7488 print
'<br><!-- Link to pay -->'.
"\n";
7489 require_once DOL_DOCUMENT_ROOT.
'/core/lib/payments.lib.php';
7490 print showOnlinePaymentUrl(
'invoice',
$object->ref).
'<br>';
7493 print
'</div><div class="fichehalfright">';
7497 $morehtmlcenter =
'<div class="nowraponall">';
7498 $morehtmlcenter .=
dolGetButtonTitle($langs->trans(
'FullConversation'),
'',
'fa fa-comments imgforviewmode', DOL_URL_ROOT.
'/compta/facture/messaging.php?id='.
$object->id);
7499 $morehtmlcenter .=
dolGetButtonTitle($langs->trans(
'FullList'),
'',
'fa fa-bars imgforviewmode', DOL_URL_ROOT.
'/compta/facture/agenda.php?id='.
$object->id);
7500 $morehtmlcenter .=
'</div>';
7503 include_once DOL_DOCUMENT_ROOT.
'/core/class/html.formactions.class.php';
7505 $somethingshown = $formactions->showactions($object,
'invoice', $socid, 1,
'', $MAXEVENT,
'', $morehtmlcenter);
7507 print
'</div></div>';
7512 $modelmail =
'facture_send';
7513 $defaulttopic =
'SendBillRef';
7515 $trackid =
'inv'.$object->id;
7517 include DOL_DOCUMENT_ROOT.
'/core/tpl/card_presend.tpl.php';
$id
Support class for third parties, contacts, members, users or resources.
if(! $sortfield) if(! $sortorder) $object
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage bank accounts.
Class to manage accounting journals.
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage warehouses.
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const STATUS_DRAFT
Draft status.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_PROFORMA
Proforma invoice (should not be used.
const STATUS_VALIDATED
Validated (need to be paid)
const TYPE_DEPOSIT
Deposit invoice.
const STATUS_ABANDONED
Classified abandoned and no payment done.
const TYPE_CREDIT_NOTE
Credit note invoice.
const STATUS_CLOSED
Classified paid.
Class to manage invoice lines.
Class to manage invoice templates.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
Class to manage the table of subscription to notifications.
Class to manage payments of customer invoices.
Class ProductCombination Used to represent the relation between a product and one of its variants.
Class to manage products or services.
const TYPE_PRODUCT
Regular product.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage VAT - Value-added tax (also known in French as TVA)
Class to manage Dolibarr users.
if(! $sortfield) if(! $sortorder) $module
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
dol_stringtotime($string, $gm=1, $processnotimeasnoon=0)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
GETPOSTDATE($prefix, $hourTime='', $gm='auto', $saverestore='')
Helper function that combines values of a dolibarr DatePicker (such as Form\selectDate) for year,...
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
GETPOSTISARRAY($paramname, $method=0)
Return true if the parameter $paramname is submit from a POST OR GET as an array.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
getDolCurrency()
Return the main currency ('EUR', 'USD', ...)
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
facture_prepare_head($object)
Initialize the array of tabs for customer invoice.
dolPayRefGenerateForInvoice($object, $user, $store=1)
Generate and optionally store the payment reference of an invoice.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
shippingSetStandaloneLineSellPrice($line, $buyer)
Complete a line of a standalone shipment (SHIPMENT_STANDALONE, no source order) before it is copied i...