card.php 163 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823
  1. <?php
  2. /* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  5. * Copyright (C) 2005 Marc Barilley <marc@ocebo.fr>
  6. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2010-2019 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2013-2015 Philippe Grand <philippe.grand@atoo-net.com>
  9. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  10. * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2016-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  12. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  13. * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
  14. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  15. *
  16. * This program is free software; you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation; either version 3 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  28. */
  29. /**
  30. * \file htdocs/fourn/facture/card.php
  31. * \ingroup facture, fournisseur
  32. * \brief Page for supplier invoice card (view, edit, validate)
  33. */
  34. require '../../main.inc.php';
  35. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
  38. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture-rec.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  44. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  45. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  46. if (!empty($conf->product->enabled)) {
  47. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  48. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  49. }
  50. if (!empty($conf->projet->enabled)) {
  51. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  52. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  53. }
  54. if (!empty($conf->variants->enabled)) {
  55. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  56. }
  57. if (!empty($conf->accounting->enabled)) {
  58. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
  59. }
  60. $langs->loadLangs(array('bills', 'compta', 'suppliers', 'companies', 'products', 'banks', 'admin'));
  61. if (!empty($conf->incoterm->enabled)) {
  62. $langs->load('incoterm');
  63. }
  64. $id = (GETPOST('facid', 'int') ? GETPOST('facid', 'int') : GETPOST('id', 'int'));
  65. $socid = GETPOST('socid', 'int');
  66. $action = GETPOST('action', 'aZ09');
  67. $confirm = GETPOST("confirm");
  68. $ref = GETPOST('ref', 'alpha');
  69. $cancel = GETPOST('cancel', 'alpha');
  70. $lineid = GETPOST('lineid', 'int');
  71. $projectid = GETPOST('projectid', 'int');
  72. $origin = GETPOST('origin', 'alpha');
  73. $originid = GETPOST('originid', 'int');
  74. $fac_recid = GETPOST('fac_rec', 'int');
  75. $rank = (GETPOST('rank', 'int') > 0) ? GETPOST('rank', 'int') : -1;
  76. // PDF
  77. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  78. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  79. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  80. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  81. $hookmanager->initHooks(array('invoicesuppliercard', 'globalcard'));
  82. $object = new FactureFournisseur($db);
  83. $extrafields = new ExtraFields($db);
  84. // fetch optionals attributes and labels
  85. $extrafields->fetch_name_optionals_label($object->table_element);
  86. // Load object
  87. if ($id > 0 || !empty($ref)) {
  88. $ret = $object->fetch($id, $ref);
  89. if ($ret < 0) {
  90. dol_print_error($db, $object->error);
  91. }
  92. $ret = $object->fetch_thirdparty();
  93. if ($ret < 0) {
  94. dol_print_error($db, $object->error);
  95. }
  96. }
  97. // Security check
  98. $socid = '';
  99. if (!empty($user->socid)) {
  100. $socid = $user->socid;
  101. }
  102. $isdraft = (($object->statut == FactureFournisseur::STATUS_DRAFT) ? 1 : 0);
  103. $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture', 'fk_soc', 'rowid', $isdraft);
  104. // Common permissions
  105. $usercanread = ($user->rights->fournisseur->facture->lire || $user->rights->supplier_invoice->lire);
  106. $usercancreate = ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer);
  107. $usercandelete = ($user->rights->fournisseur->facture->supprimer || $user->rights->supplier_invoice->supprimer);
  108. // Advanced permissions
  109. $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate)));
  110. $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send);
  111. // Permissions for includes
  112. $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
  113. $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
  114. $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
  115. $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
  116. $error = 0;
  117. /*
  118. * Actions
  119. */
  120. $parameters = array('socid'=>$socid);
  121. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  122. if ($reshook < 0) {
  123. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  124. }
  125. if (empty($reshook)) {
  126. $backurlforlist = DOL_URL_ROOT.'/fourn/facture/list.php';
  127. if (empty($backtopage) || ($cancel && empty($id))) {
  128. if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
  129. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  130. $backtopage = $backurlforlist;
  131. } else {
  132. $backtopage = DOL_URL_ROOT.'/fourn/facture/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
  133. }
  134. }
  135. }
  136. if ($cancel) {
  137. if (!empty($backtopageforcancel)) {
  138. header("Location: ".$backtopageforcancel);
  139. exit;
  140. } elseif (!empty($backtopage)) {
  141. header("Location: ".$backtopage);
  142. exit;
  143. }
  144. $action = '';
  145. }
  146. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  147. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  148. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  149. // Link invoice to order
  150. if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) {
  151. $object->fetch($id);
  152. $object->fetch_thirdparty();
  153. $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder'));
  154. }
  155. // Action clone object
  156. if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
  157. $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
  158. if (GETPOST('newsupplierref', 'alphanohtml')) {
  159. $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml');
  160. }
  161. $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
  162. $result = $objectutil->createFromClone($user, $id);
  163. if ($result > 0) {
  164. header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
  165. exit;
  166. } else {
  167. $langs->load("errors");
  168. setEventMessages($objectutil->error, $objectutil->errors, 'errors');
  169. $action = '';
  170. }
  171. } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
  172. $idwarehouse = GETPOST('idwarehouse');
  173. $object->fetch($id);
  174. $object->fetch_thirdparty();
  175. $qualified_for_stock_change = 0;
  176. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  177. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  178. } else {
  179. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  180. }
  181. // Check parameters
  182. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  183. $langs->load("stocks");
  184. if (!$idwarehouse || $idwarehouse == -1) {
  185. $error++;
  186. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  187. $action = '';
  188. }
  189. }
  190. if (!$error) {
  191. $result = $object->validate($user, '', $idwarehouse);
  192. if ($result < 0) {
  193. setEventMessages($object->error, $object->errors, 'errors');
  194. } else {
  195. // Define output language
  196. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  197. $outputlangs = $langs;
  198. $newlang = '';
  199. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  200. $newlang = GETPOST('lang_id', 'aZ09');
  201. }
  202. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  203. $newlang = $object->thirdparty->default_lang;
  204. }
  205. if (!empty($newlang)) {
  206. $outputlangs = new Translate("", $conf);
  207. $outputlangs->setDefaultLang($newlang);
  208. }
  209. $model = $object->model_pdf;
  210. $ret = $object->fetch($id); // Reload to get new records
  211. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  212. if ($result < 0) {
  213. dol_print_error($db, $result);
  214. }
  215. }
  216. }
  217. }
  218. } elseif ($action == 'confirm_delete' && $confirm == 'yes') {
  219. $object->fetch($id);
  220. $object->fetch_thirdparty();
  221. $isErasable = $object->is_erasable();
  222. if (($usercandelete && $isErasable > 0) || ($usercancreate && $isErasable == 1)) {
  223. $result = $object->delete($user);
  224. if ($result > 0) {
  225. header('Location: list.php?restore_lastsearch_values=1');
  226. exit;
  227. } else {
  228. setEventMessages($object->error, $object->errors, 'errors');
  229. }
  230. }
  231. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
  232. // Remove a product line
  233. $result = $object->deleteline($lineid);
  234. if ($result > 0) {
  235. // reorder lines
  236. $object->line_order(true);
  237. // Define output language
  238. /*$outputlangs = $langs;
  239. $newlang = '';
  240. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09'))
  241. $newlang = GETPOST('lang_id','aZ09');
  242. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  243. $newlang = $object->thirdparty->default_lang;
  244. if (! empty($newlang)) {
  245. $outputlangs = new Translate("", $conf);
  246. $outputlangs->setDefaultLang($newlang);
  247. }
  248. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  249. $ret = $object->fetch($object->id); // Reload to get new records
  250. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  251. }*/
  252. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
  253. exit;
  254. } else {
  255. setEventMessages($object->error, $object->errors, 'errors');
  256. /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */
  257. $action = '';
  258. }
  259. } elseif ($action == 'unlinkdiscount' && $usercancreate) {
  260. // Delete link of credit note to invoice
  261. $discount = new DiscountAbsolute($db);
  262. $result = $discount->fetch(GETPOST("discountid"));
  263. $discount->unlink_invoice();
  264. } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercancreate) {
  265. $object->fetch($id);
  266. $result = $object->setPaid($user);
  267. if ($result < 0) {
  268. setEventMessages($object->error, $object->errors, 'errors');
  269. }
  270. } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes') {
  271. // Classif "paid partialy"
  272. $object->fetch($id);
  273. $close_code = GETPOST("close_code", 'restricthtml');
  274. $close_note = GETPOST("close_note", 'restricthtml');
  275. if ($close_code) {
  276. $result = $object->setPaid($user, $close_code, $close_note);
  277. if ($result < 0) {
  278. setEventMessages($object->error, $object->errors, 'errors');
  279. }
  280. } else {
  281. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  282. }
  283. } elseif ($action == 'confirm_canceled' && $confirm == 'yes') {
  284. // Classify "abandoned"
  285. $object->fetch($id);
  286. $close_code = GETPOST("close_code", 'restricthtml');
  287. $close_note = GETPOST("close_note", 'restricthtml');
  288. if ($close_code) {
  289. $result = $object->setCanceled($user, $close_code, $close_note);
  290. if ($result < 0) {
  291. setEventMessages($object->error, $object->errors, 'errors');
  292. }
  293. } else {
  294. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  295. }
  296. }
  297. // Set supplier ref
  298. if ($action == 'setref_supplier' && $usercancreate) {
  299. $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
  300. if ($object->update($user) < 0) {
  301. setEventMessages($object->error, $object->errors, 'errors');
  302. } else {
  303. // Define output language
  304. $outputlangs = $langs;
  305. $newlang = '';
  306. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  307. $newlang = GETPOST('lang_id', 'aZ09');
  308. }
  309. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  310. $newlang = $object->thirdparty->default_lang;
  311. }
  312. if (!empty($newlang)) {
  313. $outputlangs = new Translate("", $conf);
  314. $outputlangs->setDefaultLang($newlang);
  315. }
  316. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  317. $ret = $object->fetch($object->id); // Reload to get new records
  318. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  319. }
  320. }
  321. }
  322. // payments conditions
  323. if ($action == 'setconditions' && $usercancreate) {
  324. $object->fetch($id);
  325. $object->cond_reglement_code = 0; // To clean property
  326. $object->cond_reglement_id = 0; // To clean property
  327. $error = 0;
  328. $db->begin();
  329. if (!$error) {
  330. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  331. if ($result < 0) {
  332. $error++;
  333. setEventMessages($object->error, $object->errors, 'errors');
  334. }
  335. }
  336. if (!$error) {
  337. $old_date_echeance = $object->date_echeance;
  338. $new_date_echeance = $object->calculate_date_lim_reglement();
  339. if ($new_date_echeance > $old_date_echeance) {
  340. $object->date_echeance = $new_date_echeance;
  341. }
  342. if ($object->date_echeance < $object->date) {
  343. $object->date_echeance = $object->date;
  344. }
  345. $result = $object->update($user);
  346. if ($result < 0) {
  347. $error++;
  348. setEventMessages($object->error, $object->errors, 'errors');
  349. }
  350. }
  351. if ($error) {
  352. $db->rollback();
  353. } else {
  354. $db->commit();
  355. }
  356. } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) {
  357. // Set incoterm
  358. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  359. } elseif ($action == 'setmode' && $usercancreate) {
  360. // payment mode
  361. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  362. } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
  363. // Multicurrency Code
  364. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  365. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
  366. // Multicurrency rate
  367. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx', 'alpha')), GETPOST('calculation_mode', 'int'));
  368. } elseif ($action == 'setbankaccount' && $usercancreate) {
  369. // bank account
  370. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  371. }
  372. if ($action == 'settransportmode' && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)) {
  373. // transport mode
  374. $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int'));
  375. } elseif ($action == 'setlabel' && $usercancreate) {
  376. // Set label
  377. $object->fetch($id);
  378. $object->label = GETPOST('label');
  379. $result = $object->update($user);
  380. if ($result < 0) {
  381. dol_print_error($db);
  382. }
  383. } elseif ($action == 'setdatef' && $usercancreate) {
  384. $newdate = dol_mktime(0, 0, 0, GETPOST('datefmonth', 'int'), GETPOST('datefday', 'int'), GETPOST('datefyear', 'int'), 'tzserver');
  385. if ($newdate > (dol_now('tzuserrel') + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  386. if (empty($conf->global->INVOICE_MAX_FUTURE_DELAY)) {
  387. setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
  388. } else {
  389. setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
  390. }
  391. }
  392. $object->fetch($id);
  393. $object->date = $newdate;
  394. $date_echence_calc = $object->calculate_date_lim_reglement();
  395. if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) {
  396. $object->date_echeance = $date_echence_calc;
  397. }
  398. if ($object->date_echeance && $object->date_echeance < $object->date) {
  399. $object->date_echeance = $object->date;
  400. }
  401. $result = $object->update($user);
  402. if ($result < 0) {
  403. dol_print_error($db, $object->error);
  404. }
  405. } elseif ($action == 'setdate_lim_reglement' && $usercancreate) {
  406. $object->fetch($id);
  407. $object->date_echeance = dol_mktime(12, 0, 0, GETPOST('date_lim_reglementmonth', 'int'), GETPOST('date_lim_reglementday', 'int'), GETPOST('date_lim_reglementyear', 'int'));
  408. if (!empty($object->date_echeance) && $object->date_echeance < $object->date) {
  409. $object->date_echeance = $object->date;
  410. setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
  411. }
  412. $result = $object->update($user);
  413. if ($result < 0) {
  414. dol_print_error($db, $object->error);
  415. }
  416. } elseif ($action == "setabsolutediscount" && $usercancreate) {
  417. // We use the credit to reduce amount of invoice
  418. if (GETPOST("remise_id", "int")) {
  419. $ret = $object->fetch($id);
  420. if ($ret > 0) {
  421. $result = $object->insert_discount(GETPOST("remise_id", "int"));
  422. if ($result < 0) {
  423. setEventMessages($object->error, $object->errors, 'errors');
  424. }
  425. } else {
  426. dol_print_error($db, $object->error);
  427. }
  428. }
  429. // We use the credit to reduce remain to pay
  430. if (GETPOST("remise_id_for_payment", "int")) {
  431. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  432. $discount = new DiscountAbsolute($db);
  433. $discount->fetch(GETPOST("remise_id_for_payment", "int"));
  434. //var_dump($object->getRemainToPay(0));
  435. //var_dump($discount->amount_ttc);exit;
  436. if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) {
  437. // TODO Split the discount in 2 automatically
  438. $error++;
  439. setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
  440. }
  441. if (!$error) {
  442. $result = $discount->link_to_invoice(0, $id);
  443. if ($result < 0) {
  444. setEventMessages($discount->error, $discount->errors, 'errors');
  445. }
  446. }
  447. }
  448. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  449. $outputlangs = $langs;
  450. $newlang = '';
  451. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  452. $newlang = GETPOST('lang_id', 'aZ09');
  453. }
  454. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  455. $newlang = $object->thirdparty->default_lang;
  456. }
  457. if (!empty($newlang)) {
  458. $outputlangs = new Translate("", $conf);
  459. $outputlangs->setDefaultLang($newlang);
  460. }
  461. $ret = $object->fetch($id); // Reload to get new records
  462. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  463. if ($result < 0) {
  464. setEventMessages($object->error, $object->errors, 'errors');
  465. }
  466. }
  467. } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
  468. // Convertir en reduc
  469. $object->fetch($id);
  470. $object->fetch_thirdparty();
  471. //$object->fetch_lines(); // Already done into fetch
  472. // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
  473. $discountcheck = new DiscountAbsolute($db);
  474. $result = $discountcheck->fetch(0, 0, $object->id);
  475. $canconvert = 0;
  476. if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) {
  477. $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
  478. }
  479. if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) {
  480. $canconvert = 1; // we can convert credit note into discount if credit note is not refunded completely and not already converted and amount of payment is 0 (see also the real condition used as the condition to show button converttoreduc)
  481. }
  482. if ($canconvert) {
  483. $db->begin();
  484. $amount_ht = $amount_tva = $amount_ttc = array();
  485. $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
  486. // Loop on each vat rate
  487. $i = 0;
  488. foreach ($object->lines as $line) {
  489. if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null
  490. $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
  491. $amount_ht[$keyforvatrate] += $line->total_ht;
  492. $amount_tva[$keyforvatrate] += $line->total_tva;
  493. $amount_ttc[$keyforvatrate] += $line->total_ttc;
  494. $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
  495. $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
  496. $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
  497. $i++;
  498. }
  499. }
  500. // If some payments were already done, we change the amount to pay using same prorate
  501. if (!empty($conf->global->SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) && $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  502. $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
  503. if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
  504. $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
  505. foreach ($amount_ht as $vatrate => $val) {
  506. $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
  507. $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
  508. $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
  509. $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
  510. $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
  511. $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
  512. }
  513. }
  514. }
  515. //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
  516. // Insert one discount by VAT rate category
  517. $discount = new DiscountAbsolute($db);
  518. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  519. $discount->description = '(CREDIT_NOTE)';
  520. } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) {
  521. $discount->description = '(DEPOSIT)';
  522. } elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) {
  523. $discount->description = '(EXCESS PAID)';
  524. } else {
  525. setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
  526. }
  527. $discount->discount_type = 1; // Supplier discount
  528. $discount->fk_soc = $object->socid;
  529. $discount->fk_invoice_supplier_source = $object->id;
  530. $error = 0;
  531. if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) {
  532. // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT
  533. // Total payments
  534. $sql = 'SELECT SUM(pf.amount) as total_paiements';
  535. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p';
  536. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')';
  537. $sql .= ' WHERE pf.fk_facturefourn = '.((int) $object->id);
  538. $sql .= ' AND pf.fk_paiementfourn = p.rowid';
  539. $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
  540. $resql = $db->query($sql);
  541. if (!$resql) {
  542. dol_print_error($db);
  543. }
  544. $res = $db->fetch_object($resql);
  545. $total_paiements = $res->total_paiements;
  546. // Total credit note and deposit
  547. $total_creditnote_and_deposit = 0;
  548. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  549. $sql .= " re.description, re.fk_invoice_supplier_source";
  550. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  551. $sql .= " WHERE fk_invoice_supplier = ".((int) $object->id);
  552. $resql = $db->query($sql);
  553. if (!empty($resql)) {
  554. while ($obj = $db->fetch_object($resql)) {
  555. $total_creditnote_and_deposit += $obj->amount_ttc;
  556. }
  557. } else {
  558. dol_print_error($db);
  559. }
  560. $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
  561. $discount->amount_tva = 0;
  562. $discount->tva_tx = 0;
  563. $discount->vat_src_code = '';
  564. $result = $discount->create($user);
  565. if ($result < 0) {
  566. $error++;
  567. }
  568. }
  569. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
  570. foreach ($amount_ht as $tva_tx => $xxx) {
  571. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  572. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  573. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  574. $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
  575. $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
  576. $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
  577. // Clean vat code
  578. $reg = array();
  579. $vat_src_code = '';
  580. if (preg_match('/\((.*)\)/', $tva_tx, $reg)) {
  581. $vat_src_code = $reg[1];
  582. $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx); // Remove code into vatrate.
  583. }
  584. $discount->tva_tx = abs($tva_tx);
  585. $discount->vat_src_code = $vat_src_code;
  586. $result = $discount->create($user);
  587. if ($result < 0) {
  588. $error++;
  589. break;
  590. }
  591. }
  592. }
  593. if (empty($error)) {
  594. if ($object->type != FactureFournisseur::TYPE_DEPOSIT) {
  595. // Classe facture
  596. $result = $object->setPaid($user);
  597. if ($result >= 0) {
  598. $db->commit();
  599. } else {
  600. setEventMessages($object->error, $object->errors, 'errors');
  601. $db->rollback();
  602. }
  603. } else {
  604. $db->commit();
  605. }
  606. } else {
  607. setEventMessages($discount->error, $discount->errors, 'errors');
  608. $db->rollback();
  609. }
  610. }
  611. } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) {
  612. // Delete payment
  613. $object->fetch($id);
  614. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) {
  615. $paiementfourn = new PaiementFourn($db);
  616. $result = $paiementfourn->fetch(GETPOST('paiement_id'));
  617. if ($result > 0) {
  618. $result = $paiementfourn->delete(); // If fetch ok and found
  619. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  620. }
  621. if ($result < 0) {
  622. setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors');
  623. }
  624. }
  625. } elseif ($action == 'add' && $usercancreate) {
  626. // Insert new invoice in database
  627. if ($socid > 0) {
  628. $object->socid = GETPOST('socid', 'int');
  629. }
  630. $selectedLines = GETPOST('toselect', 'array');
  631. $db->begin();
  632. $error = 0;
  633. // Fill array 'array_options' with data from add form
  634. $ret = $extrafields->setOptionalsFromPost(null, $object);
  635. if ($ret < 0) {
  636. $error++;
  637. }
  638. $dateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver'); // If we enter the 02 january, we need to save the 02 january for server
  639. $datedue = dol_mktime(0, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int'), 'tzserver');
  640. //var_dump($dateinvoice.' '.dol_print_date($dateinvoice, 'dayhour'));
  641. //var_dump(dol_now('tzuserrel').' '.dol_get_last_hour(dol_now('tzuserrel')).' '.dol_print_date(dol_now('tzuserrel'),'dayhour').' '.dol_print_date(dol_get_last_hour(dol_now('tzuserrel')), 'dayhour'));
  642. //var_dump($db->idate($dateinvoice));
  643. //exit;
  644. // Replacement invoice
  645. if (GETPOST('type') == FactureFournisseur::TYPE_REPLACEMENT) {
  646. if (empty($dateinvoice)) {
  647. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  648. $action = 'create';
  649. $_GET['socid'] = $_POST['socid'];
  650. $error++;
  651. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  652. $error++;
  653. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  654. $action = 'create';
  655. }
  656. if (!(GETPOST('fac_replacement', 'int') > 0)) {
  657. $error++;
  658. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
  659. }
  660. if (!$error) {
  661. // This is a replacement invoice
  662. $result = $object->fetch(GETPOST('fac_replacement', 'int'));
  663. $object->fetch_thirdparty();
  664. $object->ref = GETPOST('ref', 'nohtml');
  665. $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
  666. $object->socid = GETPOST('socid', 'int');
  667. $object->libelle = GETPOST('label', 'nohtml');
  668. $object->date = $dateinvoice;
  669. $object->date_echeance = $datedue;
  670. $object->note_public = GETPOST('note_public', 'restricthtml');
  671. $object->note_private = GETPOST('note_private', 'restricthtml');
  672. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  673. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  674. $object->fk_account = GETPOST('fk_account', 'int');
  675. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  676. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  677. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  678. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  679. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  680. $object->transport_mode_id = GETPOST('transport_mode_id', 'int');
  681. // Proprietes particulieres a facture de remplacement
  682. $object->fk_facture_source = GETPOST('fac_replacement', 'int');
  683. $object->type = FactureFournisseur::TYPE_REPLACEMENT;
  684. $id = $object->createFromCurrent($user);
  685. if ($id <= 0) {
  686. $error++;
  687. setEventMessages($object->error, $object->errors, 'errors');
  688. }
  689. }
  690. }
  691. // Credit note invoice
  692. if (GETPOST('type') == FactureFournisseur::TYPE_CREDIT_NOTE) {
  693. $sourceinvoice = GETPOST('fac_avoir', 'int');
  694. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  695. $error++;
  696. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  697. }
  698. if (GETPOST('socid', 'int') < 1) {
  699. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
  700. $action = 'create';
  701. $error++;
  702. }
  703. if (empty($dateinvoice)) {
  704. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  705. $action = 'create';
  706. $_GET['socid'] = $_POST['socid'];
  707. $error++;
  708. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  709. $error++;
  710. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  711. $action = 'create';
  712. }
  713. if (!GETPOST('ref_supplier')) {
  714. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors');
  715. $action = 'create';
  716. $_GET['socid'] = $_POST['socid'];
  717. $error++;
  718. }
  719. if (!$error) {
  720. $tmpproject = GETPOST('projectid', 'int');
  721. // Creation facture
  722. $object->ref = GETPOST('ref', 'nohtml');
  723. $object->ref_supplier = GETPOST('ref_supplier', 'nohtml');
  724. $object->socid = GETPOST('socid', 'int');
  725. $object->libelle = GETPOST('label', 'nohtml');
  726. $object->label = GETPOST('label', 'nohtml');
  727. $object->date = $dateinvoice;
  728. $object->date_echeance = $datedue;
  729. $object->note_public = GETPOST('note_public', 'restricthtml');
  730. $object->note_private = GETPOST('note_private', 'restricthtml');
  731. $object->cond_reglement_id = GETPOST('cond_reglement_id');
  732. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  733. $object->fk_account = GETPOST('fk_account', 'int');
  734. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  735. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  736. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  737. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  738. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  739. $object->transport_mode_id = GETPOST('transport_mode_id', 'int');
  740. // Proprietes particulieres a facture avoir
  741. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  742. $object->type = FactureFournisseur::TYPE_CREDIT_NOTE;
  743. $id = $object->create($user);
  744. if ($id <= 0) {
  745. $error++;
  746. }
  747. if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
  748. $facture_source = new FactureFournisseur($db); // fetch origin object
  749. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  750. $fk_parent_line = 0;
  751. foreach ($facture_source->lines as $line) {
  752. // Reset fk_parent_line for no child products and special product
  753. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  754. $fk_parent_line = 0;
  755. }
  756. $line->fk_facture_fourn = $object->id;
  757. $line->fk_parent_line = $fk_parent_line;
  758. $line->subprice = -$line->subprice; // invert price for object
  759. $line->pa_ht = -$line->pa_ht;
  760. $line->total_ht = -$line->total_ht;
  761. $line->total_tva = -$line->total_tva;
  762. $line->total_ttc = -$line->total_ttc;
  763. $line->total_localtax1 = -$line->total_localtax1;
  764. $line->total_localtax2 = -$line->total_localtax2;
  765. $result = $line->insert();
  766. $object->lines[] = $line; // insert new line in current object
  767. // Defined the new fk_parent_line
  768. if ($result > 0 && $line->product_type == 9) {
  769. $fk_parent_line = $result;
  770. }
  771. }
  772. $object->update_price(1);
  773. }
  774. }
  775. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  776. $facture_source = new FactureFournisseur($db); // fetch origin object if not previously defined
  777. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  778. $totalpaye = $facture_source->getSommePaiement();
  779. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  780. $totaldeposits = $facture_source->getSumDepositsUsed();
  781. $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits);
  782. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 0, 0, 0, 1, 0, 0, '', '', 'TTC');
  783. }
  784. }
  785. }
  786. } elseif ($fac_recid > 0 && (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT)) {
  787. // Standard invoice or Deposit invoice, created from a Predefined template invoice
  788. if (empty($dateinvoice)) {
  789. $error++;
  790. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  791. $action = 'create';
  792. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  793. $error++;
  794. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  795. $action = 'create';
  796. }
  797. if (!$error) {
  798. $object->socid = GETPOST('socid', 'int');
  799. $object->type = GETPOST('type');
  800. $object->ref = GETPOST('ref');
  801. $object->date = $dateinvoice;
  802. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  803. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  804. $object->ref_supplier = GETPOST('ref_supplier', 'nohtml');
  805. $object->model_pdf = GETPOST('model');
  806. $object->fk_project = GETPOST('projectid', 'int');
  807. $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  808. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  809. $object->fk_account = GETPOST('fk_account', 'int');
  810. $object->amount = price2num(GETPOST('amount'));
  811. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  812. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  813. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  814. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  815. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  816. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  817. // Source facture
  818. $object->fac_rec = $fac_recid;
  819. $fac_rec = new FactureFournisseurRec($db);
  820. $fac_rec->fetch($object->fac_rec);
  821. $fac_rec->fetch_lines();
  822. $object->lines = $fac_rec->lines;
  823. $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines
  824. }
  825. } elseif ($fac_recid <= 0 && (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT)) {
  826. // Standard invoice or Deposit invoice, not from a Predefined template invoice
  827. if (GETPOST('socid', 'int') < 1) {
  828. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
  829. $action = 'create';
  830. $error++;
  831. }
  832. if (empty($dateinvoice)) {
  833. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  834. $action = 'create';
  835. $_GET['socid'] = $_POST['socid'];
  836. $error++;
  837. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  838. $error++;
  839. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  840. $action = 'create';
  841. }
  842. if (!GETPOST('ref_supplier')) {
  843. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors');
  844. $action = 'create';
  845. $_GET['socid'] = $_POST['socid'];
  846. $error++;
  847. }
  848. if (!$error) {
  849. $tmpproject = GETPOST('projectid', 'int');
  850. // Creation invoice
  851. $object->socid = GETPOST('socid', 'int');
  852. $object->type = GETPOST('type');
  853. $object->ref = GETPOST('ref', 'nohtml');
  854. $object->ref_supplier = GETPOST('ref_supplier', 'nohtml');
  855. $object->socid = GETPOST('socid', 'int');
  856. $object->libelle = GETPOST('label', 'nohtml'); // deprecated
  857. $object->label = GETPOST('label', 'nohtml');
  858. $object->date = $dateinvoice;
  859. $object->date_echeance = $datedue;
  860. $object->note_public = GETPOST('note_public', 'restricthtml');
  861. $object->note_private = GETPOST('note_private', 'restricthtml');
  862. $object->cond_reglement_id = GETPOST('cond_reglement_id');
  863. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  864. $object->fk_account = GETPOST('fk_account', 'int');
  865. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  866. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  867. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  868. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  869. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  870. $object->transport_mode_id = GETPOST('transport_mode_id');
  871. // Auto calculation of date due if not filled by user
  872. if (empty($object->date_echeance)) {
  873. $object->date_echeance = $object->calculate_date_lim_reglement();
  874. }
  875. $object->fetch_thirdparty();
  876. // If creation from another object of another module
  877. if (!$error && GETPOST('origin', 'alpha') && GETPOST('originid')) {
  878. // Parse element/subelement (ex: project_task)
  879. $element = $subelement = GETPOST('origin', 'alpha');
  880. /*if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'),$regs))
  881. {
  882. $element = $regs[1];
  883. $subelement = $regs[2];
  884. }*/
  885. // For compatibility
  886. if ($element == 'order') {
  887. $element = $subelement = 'commande';
  888. }
  889. if ($element == 'propal') {
  890. $element = 'comm/propal'; $subelement = 'propal';
  891. }
  892. if ($element == 'contract') {
  893. $element = $subelement = 'contrat';
  894. }
  895. if ($element == 'order_supplier') {
  896. $element = 'fourn'; $subelement = 'fournisseur.commande';
  897. }
  898. if ($element == 'project') {
  899. $element = 'projet';
  900. }
  901. $object->origin = GETPOST('origin', 'alpha');
  902. $object->origin_id = GETPOST('originid', 'int');
  903. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  904. $classname = ucfirst($subelement);
  905. if ($classname == 'Fournisseur.commande') {
  906. $classname = 'CommandeFournisseur';
  907. }
  908. $objectsrc = new $classname($db);
  909. $objectsrc->fetch($originid);
  910. $objectsrc->fetch_thirdparty();
  911. if (!empty($object->origin) && !empty($object->origin_id)) {
  912. $object->linkedObjectsIds[$object->origin] = $object->origin_id;
  913. }
  914. // Add also link with order if object is reception
  915. if ($object->origin == 'reception') {
  916. $objectsrc->fetchObjectLinked();
  917. if (count($objectsrc->linkedObjectsIds['order_supplier']) > 0) {
  918. foreach ($objectsrc->linkedObjectsIds['order_supplier'] as $key => $value) {
  919. $object->linkedObjectsIds['order_supplier'] = $value;
  920. }
  921. }
  922. }
  923. $id = $object->create($user);
  924. // Add lines
  925. if ($id > 0) {
  926. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  927. $classname = ucfirst($subelement);
  928. if ($classname == 'Fournisseur.commande') {
  929. $classname = 'CommandeFournisseur';
  930. }
  931. $srcobject = new $classname($db);
  932. $result = $srcobject->fetch(GETPOST('originid', 'int'));
  933. // If deposit invoice - down payment with 1 line (fixed amount or percent)
  934. $typeamount = GETPOST('typedeposit', 'alpha');
  935. if (GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
  936. $valuedeposit = price2num(GETPOST('valuedeposit', 'alpha'), 'MU');
  937. // Define the array $amountdeposit
  938. $amountdeposit = array();
  939. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
  940. if ($typeamount == 'amount') {
  941. $amount = $valuedeposit;
  942. } else {
  943. $amount = $srcobject->total_ttc * ($valuedeposit / 100);
  944. }
  945. $TTotalByTva = array();
  946. foreach ($srcobject->lines as &$line) {
  947. if (!empty($line->special_code)) {
  948. continue;
  949. }
  950. $TTotalByTva[$line->tva_tx] += $line->total_ttc;
  951. }
  952. foreach ($TTotalByTva as $tva => &$total) {
  953. $coef = $total / $srcobject->total_ttc; // Calc coef
  954. $am = $amount * $coef;
  955. $amount_ttc_diff += $am;
  956. $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
  957. }
  958. } else {
  959. if ($typeamount == 'amount') {
  960. $amountdeposit[0] = $valuedeposit;
  961. } elseif ($typeamount == 'variable') {
  962. if ($result > 0) {
  963. $totalamount = 0;
  964. $lines = $srcobject->lines;
  965. $numlines = count($lines);
  966. for ($i = 0; $i < $numlines; $i++) {
  967. $qualified = 1;
  968. if (empty($lines[$i]->qty)) {
  969. $qualified = 0; // We discard qty=0, it is an option
  970. }
  971. if (!empty($lines[$i]->special_code)) {
  972. $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
  973. }
  974. if ($qualified) {
  975. $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
  976. $tva_tx = $lines[$i]->tva_tx;
  977. $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100;
  978. }
  979. }
  980. if ($totalamount == 0) {
  981. $amountdeposit[0] = 0;
  982. }
  983. } else {
  984. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  985. $error++;
  986. }
  987. }
  988. $amount_ttc_diff = $amountdeposit[0];
  989. }
  990. foreach ($amountdeposit as $tva => $amount) {
  991. if (empty($amount)) {
  992. continue;
  993. }
  994. $arraylist = array(
  995. 'amount' => 'FixAmount',
  996. 'variable' => 'VarAmount'
  997. );
  998. $descline = '(DEPOSIT)';
  999. //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
  1000. if ($typeamount == 'amount') {
  1001. $descline .= ' ('.price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')';
  1002. } elseif ($typeamount == 'variable') {
  1003. $descline .= ' ('.$valuedeposit.'%)';
  1004. }
  1005. $descline .= ' - '.$srcobject->ref;
  1006. $result = $object->addline(
  1007. $descline,
  1008. $amount, // subprice
  1009. $tva, // vat rate
  1010. 0, // localtax1_tx
  1011. 0, // localtax2_tx
  1012. 1, // quantity
  1013. (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
  1014. 0, // remise_percent
  1015. 0, // date_start
  1016. 0, // date_end
  1017. 0,
  1018. $lines[$i]->info_bits, // info_bits
  1019. 'HT',
  1020. 0, // product_type
  1021. 1,
  1022. 0,
  1023. 0,
  1024. null,
  1025. $object->origin,
  1026. 0,
  1027. '',
  1028. $lines[$i]->special_code,
  1029. 0,
  1030. 0
  1031. //,$langs->trans('Deposit') //Deprecated
  1032. );
  1033. }
  1034. $diff = $object->total_ttc - $amount_ttc_diff;
  1035. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
  1036. $object->fetch_lines();
  1037. $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
  1038. $object->updateline($object->lines[0]->id, $object->lines[0]->desc, $subprice_diff, $object->lines[0]->qty, $object->lines[0]->remise_percent, $object->lines[0]->date_start, $object->lines[0]->date_end, $object->lines[0]->tva_tx, 0, 0, 'HT', $object->lines[0]->info_bits, $object->lines[0]->product_type, 0, 0, 0, $object->lines[0]->pa_ht, $object->lines[0]->label, 0, array(), 100);
  1039. }
  1040. } elseif ($result > 0) {
  1041. $lines = $srcobject->lines;
  1042. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1043. $srcobject->fetch_lines();
  1044. $lines = $srcobject->lines;
  1045. }
  1046. $num = count($lines);
  1047. for ($i = 0; $i < $num; $i++) { // TODO handle subprice < 0
  1048. if (!in_array($lines[$i]->id, $selectedLines)) {
  1049. continue; // Skip unselected lines
  1050. }
  1051. $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle);
  1052. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  1053. // Extrafields
  1054. if (method_exists($lines[$i], 'fetch_optionals')) {
  1055. $lines[$i]->fetch_optionals();
  1056. }
  1057. // Dates
  1058. // TODO mutualiser
  1059. $date_start = $lines[$i]->date_debut_prevue;
  1060. if ($lines[$i]->date_debut_reel) {
  1061. $date_start = $lines[$i]->date_debut_reel;
  1062. }
  1063. if ($lines[$i]->date_start) {
  1064. $date_start = $lines[$i]->date_start;
  1065. }
  1066. $date_end = $lines[$i]->date_fin_prevue;
  1067. if ($lines[$i]->date_fin_reel) {
  1068. $date_end = $lines[$i]->date_fin_reel;
  1069. }
  1070. if ($lines[$i]->date_end) {
  1071. $date_end = $lines[$i]->date_end;
  1072. }
  1073. // FIXME Missing special_code into addline and updateline methods
  1074. $object->special_code = $lines[$i]->special_code;
  1075. // FIXME If currency different from main currency, take multicurrency price
  1076. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  1077. $pu = 0;
  1078. $pu_currency = $lines[$i]->multicurrency_subprice;
  1079. } else {
  1080. $pu = $lines[$i]->subprice;
  1081. $pu_currency = 0;
  1082. }
  1083. // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example.
  1084. $result = $object->addline(
  1085. $desc,
  1086. $pu,
  1087. $lines[$i]->tva_tx,
  1088. $lines[$i]->localtax1_tx,
  1089. $lines[$i]->localtax2_tx,
  1090. $lines[$i]->qty,
  1091. $lines[$i]->fk_product,
  1092. $lines[$i]->remise_percent,
  1093. $date_start,
  1094. $date_end,
  1095. 0,
  1096. $lines[$i]->info_bits,
  1097. 'HT',
  1098. $product_type,
  1099. $lines[$i]->rang,
  1100. 0,
  1101. $lines[$i]->array_options,
  1102. $lines[$i]->fk_unit,
  1103. $lines[$i]->id,
  1104. $pu_currency,
  1105. $lines[$i]->ref_supplier,
  1106. $lines[$i]->special_code
  1107. );
  1108. if ($result < 0) {
  1109. $error++;
  1110. break;
  1111. }
  1112. }
  1113. // Now reload line
  1114. $object->fetch_lines();
  1115. } else {
  1116. $error++;
  1117. }
  1118. } else {
  1119. $error++;
  1120. }
  1121. } elseif (!$error) {
  1122. $id = $object->create($user);
  1123. if ($id < 0) {
  1124. $error++;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. if ($error) {
  1130. $langs->load("errors");
  1131. $db->rollback();
  1132. setEventMessages($object->error, $object->errors, 'errors');
  1133. $action = 'create';
  1134. $_GET['socid'] = $_POST['socid'];
  1135. } else {
  1136. $db->commit();
  1137. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1138. $outputlangs = $langs;
  1139. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1140. if ($result < 0) {
  1141. dol_print_error($db, $object->error, $object->errors);
  1142. exit;
  1143. }
  1144. }
  1145. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  1146. exit;
  1147. }
  1148. } elseif ($action == 'updateline' && $usercancreate) {
  1149. // Edit line
  1150. $db->begin();
  1151. if (! $object->fetch($id) > 0) dol_print_error($db);
  1152. $object->fetch_thirdparty();
  1153. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  1154. if (GETPOST('price_ht') != '' || GETPOST('multicurrency_subprice') != '') {
  1155. $up = price2num(GETPOST('price_ht'), '', 2);
  1156. $price_base_type = 'HT';
  1157. } else {
  1158. $up = price2num(GETPOST('price_ttc'), '', 2);
  1159. $price_base_type = 'TTC';
  1160. }
  1161. if (GETPOST('productid') > 0) {
  1162. $productsupplier = new ProductFournisseur($db);
  1163. if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) {
  1164. if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty')), GETPOST('productid', 'int'), 'restricthtml', GETPOST('socid', 'int')) < 0) {
  1165. setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings');
  1166. }
  1167. }
  1168. $prod = new Product($db);
  1169. $prod->fetch(GETPOST('productid'));
  1170. $label = $prod->description;
  1171. if (trim(GETPOST('product_desc', 'restricthtml')) != trim($label)) {
  1172. $label = GETPOST('product_desc', 'restricthtml');
  1173. }
  1174. $type = $prod->type;
  1175. } else {
  1176. $label = GETPOST('product_desc', 'restricthtml');
  1177. $type = GETPOST("type") ? GETPOST("type") : 0;
  1178. }
  1179. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  1180. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  1181. // Define info_bits
  1182. $info_bits = 0;
  1183. if (preg_match('/\*/', $tva_tx)) {
  1184. $info_bits |= 0x01;
  1185. }
  1186. // Define vat_rate
  1187. $tva_tx = str_replace('*', '', $tva_tx);
  1188. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
  1189. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
  1190. $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1191. $pu_devise = price2num(GETPOST('multicurrency_subprice'), 'MU', 2);
  1192. // Extrafields Lines
  1193. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  1194. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  1195. // Unset extrafield POST Data
  1196. if (is_array($extralabelsline)) {
  1197. foreach ($extralabelsline as $key => $value) {
  1198. unset($_POST["options_".$key]);
  1199. }
  1200. }
  1201. $result = $object->updateline(GETPOST('lineid', 'int'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, price2num(GETPOST('qty'), 'MS'), GETPOST('productid', 'int'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, GETPOST('units'), $pu_devise, GETPOST('fourn_ref', 'alpha'));
  1202. if ($result >= 0) {
  1203. unset($_POST['label']);
  1204. unset($_POST['fourn_ref']);
  1205. unset($_POST['date_starthour']);
  1206. unset($_POST['date_startmin']);
  1207. unset($_POST['date_startsec']);
  1208. unset($_POST['date_startday']);
  1209. unset($_POST['date_startmonth']);
  1210. unset($_POST['date_startyear']);
  1211. unset($_POST['date_endhour']);
  1212. unset($_POST['date_endmin']);
  1213. unset($_POST['date_endsec']);
  1214. unset($_POST['date_endday']);
  1215. unset($_POST['date_endmonth']);
  1216. unset($_POST['date_endyear']);
  1217. unset($_POST['price_ttc']);
  1218. unset($_POST['price_ht']);
  1219. $db->commit();
  1220. } else {
  1221. $db->rollback();
  1222. setEventMessages($object->error, $object->errors, 'errors');
  1223. }
  1224. } elseif ($action == 'addline' && $usercancreate) {
  1225. // Add a product line
  1226. $db->begin();
  1227. $ret = $object->fetch($id);
  1228. if ($ret < 0) {
  1229. dol_print_error($db, $object->error);
  1230. exit;
  1231. }
  1232. $ret = $object->fetch_thirdparty();
  1233. $langs->load('errors');
  1234. $error = 0;
  1235. // Set if we used free entry or predefined product
  1236. $predef = '';
  1237. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  1238. $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
  1239. $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
  1240. $prod_entry_mode = GETPOST('prod_entry_mode');
  1241. if ($prod_entry_mode == 'free') {
  1242. $idprod = 0;
  1243. } else {
  1244. $idprod = GETPOST('idprod', 'int');
  1245. }
  1246. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); // Can be '1.2' or '1.2 (CODE)'
  1247. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  1248. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  1249. $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
  1250. $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
  1251. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
  1252. $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef, 'alpha'), '', 2) : 0);
  1253. if (empty($remise_percent)) {
  1254. $remise_percent = 0;
  1255. }
  1256. // Extrafields
  1257. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  1258. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  1259. // Unset extrafield
  1260. if (is_array($extralabelsline)) {
  1261. // Get extra fields
  1262. foreach ($extralabelsline as $key => $value) {
  1263. unset($_POST["options_".$key]);
  1264. }
  1265. }
  1266. if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) {
  1267. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1268. $error++;
  1269. }
  1270. if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) {
  1271. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  1272. $error++;
  1273. }
  1274. if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not ''
  1275. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors');
  1276. $error++;
  1277. }
  1278. if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) {
  1279. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  1280. $error++;
  1281. }
  1282. if (!GETPOST('qty', 'alpha')) { // 0 is NOT allowed for invoices
  1283. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1284. $error++;
  1285. }
  1286. if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') {
  1287. if ($combinations = GETPOST('combinations', 'array')) {
  1288. //Check if there is a product with the given combination
  1289. $prodcomb = new ProductCombination($db);
  1290. if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
  1291. $idprod = $res->fk_product_child;
  1292. } else {
  1293. setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
  1294. $error++;
  1295. }
  1296. }
  1297. }
  1298. if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
  1299. $productsupplier = new ProductFournisseur($db);
  1300. $idprod = 0;
  1301. if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') {
  1302. $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...)
  1303. }
  1304. $reg = array();
  1305. if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) {
  1306. $idprod = $reg[1];
  1307. $res = $productsupplier->fetch($idprod); // Load product from its id
  1308. // Call to init some price properties of $productsupplier
  1309. // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
  1310. if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) {
  1311. $fksoctosearch = 0;
  1312. $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
  1313. if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price
  1314. $productsupplier->ref_supplier = '';
  1315. }
  1316. } else {
  1317. $fksoctosearch = $object->thirdparty->id;
  1318. $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
  1319. }
  1320. } elseif (GETPOST('idprodfournprice', 'alpha') > 0) {
  1321. $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat.
  1322. //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist
  1323. $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch);
  1324. $res = $productsupplier->fetch($idprod);
  1325. }
  1326. if ($idprod > 0) {
  1327. $label = $productsupplier->label;
  1328. // Define output language
  1329. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  1330. $outputlangs = $langs;
  1331. $newlang = '';
  1332. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1333. $newlang = GETPOST('lang_id', 'aZ09');
  1334. }
  1335. if (empty($newlang)) {
  1336. $newlang = $object->thirdparty->default_lang;
  1337. }
  1338. if (!empty($newlang)) {
  1339. $outputlangs = new Translate("", $conf);
  1340. $outputlangs->setDefaultLang($newlang);
  1341. }
  1342. $desc = (!empty($productsupplier->multilangs[$outputlangs->defaultlang]["description"])) ? $productsupplier->multilangs[$outputlangs->defaultlang]["description"] : $productsupplier->description;
  1343. } else {
  1344. $desc = $productsupplier->description;
  1345. }
  1346. // if we use supplier description of the products
  1347. if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  1348. $desc = $productsupplier->desc_supplier;
  1349. }
  1350. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  1351. if (trim($product_desc) == trim($desc) && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  1352. $product_desc = '';
  1353. }
  1354. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  1355. $desc = $product_desc;
  1356. }
  1357. if (!empty($product_desc) && trim($product_desc) != trim($desc)) {
  1358. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  1359. }
  1360. $ref_supplier = $productsupplier->ref_supplier;
  1361. // Get vat rate
  1362. if (!GETPOSTISSET('tva_tx')) { // If vat rate not provided from the form (the form has the priority)
  1363. $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
  1364. $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
  1365. }
  1366. if (empty($tva_tx)) {
  1367. $tva_npr = 0;
  1368. }
  1369. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
  1370. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
  1371. $type = $productsupplier->type;
  1372. if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') {
  1373. $price_base_type = 'HT';
  1374. $pu = price2num($price_ht, 'MU');
  1375. $pu_devise = price2num($price_ht_devise, 'CU');
  1376. } elseif (GETPOST('price_ttc') != '' || GETPOST('price_ttc_devise') != '') {
  1377. $price_base_type = 'TTC';
  1378. $pu = price2num($price_ttc, 'MU');
  1379. $pu_devise = price2num($price_ttc_devise, 'CU');
  1380. } else {
  1381. $price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT');
  1382. if (empty($object->multicurrency_code) || ($productsupplier->fourn_multicurrency_code != $object->multicurrency_code)) { // If object is in a different currency and price not in this currency
  1383. $pu = $productsupplier->fourn_pu;
  1384. $pu_devise = 0;
  1385. } else {
  1386. $pu = $productsupplier->fourn_pu;
  1387. $pu_devise = $productsupplier->fourn_multicurrency_unitprice;
  1388. }
  1389. }
  1390. if (empty($pu)) {
  1391. $pu = 0; // If pu is '' or null, we force to have a numeric value
  1392. }
  1393. $result = $object->addline(
  1394. $desc,
  1395. $pu,
  1396. $tva_tx,
  1397. $localtax1_tx,
  1398. $localtax2_tx,
  1399. $qty,
  1400. $idprod,
  1401. $remise_percent,
  1402. $date_start,
  1403. $date_end,
  1404. 0,
  1405. $tva_npr,
  1406. $price_base_type,
  1407. $type,
  1408. min($rank, count($object->lines) + 1),
  1409. 0,
  1410. $array_options,
  1411. $productsupplier->fk_unit,
  1412. 0,
  1413. $pu_devise,
  1414. $ref_supplier,
  1415. ''
  1416. );
  1417. }
  1418. if ($idprod == -99 || $idprod == 0) {
  1419. // Product not selected
  1420. $error++;
  1421. $langs->load("errors");
  1422. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
  1423. }
  1424. if ($idprod == -1) {
  1425. // Quantity too low
  1426. $error++;
  1427. $langs->load("errors");
  1428. setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors');
  1429. }
  1430. } elseif (empty($error)) { // $price_ht is already set
  1431. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  1432. $tva_tx = str_replace('*', '', $tva_tx);
  1433. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1434. $desc = $product_desc;
  1435. $type = GETPOST('type');
  1436. $ref_supplier = GETPOST('fourn_ref', 'alpha');
  1437. $fk_unit = GETPOST('units', 'alpha');
  1438. if (!preg_match('/\((.*)\)/', $tva_tx)) {
  1439. $tva_tx = price2num($tva_tx); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
  1440. }
  1441. // Local Taxes
  1442. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
  1443. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
  1444. if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') {
  1445. $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings
  1446. } else {
  1447. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  1448. $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); // $pu_ht must be rounded according to settings
  1449. }
  1450. $price_base_type = 'HT';
  1451. $pu_devise = price2num($price_devise, 'CU');
  1452. $result = $object->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $date_start, $date_end, 0, $tva_npr, $price_base_type, $type, -1, 0, $array_options, $fk_unit, 0, $pu_devise, $ref_supplier);
  1453. }
  1454. //print "xx".$tva_tx; exit;
  1455. if (!$error && $result > 0) {
  1456. $db->commit();
  1457. // Define output language
  1458. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1459. $outputlangs = $langs;
  1460. $newlang = '';
  1461. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1462. $newlang = GETPOST('lang_id', 'aZ09');
  1463. }
  1464. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1465. $newlang = $object->thirdparty->default_lang;
  1466. }
  1467. if (!empty($newlang)) {
  1468. $outputlangs = new Translate("", $conf);
  1469. $outputlangs->setDefaultLang($newlang);
  1470. }
  1471. $model = $object->model_pdf;
  1472. $ret = $object->fetch($id); // Reload to get new records
  1473. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1474. if ($result < 0) {
  1475. dol_print_error($db, $result);
  1476. }
  1477. }
  1478. unset($_POST ['prod_entry_mode']);
  1479. unset($_POST['qty']);
  1480. unset($_POST['type']);
  1481. unset($_POST['remise_percent']);
  1482. unset($_POST['pu']);
  1483. unset($_POST['price_ht']);
  1484. unset($_POST['multicurrency_price_ht']);
  1485. unset($_POST['price_ttc']);
  1486. unset($_POST['fourn_ref']);
  1487. unset($_POST['tva_tx']);
  1488. unset($_POST['label']);
  1489. unset($localtax1_tx);
  1490. unset($localtax2_tx);
  1491. unset($_POST['np_marginRate']);
  1492. unset($_POST['np_markRate']);
  1493. unset($_POST['dp_desc']);
  1494. unset($_POST['idprodfournprice']);
  1495. unset($_POST['units']);
  1496. unset($_POST['date_starthour']);
  1497. unset($_POST['date_startmin']);
  1498. unset($_POST['date_startsec']);
  1499. unset($_POST['date_startday']);
  1500. unset($_POST['date_startmonth']);
  1501. unset($_POST['date_startyear']);
  1502. unset($_POST['date_endhour']);
  1503. unset($_POST['date_endmin']);
  1504. unset($_POST['date_endsec']);
  1505. unset($_POST['date_endday']);
  1506. unset($_POST['date_endmonth']);
  1507. unset($_POST['date_endyear']);
  1508. } else {
  1509. $db->rollback();
  1510. setEventMessages($object->error, $object->errors, 'errors');
  1511. }
  1512. $action = '';
  1513. } elseif ($action == 'classin' && $usercancreate) {
  1514. $object->fetch($id);
  1515. $result = $object->setProject($projectid);
  1516. } elseif ($action == 'confirm_edit' && $confirm == 'yes' && $usercancreate) {
  1517. // Set invoice to draft status
  1518. $object->fetch($id);
  1519. $totalpaye = $object->getSommePaiement();
  1520. $resteapayer = $object->total_ttc - $totalpaye;
  1521. // We check that lines of invoices are exported in accountancy
  1522. $ventilExportCompta = $object->getVentilExportCompta();
  1523. if (!$ventilExportCompta) {
  1524. // On verifie si aucun paiement n'a ete effectue
  1525. if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) {
  1526. $idwarehouse = GETPOST('idwarehouse');
  1527. $object->fetch_thirdparty();
  1528. $qualified_for_stock_change = 0;
  1529. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  1530. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  1531. } else {
  1532. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  1533. }
  1534. // Check parameters
  1535. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  1536. $langs->load("stocks");
  1537. if (!$idwarehouse || $idwarehouse == -1) {
  1538. $error++;
  1539. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  1540. $action = '';
  1541. }
  1542. }
  1543. $object->setDraft($user, $idwarehouse);
  1544. // Define output language
  1545. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1546. $outputlangs = $langs;
  1547. $newlang = '';
  1548. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1549. $newlang = GETPOST('lang_id', 'aZ09');
  1550. }
  1551. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1552. $newlang = $object->thirdparty->default_lang;
  1553. }
  1554. if (!empty($newlang)) {
  1555. $outputlangs = new Translate("", $conf);
  1556. $outputlangs->setDefaultLang($newlang);
  1557. }
  1558. $model = $object->model_pdf;
  1559. $ret = $object->fetch($id); // Reload to get new records
  1560. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1561. if ($result < 0) {
  1562. dol_print_error($db, $result);
  1563. }
  1564. }
  1565. $action = '';
  1566. }
  1567. }
  1568. } elseif ($action == 'reopen' && $usercancreate) {
  1569. // Set invoice to validated/unpaid status
  1570. $result = $object->fetch($id);
  1571. if ($object->statut == FactureFournisseur::STATUS_CLOSED
  1572. || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) {
  1573. $result = $object->setUnpaid($user);
  1574. if ($result > 0) {
  1575. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
  1576. exit;
  1577. } else {
  1578. setEventMessages($object->error, $object->errors, 'errors');
  1579. }
  1580. }
  1581. }
  1582. // Actions when printing a doc from card
  1583. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  1584. // Actions to send emails
  1585. $triggersendname = 'BILL_SUPPLIER_SENTBYMAIL';
  1586. $paramname = 'id';
  1587. $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
  1588. $trackid = 'sinv'.$object->id;
  1589. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  1590. // Actions to build doc
  1591. $upload_dir = $conf->fournisseur->facture->dir_output;
  1592. $permissiontoadd = $usercancreate;
  1593. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  1594. // Make calculation according to calculationrule
  1595. if ($action == 'calculate') {
  1596. $calculationrule = GETPOST('calculationrule');
  1597. $object->fetch($id);
  1598. $object->fetch_thirdparty();
  1599. $result = $object->update_price(0, (($calculationrule == 'totalofround') ? '0' : '1'), 0, $object->thirdparty);
  1600. if ($result <= 0) {
  1601. dol_print_error($db, $result);
  1602. exit;
  1603. }
  1604. }
  1605. if ($action == 'update_extras') {
  1606. $object->oldcopy = dol_clone($object);
  1607. // Fill array 'array_options' with data from add form
  1608. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  1609. if ($ret < 0) {
  1610. $error++;
  1611. }
  1612. if (!$error) {
  1613. // Actions on extra fields
  1614. if (!$error) {
  1615. $result = $object->insertExtraFields('BILL_SUPPLIER_MODIFY');
  1616. if ($result < 0) {
  1617. $error++;
  1618. }
  1619. }
  1620. }
  1621. if ($error) {
  1622. $action = 'edit_extras';
  1623. }
  1624. }
  1625. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
  1626. if ($action == 'addcontact') {
  1627. $result = $object->fetch($id);
  1628. if ($result > 0 && $id > 0) {
  1629. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  1630. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  1631. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  1632. }
  1633. if ($result >= 0) {
  1634. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1635. exit;
  1636. } else {
  1637. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1638. $langs->load("errors");
  1639. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  1640. } else {
  1641. setEventMessages($object->error, $object->errors, 'errors');
  1642. }
  1643. }
  1644. } elseif ($action == 'swapstatut') {
  1645. // bascule du statut d'un contact
  1646. if ($object->fetch($id)) {
  1647. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  1648. } else {
  1649. dol_print_error($db);
  1650. }
  1651. } elseif ($action == 'deletecontact') {
  1652. // Efface un contact
  1653. $object->fetch($id);
  1654. $result = $object->delete_contact(GETPOST("lineid", 'int'));
  1655. if ($result >= 0) {
  1656. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1657. exit;
  1658. } else {
  1659. dol_print_error($db);
  1660. }
  1661. }
  1662. }
  1663. }
  1664. /*
  1665. * View
  1666. */
  1667. $form = new Form($db);
  1668. $formfile = new FormFile($db);
  1669. $bankaccountstatic = new Account($db);
  1670. $paymentstatic = new PaiementFourn($db);
  1671. if (!empty($conf->projet->enabled)) {
  1672. $formproject = new FormProjets($db);
  1673. }
  1674. $now = dol_now();
  1675. $title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Card');
  1676. $help_url = 'EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores|DE:Modul_Lieferantenrechnungen';
  1677. llxHeader('', $title, $help_url);
  1678. // Mode creation
  1679. if ($action == 'create') {
  1680. $facturestatic = new FactureFournisseur($db);
  1681. print load_fiche_titre($langs->trans('NewBill'), '', 'supplier_invoice');
  1682. dol_htmloutput_events();
  1683. $currency_code = $conf->currency;
  1684. $societe = '';
  1685. if (GETPOST('socid', 'int') > 0) {
  1686. $societe = new Societe($db);
  1687. $societe->fetch(GETPOST('socid', 'int'));
  1688. if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) {
  1689. $currency_code = $societe->multicurrency_code;
  1690. }
  1691. }
  1692. if (!empty($origin) && !empty($originid)) {
  1693. // Parse element/subelement (ex: project_task)
  1694. $element = $subelement = $origin;
  1695. if ($element == 'project') {
  1696. $projectid = $originid;
  1697. $element = 'projet';
  1698. }
  1699. // For compatibility
  1700. if ($element == 'order') {
  1701. $element = $subelement = 'commande';
  1702. }
  1703. if ($element == 'propal') {
  1704. $element = 'comm/propal'; $subelement = 'propal';
  1705. }
  1706. if ($element == 'contract') {
  1707. $element = $subelement = 'contrat';
  1708. }
  1709. if ($element == 'order_supplier') {
  1710. $element = 'fourn'; $subelement = 'fournisseur.commande';
  1711. }
  1712. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  1713. $classname = ucfirst($subelement);
  1714. if ($classname == 'Fournisseur.commande') {
  1715. $classname = 'CommandeFournisseur';
  1716. }
  1717. $objectsrc = new $classname($db);
  1718. $objectsrc->fetch($originid);
  1719. $objectsrc->fetch_thirdparty();
  1720. $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
  1721. //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:'');
  1722. $soc = $objectsrc->thirdparty;
  1723. $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_supplier_id) ? $soc->cond_reglement_supplier_id : 0)); // TODO maybe add default value option
  1724. $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_supplier_id) ? $soc->mode_reglement_supplier_id : 0));
  1725. $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  1726. $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_supplier_percent) ? $soc->remise_supplier_percent : 0));
  1727. $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  1728. $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '';
  1729. $transport_mode_id = (!empty($objectsrc->transport_mode_id) ? $objectsrc->transport_mode_id : (!empty($soc->transport_mode_id) ? $soc->transport_mode_id : 0));
  1730. if (!empty($conf->multicurrency->enabled)) {
  1731. if (!empty($objectsrc->multicurrency_code)) {
  1732. $currency_code = $objectsrc->multicurrency_code;
  1733. }
  1734. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
  1735. $currency_tx = $objectsrc->multicurrency_tx;
  1736. }
  1737. }
  1738. $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  1739. $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp);
  1740. $datetmp = dol_mktime(12, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int'));
  1741. $datedue = ($datetmp == '' ?-1 : $datetmp);
  1742. // Replicate extrafields
  1743. $objectsrc->fetch_optionals();
  1744. $object->array_options = $objectsrc->array_options;
  1745. } else {
  1746. $cond_reglement_id = !empty($societe->cond_reglement_supplier_id) ? $societe->cond_reglement_supplier_id : 0;
  1747. $mode_reglement_id = !empty($societe->mode_reglement_supplier_id) ? $societe->mode_reglement_supplier_id : 0;
  1748. $transport_mode_id = !empty($societe->transport_mode_supplier_id) ? $societe->transport_mode_supplier_id : 0;
  1749. $fk_account = !empty($societe->fk_account) ? $societe->fk_account : 0;
  1750. $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  1751. $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp);
  1752. $datetmp = dol_mktime(12, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int'));
  1753. $datedue = ($datetmp == '' ?-1 : $datetmp);
  1754. if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) {
  1755. $currency_code = $soc->multicurrency_code;
  1756. }
  1757. }
  1758. // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
  1759. if (empty($cond_reglement_id)) {
  1760. $cond_reglement_id = GETPOST("cond_reglement_id");
  1761. }
  1762. // when payment mode is empty (means not override by payment condition form a other object, like third-party), try to use default value
  1763. if (empty($mode_reglement_id)) {
  1764. $mode_reglement_id = GETPOST("mode_reglement_id");
  1765. }
  1766. $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTUREFOURN_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null));
  1767. $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTUREFOURN_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null));
  1768. print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
  1769. print '<input type="hidden" name="token" value="'.newToken().'">';
  1770. print '<input type="hidden" name="action" value="add">';
  1771. if (!empty($societe->id) && $societe->id > 0) {
  1772. print '<input type="hidden" name="socid" value="'.$societe->id.'">'."\n";
  1773. }
  1774. print '<input type="hidden" name="origin" value="'.$origin.'">';
  1775. print '<input type="hidden" name="originid" value="'.$originid.'">';
  1776. if (!empty($currency_tx)) {
  1777. print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
  1778. }
  1779. print dol_get_fiche_head();
  1780. print '<table class="border centpercent">';
  1781. // Ref
  1782. print '<tr><td class="titlefieldcreate">'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
  1783. $exampletemplateinvoice = new FactureFournisseurRec($db);
  1784. $invoice_predefined = new FactureFournisseurRec($db);
  1785. if (empty($origin) && empty($originid) && $fac_recid > 0) {
  1786. $invoice_predefined->fetch($fac_recid);
  1787. }
  1788. // Third party
  1789. print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
  1790. print '<td>';
  1791. if (!empty($societe->id) && $societe->id > 0 && ($fac_recid <= 0 || !empty($invoice_predefined->frequency))) {
  1792. $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1);
  1793. print $societe->getNomUrl(1, 'supplier');
  1794. print '<input type="hidden" name="socid" value="'.$societe->id.'">';
  1795. } else {
  1796. print img_picto('', 'company').$form->select_company(!empty($societe->id) ? $societe->id : 0, 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  1797. // reload page to retrieve supplier informations
  1798. if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) {
  1799. print '<script type="text/javascript">
  1800. $(document).ready(function() {
  1801. $("#socid").change(function() {
  1802. var socid = $(this).val();
  1803. var fac_rec = $(\'#fac_rec\').val();
  1804. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  1805. });
  1806. });
  1807. </script>';
  1808. }
  1809. if ($fac_recid <= 0) {
  1810. print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=0&fournisseur=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
  1811. }
  1812. }
  1813. print '</td></tr>';
  1814. // Overwrite some values if creation of invoice is from a predefined invoice
  1815. if (empty($origin) && empty($originid) && $fac_recid > 0) {
  1816. $invoice_predefined->fetch($fac_recid);
  1817. $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
  1818. if (empty($projectid)) {
  1819. $projectid = $invoice_predefined->fk_project;
  1820. }
  1821. $cond_reglement_id = $invoice_predefined->cond_reglement_id;
  1822. $mode_reglement_id = $invoice_predefined->mode_reglement_id;
  1823. $fk_account = $invoice_predefined->fk_account;
  1824. $note_public = $invoice_predefined->note_public;
  1825. $note_private = $invoice_predefined->note_private;
  1826. if (!empty($invoice_predefined->multicurrency_code)) {
  1827. $currency_code = $invoice_predefined->multicurrency_code;
  1828. }
  1829. if (!empty($invoice_predefined->multicurrency_tx)) {
  1830. $currency_tx = $invoice_predefined->multicurrency_tx;
  1831. }
  1832. $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc';
  1833. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_rec as r';
  1834. $sql .= ' WHERE r.fk_soc = '. (int) $invoice_predefined->socid;
  1835. $resql = $db->query($sql);
  1836. if ($resql) {
  1837. $num = $db->num_rows($resql);
  1838. $i = 0;
  1839. if ($num > 0) {
  1840. print '<tr><td>'.$langs->trans('CreateFromRepeatableInvoice').'</td><td>';
  1841. //print '<input type="hidden" name="fac_rec" id="fac_rec" value="'.$fac_recid.'">';
  1842. print '<select class="flat" id="fac_rec" name="fac_rec">'; // We may want to change the template to use
  1843. print '<option value="0" selected></option>';
  1844. while ($i < $num) {
  1845. $objp = $db->fetch_object($resql);
  1846. print '<option value="'.$objp->rowid.'"';
  1847. if ($fac_recid == $objp->rowid) {
  1848. print ' selected';
  1849. $exampletemplateinvoice->fetch($fac_recid);
  1850. }
  1851. print '>'.$objp->title.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')</option>';
  1852. $i++;
  1853. }
  1854. print '</select>';
  1855. // Option to reload page to retrieve customer informations. Note, this clear other input
  1856. if (empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED)) {
  1857. print '<script type="text/javascript">
  1858. $(document).ready(function() {
  1859. $("#fac_rec").change(function() {
  1860. console.log("We have changed the template invoice - Reload page");
  1861. var fac_rec = $(this).val();
  1862. var socid = $(\'#socid\').val();
  1863. // 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.
  1864. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  1865. });
  1866. });
  1867. </script>';
  1868. }
  1869. print '</td></tr>';
  1870. }
  1871. $db->free($resql);
  1872. } else {
  1873. dol_print_error($db);
  1874. }
  1875. }
  1876. // Ref supplier
  1877. print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="ref_supplier" value="'.(GETPOSTISSET('ref_supplier') ? GETPOST('ref_supplier') : (!empty($objectsrc->ref_supplier) ? $objectsrc->ref_supplier : '')).'" type="text"';
  1878. if (!empty($societe->id) && $societe->id > 0) {
  1879. print ' autofocus';
  1880. }
  1881. print '></td>';
  1882. print '</tr>';
  1883. print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Type').'</td><td>';
  1884. print '<div class="tagtable">'."\n";
  1885. // Standard invoice
  1886. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1887. $tmp = '<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOST('type') == 0 ? ' checked' : '').'> ';
  1888. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
  1889. print $desc;
  1890. print '</div></div>';
  1891. if (empty($origin) || ($origin == 'order_supplier' && !empty($originid))) {
  1892. // Deposit - Down payment
  1893. if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) {
  1894. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1895. $tmp='<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
  1896. print '<script type="text/javascript">
  1897. jQuery(document).ready(function() {
  1898. jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
  1899. jQuery("#radio_standard").prop("checked", true);
  1900. });
  1901. jQuery("#typedeposit, #valuedeposit").click(function() {
  1902. jQuery("#radio_deposit").prop("checked", true);
  1903. });
  1904. jQuery("#typedeposit").change(function() {
  1905. console.log("We change type of down payment");
  1906. jQuery("#radio_deposit").prop("checked", true);
  1907. setRadioForTypeOfInvoice();
  1908. });
  1909. jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_template").change(function() {
  1910. setRadioForTypeOfInvoice();
  1911. });
  1912. function setRadioForTypeOfInvoice() {
  1913. console.log("Change radio");
  1914. if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
  1915. jQuery(".checkforselect").prop("disabled", true);
  1916. jQuery(".checkforselect").prop("checked", false);
  1917. } else {
  1918. jQuery(".checkforselect").prop("disabled", false);
  1919. jQuery(".checkforselect").prop("checked", true);
  1920. }
  1921. };
  1922. });
  1923. </script>';
  1924. $tmp = $tmp.'<label for="radio_deposit" >'.$langs->trans("InvoiceDeposit").'</label>';
  1925. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
  1926. print '<table class="nobordernopadding"><tr>';
  1927. print '<td>';
  1928. print $desc;
  1929. print '</td>';
  1930. if ($origin == 'order_supplier') {
  1931. print '<td class="nowrap" style="padding-left: 15px">';
  1932. $arraylist = array(
  1933. 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  1934. 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  1935. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  1936. );
  1937. print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit', 'aZ09'), 0, 0, 0, '', 1);
  1938. print '</td>';
  1939. print '<td class="nowrap" style="padding-left: 5px">';
  1940. print '<span class="opacitymedium paddingleft">'.$langs->trans("AmountOrPercent").'</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="' . GETPOST('valuedeposit', 'int') . '"/>';
  1941. print '</td>';
  1942. }
  1943. print '</tr></table>';
  1944. print '</div></div>';
  1945. }
  1946. }
  1947. /* Not yet supported for supplier
  1948. if ($societe->id > 0)
  1949. {
  1950. // Replacement
  1951. if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT))
  1952. {
  1953. // Type invoice
  1954. $facids = $facturestatic->list_replacable_supplier_invoices($societe->id);
  1955. if ($facids < 0) {
  1956. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  1957. exit();
  1958. }
  1959. $options = "";
  1960. foreach ($facids as $facparam)
  1961. {
  1962. $options .= '<option value="' . $facparam ['id'] . '"';
  1963. if ($facparam ['id'] == GETPOST('fac_replacement') {
  1964. $options .= ' selected';
  1965. }
  1966. $options .= '>' . $facparam ['ref'];
  1967. $options .= ' (' . $facturestatic->LibStatut(0, $facparam ['status']) . ')';
  1968. $options .= '</option>';
  1969. }
  1970. print '<!-- replacement line -->';
  1971. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1972. $tmp='<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
  1973. if (! $options) $tmp.=' disabled';
  1974. $tmp.='> ';
  1975. print '<script type="text/javascript">
  1976. jQuery(document).ready(function() {
  1977. jQuery("#fac_replacement").change(function() {
  1978. jQuery("#radio_replacement").prop("checked", true);
  1979. });
  1980. });
  1981. </script>';
  1982. $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' ';
  1983. $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
  1984. if (! $options)
  1985. $text .= ' disabled';
  1986. $text .= '>';
  1987. if ($options) {
  1988. $text .= '<option value="-1">&nbsp;</option>';
  1989. $text .= $options;
  1990. } else {
  1991. $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
  1992. }
  1993. $text .= '</select>';
  1994. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  1995. print $desc;
  1996. print '</div></div>';
  1997. }
  1998. }
  1999. else
  2000. {
  2001. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2002. $tmp='<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
  2003. $text = $tmp.$langs->trans("InvoiceReplacement") . ' ';
  2004. $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') ';
  2005. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  2006. print $desc;
  2007. print '</div></div>';
  2008. }
  2009. */
  2010. if (empty($origin)) {
  2011. if (!empty($societe->id) && $societe->id > 0) {
  2012. // Credit note
  2013. if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) {
  2014. // Show link for credit note
  2015. $facids = $facturestatic->list_qualified_avoir_supplier_invoices($societe->id);
  2016. if ($facids < 0) {
  2017. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  2018. exit;
  2019. }
  2020. $optionsav = "";
  2021. $newinvoice_static = new FactureFournisseur($db);
  2022. foreach ($facids as $key => $valarray) {
  2023. $newinvoice_static->id = $key;
  2024. $newinvoice_static->ref = $valarray ['ref'];
  2025. $newinvoice_static->statut = $valarray ['status'];
  2026. $newinvoice_static->type = $valarray ['type'];
  2027. $newinvoice_static->paye = $valarray ['paye'];
  2028. $optionsav .= '<option value="'.$key.'"';
  2029. if ($key == GETPOST('fac_avoir', 'int')) {
  2030. $optionsav .= ' selected';
  2031. }
  2032. $optionsav .= '>';
  2033. $optionsav .= $newinvoice_static->ref;
  2034. $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')';
  2035. $optionsav .= '</option>';
  2036. }
  2037. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2038. $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST('type') == 2 ? ' checked' : '');
  2039. if (!$optionsav) {
  2040. $tmp .= ' disabled';
  2041. }
  2042. $tmp .= '> ';
  2043. // Show credit note options only if we checked credit note
  2044. print '<script type="text/javascript">
  2045. jQuery(document).ready(function() {
  2046. if (! jQuery("#radio_creditnote").is(":checked"))
  2047. {
  2048. jQuery("#credit_note_options").hide();
  2049. }
  2050. jQuery("#radio_creditnote").click(function() {
  2051. jQuery("#credit_note_options").show();
  2052. });
  2053. jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
  2054. jQuery("#credit_note_options").hide();
  2055. });
  2056. });
  2057. </script>';
  2058. $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk").' ';
  2059. // $text.='<input type="text" value="">';
  2060. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  2061. if (!$optionsav) {
  2062. $text .= ' disabled';
  2063. }
  2064. $text .= '>';
  2065. if ($optionsav) {
  2066. $text .= '<option value="-1"></option>';
  2067. $text .= $optionsav;
  2068. } else {
  2069. $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
  2070. }
  2071. $text .= '</select>';
  2072. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  2073. print $desc;
  2074. print '<div id="credit_note_options" class="clearboth">';
  2075. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithPaymentRestAmount\').removeAttr(\'checked\'); }" '.(GETPOST('invoiceAvoirWithLines', 'int') > 0 ? 'checked' : '').' /> ';
  2076. print '<label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
  2077. print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithLines\').removeAttr(\'checked\'); }" '.(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '').' /> ';
  2078. print '<label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  2079. print '</div>';
  2080. print '</div></div>';
  2081. }
  2082. } else {
  2083. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2084. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
  2085. $text = $tmp.$langs->trans("InvoiceAvoir").' ';
  2086. $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").')</span> ';
  2087. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  2088. print $desc;
  2089. print '</div></div>'."\n";
  2090. }
  2091. }
  2092. print '</div>';
  2093. print '</td></tr>';
  2094. if (!empty($societe->id) && $societe->id > 0) {
  2095. // Discounts for third party
  2096. print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
  2097. $thirdparty = $societe;
  2098. $discount_type = 1;
  2099. $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$societe->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid'));
  2100. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  2101. print '</td></tr>';
  2102. }
  2103. // Label
  2104. print '<tr><td>'.$langs->trans('Label').'</td><td><input class="minwidth200" name="label" value="'.dol_escape_htmltag(GETPOST('label')).'" type="text"></td></tr>';
  2105. // Date invoice
  2106. print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td>';
  2107. print $form->selectDate($dateinvoice, '', '', '', '', "add", 1, 1);
  2108. print '</td></tr>';
  2109. // Due date
  2110. print '<tr><td>'.$langs->trans('DateMaxPayment').'</td><td>';
  2111. print $form->selectDate($datedue, 'ech', '', '', '', "add", 1, 1);
  2112. print '</td></tr>';
  2113. // Payment term
  2114. print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
  2115. $form->select_conditions_paiements(GETPOSTISSET('cond_reglement_id') ?GETPOST('cond_reglement_id', 'int') : $cond_reglement_id, 'cond_reglement_id');
  2116. print '</td></tr>';
  2117. // Payment mode
  2118. print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
  2119. print img_picto('', 'bank', 'class="pictofixedwidth"');
  2120. $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ?GETPOST('mode_reglement_id', 'int') : $mode_reglement_id, 'mode_reglement_id', 'DBIT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx');
  2121. print '</td></tr>';
  2122. // Bank Account
  2123. if (!empty($conf->banque->enabled)) {
  2124. print '<tr><td>'.$langs->trans('BankAccount').'</td><td>';
  2125. print img_picto('', 'bank_account', 'class="pictofixedwidth"').$form->select_comptes((GETPOSTISSET('fk_account') ?GETPOST('fk_account', 'alpha') : $fk_account), 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
  2126. print '</td></tr>';
  2127. }
  2128. // Project
  2129. if (!empty($conf->projet->enabled)) {
  2130. $formproject = new FormProjets($db);
  2131. $langs->load('projects');
  2132. print '<tr><td>'.$langs->trans('Project').'</td><td>';
  2133. print img_picto('', 'project', 'class="pictofixedwidth"').$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
  2134. print ' <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.(!empty($soc->id) ? $soc->id : 0).'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.(!empty($soc->id) ? $soc->id : 0).($fac_recid > 0 ? '&fac_rec='.$fac_recid : '')).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
  2135. print '</td></tr>';
  2136. }
  2137. // Incoterms
  2138. if (!empty($conf->incoterm->enabled)) {
  2139. print '<tr>';
  2140. print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms : '', 1).'</label></td>';
  2141. print '<td colspan="3" class="maxwidthonsmartphone">';
  2142. print $form->select_incoterms(GETPOSTISSET('incoterm_id') ? GETPOST('incoterm_id', 'alphanohtml') : (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), GETPOSTISSET('location_incoterms') ? GETPOST('location_incoterms', 'alphanohtml') : (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : ''));
  2143. print '</td></tr>';
  2144. }
  2145. // Multicurrency
  2146. if (!empty($conf->multicurrency->enabled)) {
  2147. print '<tr>';
  2148. print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
  2149. print '<td class="maxwidthonsmartphone">';
  2150. print $form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ?GETPOST('multicurrency_code', 'alpha') : $currency_code), 'multicurrency_code');
  2151. print '</td></tr>';
  2152. }
  2153. // Help of substitution key
  2154. $htmltext = '';
  2155. if ($fac_recid > 0) {
  2156. $dateexample = $newdateinvoice ? $newdateinvoice : $dateinvoice;
  2157. if (empty($dateexample)) {
  2158. $dateexample = dol_now();
  2159. }
  2160. $substitutionarray = array(
  2161. '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')',
  2162. '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')',
  2163. '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m').')',
  2164. '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%m').')',
  2165. '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m').')',
  2166. '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B').')',
  2167. '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')',
  2168. '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')',
  2169. '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')',
  2170. '__INVOICE_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')',
  2171. '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')'
  2172. );
  2173. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  2174. foreach ($substitutionarray as $key => $val) {
  2175. $htmltext .= $key.' = '.$langs->trans($val).'<br>';
  2176. }
  2177. $htmltext .= '</i>';
  2178. }
  2179. // Intracomm report
  2180. if (!empty($conf->intracommreport->enabled)) {
  2181. $langs->loadLangs(array("intracommreport"));
  2182. print '<tr><td>'.$langs->trans('IntracommReportTransportMode').'</td><td>';
  2183. $form->selectTransportMode(GETPOSTISSET('transport_mode_id') ? GETPOST('transport_mode_id') : $transport_mode_id, 'transport_mode_id');
  2184. print '</td></tr>';
  2185. }
  2186. if (empty($reshook)) {
  2187. print $object->showOptionals($extrafields, 'create');
  2188. }
  2189. // Public note
  2190. print '<tr><td>'.$langs->trans('NotePublic').'</td>';
  2191. print '<td>';
  2192. $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'restricthtml') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  2193. print $doleditor->Create(1);
  2194. print '</td>';
  2195. // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
  2196. print '</tr>';
  2197. // Private note
  2198. print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
  2199. print '<td>';
  2200. $doleditor = new DolEditor('note_private', (GETPOSTISSET('note_private') ?GETPOST('note_private', 'restricthtml') : $note_private), '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  2201. print $doleditor->Create(1);
  2202. print '</td>';
  2203. // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
  2204. print '</tr>';
  2205. if (!empty($objectsrc) && is_object($objectsrc)) {
  2206. print "\n<!-- ".$classname." info -->";
  2207. print "\n";
  2208. print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
  2209. print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
  2210. print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
  2211. print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  2212. print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  2213. $txt = $langs->trans($classname);
  2214. if ($classname == 'CommandeFournisseur') {
  2215. $langs->load('orders');
  2216. $txt = $langs->trans("SupplierOrder");
  2217. }
  2218. print '<tr><td>'.$txt.'</td><td>'.$objectsrc->getNomUrl(1);
  2219. // We check if Origin document (id and type is known) has already at least one invoice attached to it
  2220. $objectsrc->fetchObjectLinked($originid, $origin, '', 'invoice_supplier');
  2221. $invoice_supplier = $objectsrc->linkedObjects['invoice_supplier'];
  2222. // count function need a array as argument (Note: the array must implement Countable too)
  2223. if (is_array($invoice_supplier)) {
  2224. $cntinvoice = count($invoice_supplier);
  2225. if ($cntinvoice >= 1) {
  2226. setEventMessages('WarningBillExist', null, 'warnings');
  2227. echo ' ('.$langs->trans('LatestRelatedBill').end($invoice_supplier)->getNomUrl(1).')';
  2228. }
  2229. }
  2230. print '</td></tr>';
  2231. print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>';
  2232. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>";
  2233. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1
  2234. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>";
  2235. }
  2236. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2
  2237. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>";
  2238. }
  2239. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>";
  2240. if (!empty($conf->multicurrency->enabled)) {
  2241. print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
  2242. print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
  2243. print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
  2244. }
  2245. }
  2246. // Other options
  2247. $parameters = array();
  2248. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2249. print $hookmanager->resPrint;
  2250. print "</table>\n";
  2251. print dol_get_fiche_end();
  2252. print $form->buttonsSaveCancel("CreateDraft");
  2253. // Show origin lines
  2254. if (!empty($objectsrc) && is_object($objectsrc)) {
  2255. print '<br>';
  2256. $title = $langs->trans('ProductsAndServices');
  2257. print load_fiche_titre($title);
  2258. print '<div class="div-table-responsive-no-min">';
  2259. print '<table class="noborder centpercent">';
  2260. $objectsrc->printOriginLinesList('', $selectedLines);
  2261. print '</table>';
  2262. print '</div>';
  2263. }
  2264. print "</form>\n";
  2265. } else {
  2266. if ($id > 0 || !empty($ref)) {
  2267. //
  2268. // View or edit mode
  2269. //
  2270. $now = dol_now();
  2271. $productstatic = new Product($db);
  2272. $result = $object->fetch($id, $ref);
  2273. if ($result <= 0) {
  2274. $langs->load("errors");
  2275. print $langs->trans("ErrorRecordNotFound");
  2276. llxFooter();
  2277. $db->close();
  2278. exit;
  2279. }
  2280. $result = $object->fetch_thirdparty();
  2281. if ($result < 0) {
  2282. dol_print_error($db, $object->error, $object->errors);
  2283. exit;
  2284. }
  2285. $societe = $object->thirdparty;
  2286. $totalpaye = $object->getSommePaiement();
  2287. $totalcreditnotes = $object->getSumCreditNotesUsed();
  2288. $totaldeposits = $object->getSumDepositsUsed();
  2289. // print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
  2290. // selleruserrevenuestamp=".$selleruserevenustamp;
  2291. // We can also use bcadd to avoid pb with floating points
  2292. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  2293. // $resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2294. // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2295. $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
  2296. // Multicurrency
  2297. if (!empty($conf->multicurrency->enabled)) {
  2298. $multicurrency_totalpaye = $object->getSommePaiement(1);
  2299. $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
  2300. $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
  2301. $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaye - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
  2302. // Code to fix case of corrupted data
  2303. if ($resteapayer == 0 && $multicurrency_resteapayer != 0) {
  2304. $resteapayer = price2num($multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
  2305. }
  2306. }
  2307. if ($object->paye) {
  2308. $resteapayer = 0;
  2309. }
  2310. $resteapayeraffiche = $resteapayer;
  2311. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this
  2312. $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2313. $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2314. } else {
  2315. $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')";
  2316. $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')";
  2317. }
  2318. $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1);
  2319. $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1);
  2320. $absolute_discount = price2num($absolute_discount, 'MT');
  2321. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  2322. /*
  2323. * View card
  2324. */
  2325. $head = facturefourn_prepare_head($object);
  2326. $titre = $langs->trans('SupplierInvoice');
  2327. print dol_get_fiche_head($head, 'card', $titre, -1, 'supplier_invoice');
  2328. $formconfirm = '';
  2329. // Confirmation de la conversion de l'avoir en reduc
  2330. if ($action == 'converttoreduc') {
  2331. if ($object->type == FactureFournisseur::TYPE_STANDARD) {
  2332. $type_fac = 'ExcessPaid';
  2333. } elseif ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2334. $type_fac = 'CreditNote';
  2335. } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) {
  2336. $type_fac = 'Deposit';
  2337. }
  2338. $text = $langs->trans('ConfirmConvertToReducSupplier', strtolower($langs->transnoentities($type_fac)));
  2339. $text .= '<br>'.$langs->trans('ConfirmConvertToReducSupplier2');
  2340. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
  2341. }
  2342. // Clone confirmation
  2343. if ($action == 'clone') {
  2344. // Create an array for form
  2345. $formquestion = array(
  2346. array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier),
  2347. array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
  2348. );
  2349. // Ask confirmation to clone
  2350. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250);
  2351. }
  2352. // Confirmation of validation
  2353. if ($action == 'valid') {
  2354. // We check if number is temporary number
  2355. if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) {
  2356. // empty should not happened, but when it occurs, the test save life
  2357. $numref = $object->getNextNumRef($societe);
  2358. } else {
  2359. $numref = $object->ref;
  2360. }
  2361. if ($numref < 0) {
  2362. setEventMessages($object->error, $object->errors, 'errors');
  2363. $action = '';
  2364. } else {
  2365. $text = $langs->trans('ConfirmValidateBill', $numref);
  2366. /*if (! empty($conf->notification->enabled))
  2367. {
  2368. require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
  2369. $notify=new Notify($db);
  2370. $text.='<br>';
  2371. $text.=$notify->confirmMessage('BILL_SUPPLIER_VALIDATE',$object->socid, $object);
  2372. }*/
  2373. $formquestion = array();
  2374. $qualified_for_stock_change = 0;
  2375. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2376. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2377. } else {
  2378. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2379. }
  2380. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  2381. $langs->load("stocks");
  2382. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2383. $formproduct = new FormProduct($db);
  2384. $warehouse = new Entrepot($db);
  2385. $warehouse_array = $warehouse->list_array();
  2386. if (count($warehouse_array) == 1) {
  2387. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
  2388. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
  2389. } else {
  2390. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  2391. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  2392. }
  2393. $formquestion = array(
  2394. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  2395. );
  2396. }
  2397. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1);
  2398. }
  2399. }
  2400. // Confirmation edit (back to draft)
  2401. if ($action == 'edit') {
  2402. $formquestion = array();
  2403. $qualified_for_stock_change = 0;
  2404. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2405. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2406. } else {
  2407. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2408. }
  2409. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  2410. $langs->load("stocks");
  2411. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2412. $formproduct = new FormProduct($db);
  2413. $warehouse = new Entrepot($db);
  2414. $warehouse_array = $warehouse->list_array();
  2415. if (count($warehouse_array) == 1) {
  2416. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
  2417. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
  2418. } else {
  2419. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
  2420. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  2421. }
  2422. $formquestion = array(
  2423. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  2424. );
  2425. }
  2426. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1);
  2427. }
  2428. // Confirmation set paid
  2429. if ($action == 'paid' && ($resteapayer <= 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $resteapayer == $object->total_ttc))) {
  2430. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1);
  2431. }
  2432. if ($action == 'paid' && $resteapayer > 0 && (empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $resteapayer != $object->total_ttc)) {
  2433. $close = array();
  2434. // Code
  2435. $i = 0;
  2436. $close[$i]['code'] = 'discount_vat'; // escompte
  2437. $i++;
  2438. $close[$i]['code'] = 'badsupplier';
  2439. $i++;
  2440. $close[$i]['code'] = 'other';
  2441. $i++;
  2442. // Help
  2443. $i = 0;
  2444. $close[$i]['label'] = $langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
  2445. $i++;
  2446. $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadSupplierDesc");
  2447. $i++;
  2448. $close[$i]['label'] = $langs->trans("Other");
  2449. $i++;
  2450. // Text
  2451. $i = 0;
  2452. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
  2453. $i++;
  2454. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
  2455. $i++;
  2456. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
  2457. $i++;
  2458. // arrayreasons[code]=reason
  2459. foreach ($close as $key => $val) {
  2460. $arrayreasons[$close[$key]['code']] = $close[$key]['reason'];
  2461. }
  2462. // Create a form table
  2463. $formquestion = array('text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
  2464. // Incomplete payment. We ask if the reason is discount or other
  2465. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 310);
  2466. }
  2467. // Confirmation of the abandoned classification
  2468. if ($action == 'canceled') {
  2469. // Code
  2470. $close[1]['code'] = 'badsupplier';
  2471. $close[2]['code'] = 'abandon';
  2472. // Help
  2473. $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadSupplierDesc");
  2474. $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
  2475. // Text
  2476. $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadSupplier", $object->ref), $close[1]['label'], 1);
  2477. $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
  2478. // arrayreasons
  2479. $arrayreasons[$close[1]['code']] = $close[1]['reason'];
  2480. $arrayreasons[$close[2]['code']] = $close[2]['reason'];
  2481. // Create a form table
  2482. $formquestion = array('text' => $langs->trans("ConfirmCancelBillQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
  2483. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 250);
  2484. }
  2485. // Confirmation de la suppression de la facture fournisseur
  2486. if ($action == 'delete') {
  2487. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1);
  2488. }
  2489. if ($action == 'deletepayment') {
  2490. $payment_id = GETPOST('paiement_id');
  2491. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1);
  2492. }
  2493. // Confirmation to delete line
  2494. if ($action == 'ask_deleteline') {
  2495. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
  2496. }
  2497. if (!$formconfirm) {
  2498. $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid);
  2499. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2500. if (empty($reshook)) {
  2501. $formconfirm .= $hookmanager->resPrint;
  2502. } elseif ($reshook > 0) {
  2503. $formconfirm = $hookmanager->resPrint;
  2504. }
  2505. }
  2506. // Print form confirm
  2507. print $formconfirm;
  2508. // Supplier invoice card
  2509. $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  2510. $morehtmlref = '<div class="refidno">';
  2511. // Ref supplier
  2512. $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1);
  2513. $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1);
  2514. // Thirdparty
  2515. $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'supplier');
  2516. if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
  2517. $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
  2518. }
  2519. // Project
  2520. if (!empty($conf->projet->enabled)) {
  2521. $langs->load("projects");
  2522. $morehtmlref .= '<br>'.$langs->trans('Project').' ';
  2523. if ($usercancreate) {
  2524. if ($action != 'classify') {
  2525. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
  2526. }
  2527. if ($action == 'classify') {
  2528. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  2529. $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  2530. $morehtmlref .= '<input type="hidden" name="action" value="classin">';
  2531. $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
  2532. $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  2533. $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  2534. $morehtmlref .= '</form>';
  2535. } else {
  2536. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
  2537. }
  2538. } else {
  2539. if (!empty($object->fk_project)) {
  2540. $proj = new Project($db);
  2541. $proj->fetch($object->fk_project);
  2542. $morehtmlref .= ' : '.$proj->getNomUrl(1);
  2543. if ($proj->title) {
  2544. $morehtmlref .= ' - '.$proj->title;
  2545. }
  2546. } else {
  2547. $morehtmlref .= '';
  2548. }
  2549. }
  2550. }
  2551. $morehtmlref .= '</div>';
  2552. $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
  2553. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
  2554. print '<div class="fichecenter">';
  2555. print '<div class="fichehalfleft">';
  2556. print '<div class="underbanner clearboth"></div>';
  2557. print '<table class="border tableforfield" width="100%">';
  2558. // Type
  2559. print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>';
  2560. print '<span class="badgeneutral">';
  2561. print $object->getLibType();
  2562. print '</span>';
  2563. if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) {
  2564. $facreplaced = new FactureFournisseur($db);
  2565. $facreplaced->fetch($object->fk_facture_source);
  2566. print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')';
  2567. }
  2568. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2569. $facusing = new FactureFournisseur($db);
  2570. if ($object->fk_facture_source > 0) {
  2571. $facusing->fetch($object->fk_facture_source);
  2572. print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')';
  2573. } else {
  2574. print ' ('.$langs->transnoentities("CorrectedInvoiceNotFound").')';
  2575. }
  2576. }
  2577. $facidavoir = $object->getListIdAvoirFromInvoice();
  2578. if (count($facidavoir) > 0) {
  2579. $invoicecredits = array();
  2580. foreach ($facidavoir as $id) {
  2581. $facavoir = new FactureFournisseur($db);
  2582. $facavoir->fetch($id);
  2583. $invoicecredits[] = $facavoir->getNomUrl(1);
  2584. }
  2585. print ' ('.$langs->transnoentities("InvoiceHasAvoir") . (count($invoicecredits) ? ' ' : '') . implode(',', $invoicecredits) . ')';
  2586. }
  2587. if (isset($facidnext) && $facidnext > 0) {
  2588. $facthatreplace = new FactureFournisseur($db);
  2589. $facthatreplace->fetch($facidnext);
  2590. print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')';
  2591. }
  2592. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
  2593. $discount = new DiscountAbsolute($db);
  2594. $result = $discount->fetch(0, 0, $object->id);
  2595. if ($result > 0) {
  2596. print ' <span class="opacitymediumbycolor paddingleft">';
  2597. $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
  2598. $s = str_replace('{s1}', $object->getLibType(1), $s);
  2599. $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
  2600. print $s;
  2601. print '</span><br>';
  2602. }
  2603. }
  2604. if ($object->fk_fac_rec_source > 0) {
  2605. $tmptemplate = new FactureFournisseurRec($db);
  2606. $result = $tmptemplate->fetch($object->fk_fac_rec_source);
  2607. if ($result > 0) {
  2608. print ' <span class="opacitymediumbycolor paddingleft">';
  2609. $link = '<a href="'.DOL_URL_ROOT.'/fourn/facture/card-rec.php?facid='.$tmptemplate->id.'">'.dol_escape_htmltag($tmptemplate->titre).'</a>';
  2610. $s = $langs->transnoentities("GeneratedFromSupplierTemplate", $link);
  2611. print $s;
  2612. print '</span>';
  2613. }
  2614. }
  2615. print '</td></tr>';
  2616. // Relative and absolute discounts
  2617. print '<!-- Discounts --><tr><td>'.$langs->trans('Discounts');
  2618. print '</td><td>';
  2619. $thirdparty = $societe;
  2620. $discount_type = 1;
  2621. $backtopage = urlencode($_SERVER["PHP_SELF"].'?facid='.$object->id);
  2622. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  2623. print '</td></tr>';
  2624. // Label
  2625. print '<tr>';
  2626. print '<td>'.$form->editfieldkey("Label", 'label', $object->label, $object, $usercancreate).'</td>';
  2627. print '<td>'.$form->editfieldval("Label", 'label', $object->label, $object, $usercancreate).'</td>';
  2628. print '</tr>';
  2629. $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0);
  2630. $form_permission2 = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate;
  2631. // Date
  2632. print '<tr><td>';
  2633. print $form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker');
  2634. print '</td><td colspan="3">';
  2635. print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker');
  2636. print '</td>';
  2637. // Default terms of the settlement
  2638. $langs->load('bills');
  2639. print '<tr><td class="nowrap">';
  2640. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2641. print $langs->trans('PaymentConditions');
  2642. print '<td>';
  2643. if ($action != 'editconditions' && $form_permission) {
  2644. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
  2645. }
  2646. print '</tr></table>';
  2647. print '</td><td>';
  2648. if ($action == 'editconditions') {
  2649. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  2650. } else {
  2651. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none');
  2652. }
  2653. print "</td>";
  2654. print '</tr>';
  2655. // Due date
  2656. print '<tr><td>';
  2657. print $form->editfieldkey("DateMaxPayment", 'date_lim_reglement', $object->date_echeance, $object, $form_permission2, 'datepicker');
  2658. print '</td><td>';
  2659. print $form->editfieldval("DateMaxPayment", 'date_lim_reglement', $object->date_echeance, $object, $form_permission2, 'datepicker');
  2660. if ($action != 'editdate_lim_reglement' && $object->hasDelay()) {
  2661. print img_warning($langs->trans('Late'));
  2662. }
  2663. print '</td>';
  2664. // Mode of payment
  2665. $langs->load('bills');
  2666. print '<tr><td class="nowrap">';
  2667. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2668. print $langs->trans('PaymentMode');
  2669. print '</td>';
  2670. if ($action != 'editmode' && $form_permission2) {
  2671. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
  2672. }
  2673. print '</tr></table>';
  2674. print '</td><td>';
  2675. if ($action == 'editmode') {
  2676. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1);
  2677. } else {
  2678. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
  2679. }
  2680. print '</td></tr>';
  2681. // Multicurrency
  2682. if (!empty($conf->multicurrency->enabled)) {
  2683. // Multicurrency code
  2684. print '<tr>';
  2685. print '<td>';
  2686. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2687. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  2688. print '</td>';
  2689. if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) {
  2690. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
  2691. }
  2692. print '</tr></table>';
  2693. print '</td><td>';
  2694. if ($action == 'editmulticurrencycode') {
  2695. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code');
  2696. } else {
  2697. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none');
  2698. }
  2699. print '</td></tr>';
  2700. // Multicurrency rate
  2701. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  2702. print '<tr>';
  2703. print '<td>';
  2704. print '<table class="nobordernopadding centpercent"><tr><td>';
  2705. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  2706. print '</td>';
  2707. if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  2708. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
  2709. }
  2710. print '</tr></table>';
  2711. print '</td><td>';
  2712. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  2713. if ($action == 'actualizemulticurrencyrate') {
  2714. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  2715. }
  2716. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
  2717. } else {
  2718. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  2719. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  2720. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  2721. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  2722. print '</div>';
  2723. }
  2724. }
  2725. print '</td></tr>';
  2726. }
  2727. }
  2728. // Bank Account
  2729. if (!empty($conf->banque->enabled)) {
  2730. print '<tr><td class="nowrap">';
  2731. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2732. print $langs->trans('BankAccount');
  2733. print '<td>';
  2734. if ($action != 'editbankaccount' && $usercancreate) {
  2735. 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>';
  2736. }
  2737. print '</tr></table>';
  2738. print '</td><td>';
  2739. if ($action == 'editbankaccount') {
  2740. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  2741. } else {
  2742. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  2743. }
  2744. print "</td>";
  2745. print '</tr>';
  2746. }
  2747. // Incoterms
  2748. if (!empty($conf->incoterm->enabled)) {
  2749. print '<tr><td>';
  2750. print '<table width="100%" class="nobordernopadding"><tr><td>';
  2751. print $langs->trans('IncotermLabel');
  2752. print '<td><td class="right">';
  2753. if ($usercancreate) {
  2754. print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm&token='.newToken().'">'.img_edit().'</a>';
  2755. } else {
  2756. print '&nbsp;';
  2757. }
  2758. print '</td></tr></table>';
  2759. print '</td>';
  2760. print '<td>';
  2761. if ($action != 'editincoterm') {
  2762. print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
  2763. } else {
  2764. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
  2765. }
  2766. print '</td></tr>';
  2767. }
  2768. // Intracomm report
  2769. if (!empty($conf->intracommreport->enabled)) {
  2770. $langs->loadLangs(array("intracommreport"));
  2771. print '<tr><td>';
  2772. print '<table width="100%" class="nobordernopadding"><tr><td>';
  2773. print $langs->trans('IntracommReportTransportMode');
  2774. print '</td>';
  2775. if ($action != 'editmode' && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)) {
  2776. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&id='.$object->id.'">'.img_edit().'</a></td>';
  2777. }
  2778. print '</tr></table>';
  2779. print '</td>';
  2780. print '<td>';
  2781. if ($action == 'editmode') {
  2782. $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'transport_mode_id', 1, 1);
  2783. } else {
  2784. $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'none');
  2785. }
  2786. print '</td></tr>';
  2787. }
  2788. // Other attributes
  2789. $cols = 2;
  2790. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  2791. print '</table>';
  2792. print '</div>';
  2793. print '<div class="fichehalfright">';
  2794. print '<div class="underbanner clearboth"></div>';
  2795. print '<table class="border tableforfield centpercent">';
  2796. if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) {
  2797. // Multicurrency Amount HT
  2798. print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
  2799. print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2800. print '</tr>';
  2801. // Multicurrency Amount VAT
  2802. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
  2803. print '<td>'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2804. print '</tr>';
  2805. // Multicurrency Amount TTC
  2806. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
  2807. print '<td>'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2808. print '</tr>';
  2809. }
  2810. // Amount
  2811. print '<tr><td class="titlefield">'.$langs->trans('AmountHT').'</td><td>'.price($object->total_ht, 1, $langs, 0, -1, -1, $conf->currency).'</td></tr>';
  2812. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($object->total_tva, 1, $langs, 0, -1, -1, $conf->currency);
  2813. if (GETPOST('calculationrule')) {
  2814. $calculationrule = GETPOST('calculationrule', 'alpha');
  2815. } else {
  2816. $calculationrule = (empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND) ? 'totalofround' : 'roundoftotal');
  2817. }
  2818. if ($calculationrule == 'totalofround') {
  2819. $calculationrulenum = 1;
  2820. } else {
  2821. $calculationrulenum = 2;
  2822. }
  2823. // Show link for "recalculate"
  2824. if ($object->getVentilExportCompta() == 0) {
  2825. $s = '<span class="hideonsmartphone opacitymedium">'.$langs->trans("ReCalculate").' </span>';
  2826. $s .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=calculate&calculationrule=totalofround">'.$langs->trans("Mode1").'</a>';
  2827. $s .= ' / ';
  2828. $s .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=calculate&calculationrule=roundoftotal">'.$langs->trans("Mode2").'</a>';
  2829. print '<div class="inline-block">';
  2830. print ' &nbsp; &nbsp; &nbsp; &nbsp; ';
  2831. print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc", $calculationrulenum).'<br>'.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('', 'help'), '', 3, '', 0, 'recalculate');
  2832. print '</div>';
  2833. }
  2834. print '</td></tr>';
  2835. // Amount Local Taxes
  2836. //TODO: Place into a function to control showing by country or study better option
  2837. if ($societe->localtax1_assuj == "1") { //Localtax1
  2838. print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>';
  2839. print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>';
  2840. print '</tr>';
  2841. }
  2842. if ($societe->localtax2_assuj == "1") { //Localtax2
  2843. print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>';
  2844. print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>';
  2845. print '</tr>';
  2846. }
  2847. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="3">'.price($object->total_ttc, 1, $langs, 0, -1, -1, $conf->currency).'</td></tr>';
  2848. print '</table>';
  2849. // List of payments
  2850. $totalpaye = 0;
  2851. $sign = 1;
  2852. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2853. $sign = - 1;
  2854. }
  2855. $nbrows = 9; $nbcols = 3;
  2856. if (!empty($conf->projet->enabled)) {
  2857. $nbrows++;
  2858. }
  2859. if (!empty($conf->banque->enabled)) {
  2860. $nbrows++; $nbcols++;
  2861. }
  2862. if (!empty($conf->incoterm->enabled)) {
  2863. $nbrows++;
  2864. }
  2865. if (!empty($conf->multicurrency->enabled)) {
  2866. $nbrows += 5;
  2867. }
  2868. // Local taxes
  2869. if ($societe->localtax1_assuj == "1") {
  2870. $nbrows++;
  2871. }
  2872. if ($societe->localtax2_assuj == "1") {
  2873. $nbrows++;
  2874. }
  2875. $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
  2876. $sql .= ' c.id as paiement_type,';
  2877. $sql .= ' pf.amount,';
  2878. $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal';
  2879. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p';
  2880. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
  2881. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
  2882. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
  2883. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid';
  2884. $sql .= ' WHERE pf.fk_facturefourn = '.((int) $object->id);
  2885. $sql .= ' ORDER BY p.datep, p.tms';
  2886. $result = $db->query($sql);
  2887. if ($result) {
  2888. $num = $db->num_rows($result);
  2889. $i = 0;
  2890. print '<div class="div-table-responsive-no-min">';
  2891. print '<table class="noborder paymenttable" width="100%">';
  2892. print '<tr class="liste_titre">';
  2893. print '<td class="liste_titre">'.($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
  2894. print '<td>'.$langs->trans('Date').'</td>';
  2895. print '<td>'.$langs->trans('Type').'</td>';
  2896. if (!empty($conf->banque->enabled)) {
  2897. print '<td class="right">'.$langs->trans('BankAccount').'</td>';
  2898. }
  2899. print '<td class="right">'.$langs->trans('Amount').'</td>';
  2900. print '<td width="18">&nbsp;</td>';
  2901. print '</tr>';
  2902. if ($num > 0) {
  2903. while ($i < $num) {
  2904. $objp = $db->fetch_object($result);
  2905. $paymentstatic->id = $objp->rowid;
  2906. $paymentstatic->datepaye = $db->jdate($objp->dp);
  2907. $paymentstatic->ref = ($objp->ref ? $objp->ref : $objp->rowid);
  2908. $paymentstatic->num_payment = $objp->num_payment;
  2909. $paymentstatic->payment_code = $objp->payment_code;
  2910. print '<tr class="oddeven">';
  2911. print '<td>';
  2912. print $paymentstatic->getNomUrl(1);
  2913. print '</td>';
  2914. print '<td>'.dol_print_date($db->jdate($objp->dp), 'day').'</td>';
  2915. print '<td>';
  2916. print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_payment;
  2917. print '</td>';
  2918. if (!empty($conf->banque->enabled)) {
  2919. $bankaccountstatic->id = $objp->baid;
  2920. $bankaccountstatic->ref = $objp->baref;
  2921. $bankaccountstatic->label = $objp->baref;
  2922. $bankaccountstatic->number = $objp->banumber;
  2923. if (!empty($conf->accounting->enabled)) {
  2924. $bankaccountstatic->account_number = $objp->account_number;
  2925. $accountingjournal = new AccountingJournal($db);
  2926. $accountingjournal->fetch($objp->fk_accountancy_journal);
  2927. $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
  2928. }
  2929. print '<td class="right">';
  2930. if ($objp->baid > 0) {
  2931. print $bankaccountstatic->getNomUrl(1, 'transactions');
  2932. }
  2933. print '</td>';
  2934. }
  2935. print '<td class="right">'.price($sign * $objp->amount).'</td>';
  2936. print '<td class="center">';
  2937. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) {
  2938. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">';
  2939. print img_delete();
  2940. print '</a>';
  2941. }
  2942. print '</td>';
  2943. print '</tr>';
  2944. $totalpaye += $objp->amount;
  2945. $i++;
  2946. }
  2947. } else {
  2948. print '<tr class="oddeven"><td colspan="'.$nbcols.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td><td></td><td></td></tr>';
  2949. }
  2950. /*
  2951. if ($object->paye == 0)
  2952. {
  2953. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('AlreadyPaid').' :</td><td class="right">'.price($totalpaye).'</td><td></td></tr>';
  2954. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>';
  2955. $resteapayer = $object->total_ttc - $totalpaye;
  2956. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('RemainderToPay').' :</td>';
  2957. print '<td class="right'.($resteapayer?' amountremaintopay':'').'">'.price($resteapayer).'</td><td></td></tr>';
  2958. }
  2959. */
  2960. $db->free($result);
  2961. } else {
  2962. dol_print_error($db);
  2963. }
  2964. if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) {
  2965. // Total already paid
  2966. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2967. print '<span class="opacitymedium">';
  2968. if ($object->type != FactureFournisseur::TYPE_DEPOSIT) {
  2969. print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
  2970. } else {
  2971. print $langs->trans('AlreadyPaid');
  2972. }
  2973. print '</span>';
  2974. print '</td><td class="right"'.(($totalpaye > 0) ? ' class="amountalreadypaid"' : '').'>'.price($totalpaye).'</td><td>&nbsp;</td></tr>';
  2975. //$resteapayer = $object->total_ttc - $totalpaye;
  2976. $resteapayeraffiche = $resteapayer;
  2977. $cssforamountpaymentcomplete = 'amountpaymentcomplete';
  2978. // Loop on each credit note or deposit amount applied
  2979. $creditnoteamount = 0;
  2980. $depositamount = 0;
  2981. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  2982. $sql .= " re.description, re.fk_invoice_supplier_source";
  2983. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  2984. $sql .= " WHERE fk_invoice_supplier = ".((int) $object->id);
  2985. $resql = $db->query($sql);
  2986. if ($resql) {
  2987. $num = $db->num_rows($resql);
  2988. $i = 0;
  2989. $invoice = new FactureFournisseur($db);
  2990. while ($i < $num) {
  2991. $obj = $db->fetch_object($resql);
  2992. $invoice->fetch($obj->fk_invoice_supplier_source);
  2993. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2994. if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2995. print $langs->trans("CreditNote").' ';
  2996. }
  2997. if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
  2998. print $langs->trans("Deposit").' ';
  2999. }
  3000. print $invoice->getNomUrl(0);
  3001. print ' :</td>';
  3002. print '<td class="right">'.price($obj->amount_ttc).'</td>';
  3003. print '<td class="right">';
  3004. print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>';
  3005. print '</td></tr>';
  3006. $i++;
  3007. if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  3008. $creditnoteamount += $obj->amount_ttc;
  3009. }
  3010. if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
  3011. $depositamount += $obj->amount_ttc;
  3012. }
  3013. }
  3014. } else {
  3015. dol_print_error($db);
  3016. }
  3017. // Paye partiellement 'escompte'
  3018. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
  3019. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  3020. print '<span class="opacitymedium">';
  3021. print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), - 1);
  3022. print '</span>';
  3023. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
  3024. $resteapayeraffiche = 0;
  3025. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3026. }
  3027. // Paye partiellement ou Abandon 'badsupplier'
  3028. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'badsupplier') {
  3029. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  3030. print '<span class="opacitymedium">';
  3031. print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), - 1);
  3032. print '</span>';
  3033. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
  3034. // $resteapayeraffiche=0;
  3035. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3036. }
  3037. // Paye partiellement ou Abandon 'product_returned'
  3038. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
  3039. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  3040. print '<span class="opacitymedium">';
  3041. print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), - 1);
  3042. print '</span>';
  3043. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
  3044. $resteapayeraffiche = 0;
  3045. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3046. }
  3047. // Paye partiellement ou Abandon 'abandon'
  3048. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') {
  3049. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  3050. $text = $langs->trans("HelpAbandonOther");
  3051. if ($object->close_note) {
  3052. $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
  3053. }
  3054. print '<span class="opacitymedium">';
  3055. print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1);
  3056. print '</span>';
  3057. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
  3058. $resteapayeraffiche = 0;
  3059. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3060. }
  3061. // Billed
  3062. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3063. print '<span class="opacitymedium">';
  3064. print $langs->trans("Billed");
  3065. print '</span>';
  3066. print '</td><td class="right">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
  3067. // Remainder to pay
  3068. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3069. print '<span class="opacitymedium">';
  3070. print $langs->trans('RemainderToPay');
  3071. if ($resteapayeraffiche < 0) {
  3072. print ' ('.$langs->trans('NegativeIfExcessPaid').')';
  3073. }
  3074. print '</span>';
  3075. print '</td>';
  3076. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td><td>&nbsp;</td></tr>';
  3077. // Remainder to pay Multicurrency
  3078. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  3079. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3080. print '<span class="opacitymedium">';
  3081. print $langs->trans('RemainderToPayMulticurrency');
  3082. if ($resteapayeraffiche < 0) {
  3083. print ' ('.$langs->trans('NegativeIfExcessPaid').')';
  3084. }
  3085. print '</span>';
  3086. print '</td>';
  3087. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.(!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency).' '.price(price2num($object->multicurrency_tx*$resteapayeraffiche, 'MT')).'</td><td>&nbsp;</td></tr>';
  3088. }
  3089. } else // Credit note
  3090. {
  3091. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  3092. // Total already paid back
  3093. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3094. print $langs->trans('AlreadyPaidBack');
  3095. print ' :</td><td class="right">'.price($sign * $totalpaye).'</td><td>&nbsp;</td></tr>';
  3096. // Billed
  3097. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($sign * $object->total_ttc).'</td><td>&nbsp;</td></tr>';
  3098. // Remainder to pay back
  3099. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3100. print '<span class="opacitymedium">';
  3101. print $langs->trans('RemainderToPayBack');
  3102. if ($resteapayeraffiche > 0) {
  3103. print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
  3104. }
  3105. print '</td>';
  3106. print '</span>';
  3107. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche).'</td><td>&nbsp;</td></tr>';
  3108. // Remainder to pay back Multicurrency
  3109. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  3110. print '<tr><td colspan="'.$nbcols.'" class="right">';
  3111. print '<span class="opacitymedium">';
  3112. print $langs->trans('RemainderToPayBackMulticurrency');
  3113. if ($resteapayeraffiche> 0) {
  3114. print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
  3115. }
  3116. print '</span>';
  3117. print '</td>';
  3118. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.(!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency).' '.price(price2num($sign * $object->multicurrency_tx * $resteapayeraffiche, 'MT')).'</td><td>&nbsp;</td></tr>';
  3119. }
  3120. // Sold credit note
  3121. // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
  3122. // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
  3123. // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
  3124. }
  3125. print '</table>';
  3126. print '</div>';
  3127. print '</div>';
  3128. print '</div>';
  3129. print '<div class="clearboth"></div><br>';
  3130. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  3131. $blocname = 'contacts';
  3132. $title = $langs->trans('ContactsAddresses');
  3133. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  3134. }
  3135. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  3136. $colwidth = 20;
  3137. $blocname = 'notes';
  3138. $title = $langs->trans('Notes');
  3139. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  3140. }
  3141. /*
  3142. * Lines
  3143. */
  3144. print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">';
  3145. print '<input type="hidden" name="token" value="'.newToken().'">';
  3146. print '<input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">';
  3147. print '<input type="hidden" name="mode" value="">';
  3148. print '<input type="hidden" name="page_y" value="">';
  3149. print '<input type="hidden" name="id" value="'.$object->id.'">';
  3150. print '<input type="hidden" name="socid" value="'.$societe->id.'">';
  3151. if (!empty($conf->use_javascript_ajax) && $object->statut == FactureFournisseur::STATUS_DRAFT) {
  3152. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  3153. }
  3154. print '<div class="div-table-responsive-no-min">';
  3155. print '<table id="tablelines" class="noborder noshadow centpercent">';
  3156. global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax;
  3157. $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1;
  3158. $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum.
  3159. //if (! empty($conf->global->SUPPLIER_INVOICE_WITH_NOPRICEDEFINED)) $senderissupplier=2;
  3160. if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) {
  3161. $senderissupplier = 1;
  3162. }
  3163. // Show object lines
  3164. if (!empty($object->lines)) {
  3165. $ret = $object->printObjectLines($action, $societe, $mysoc, $lineid, 1);
  3166. }
  3167. $num = count($object->lines);
  3168. // Form to add new line
  3169. if ($object->statut == FactureFournisseur::STATUS_DRAFT && $usercancreate) {
  3170. if ($action != 'editline') {
  3171. // Add free products/services
  3172. $parameters = array();
  3173. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  3174. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  3175. if (empty($reshook))
  3176. $object->formAddObjectLine(1, $societe, $mysoc);
  3177. }
  3178. }
  3179. print '</table>';
  3180. print '</div>';
  3181. print '</form>';
  3182. print dol_get_fiche_end();
  3183. if ($action != 'presend') {
  3184. /*
  3185. * Buttons actions
  3186. */
  3187. print '<div class="tabsAction">';
  3188. $parameters = array();
  3189. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
  3190. // modified by hook
  3191. if (empty($reshook)) {
  3192. // Modify a validated invoice with no payments
  3193. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) {
  3194. // We check if lines of invoice are not already transfered into accountancy
  3195. $ventilExportCompta = $object->getVentilExportCompta(); // Should be 0 since the sum of payments are zero. But we keep the protection.
  3196. if ($ventilExportCompta == 0) {
  3197. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=edit&token='.newToken().'">'.$langs->trans('Modify').'</a>';
  3198. } else {
  3199. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Modify').'</span>';
  3200. }
  3201. }
  3202. $discount = new DiscountAbsolute($db);
  3203. $result = $discount->fetch(0, 0, $object->id);
  3204. // Reopen a standard paid invoice
  3205. if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT
  3206. || ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && empty($discount->id))
  3207. || ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discount->id)))
  3208. && ($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED)) { // A paid invoice (partially or completely)
  3209. if (!$facidnext && $object->close_code != 'replaced' && $usercancreate) { // Not replaced by another invoice
  3210. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen&token='.newToken().'">'.$langs->trans('ReOpen').'</a>';
  3211. } else {
  3212. if ($usercancreate) {
  3213. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span>';
  3214. } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
  3215. print '<span class="butActionRefused classfortooltip">'.$langs->trans('ReOpen').'</span>';
  3216. }
  3217. }
  3218. }
  3219. // Validate
  3220. if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) {
  3221. if (count($object->lines)) {
  3222. if ($usercanvalidate) {
  3223. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid"';
  3224. print '>'.$langs->trans('Validate').'</a>';
  3225. } else {
  3226. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
  3227. print '>'.$langs->trans('Validate').'</a>';
  3228. }
  3229. }
  3230. }
  3231. // Send by mail
  3232. if (empty($user->socid)) {
  3233. if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) {
  3234. if ($usercansend) {
  3235. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>';
  3236. } else {
  3237. print '<span class="butActionRefused classfortooltip">'.$langs->trans('SendMail').'</span>';
  3238. }
  3239. }
  3240. }
  3241. // Create payment
  3242. if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) {
  3243. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.DOL_URL_ROOT.'/fourn/facture/paiement.php?facid='.$object->id.'&amp;action=create'.($object->fk_account > 0 ? '&amp;accountid='.$object->fk_account : '').'">'.$langs->trans('DoPayment').'</a>'; // must use facid because id is for payment id not invoice
  3244. }
  3245. // Reverse back money or convert to reduction
  3246. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) {
  3247. // For credit note only
  3248. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) {
  3249. if ($resteapayer == 0) {
  3250. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span>';
  3251. } else {
  3252. print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a>';
  3253. }
  3254. }
  3255. // For standard invoice with excess paid
  3256. if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $usercancreate && empty($discount->id)) {
  3257. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertExcessPaidToReduc').'</a>';
  3258. }
  3259. // For credit note
  3260. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercancreate
  3261. && (!empty($conf->global->SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $object->getSommePaiement() == 0)
  3262. ) {
  3263. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReducSupplier2")).'">'.$langs->trans('ConvertToReduc').'</a>';
  3264. }
  3265. // For deposit invoice
  3266. if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $usercancreate && $object->statut > 0 && empty($discount->id)) {
  3267. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a>';
  3268. }
  3269. }
  3270. // Classify paid
  3271. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && (
  3272. ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT && ($resteapayer <= 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $object->total_ttc == $resteapayer))) ||
  3273. ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $resteapayer >= 0) ||
  3274. ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->total_ttc > 0 && ($resteapayer == 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $object->total_ttc == $resteapayer)))
  3275. )
  3276. ) {
  3277. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a>';
  3278. }
  3279. // Classify 'closed not completely paid' (possible if validated and not yet filed paid)
  3280. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && (empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $object->total_ttc != $resteapayer)) {
  3281. if ($totalpaye > 0 || $totalcreditnotes > 0) {
  3282. // If one payment or one credit note was linked to this invoice
  3283. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaidPartially').'</a>';
  3284. } else {
  3285. if (empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED)) {
  3286. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=canceled">'.$langs->trans('ClassifyCanceled').'</a>';
  3287. }
  3288. }
  3289. }
  3290. // Create event
  3291. /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
  3292. {
  3293. print '<div class="inline-block divButAction"><a class="butAction" href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '">' . $langs->trans("AddAction") . '</a></div>';
  3294. }*/
  3295. // Create a credit note
  3296. if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $usercancreate) {
  3297. if (!$objectidnext) {
  3298. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&amp;action=create&amp;type=2'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').'">'.$langs->trans("CreateCreditNote").'</a>';
  3299. }
  3300. }
  3301. // Clone
  3302. if ($action != 'edit' && $usercancreate) {
  3303. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=clone&amp;socid='.$object->socid.'">'.$langs->trans('ToClone').'</a>';
  3304. }
  3305. // Clone as predefined / Create template
  3306. if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut == 0 && $usercancreate) {
  3307. if (!$objectidnext && count($object->lines) > 0) {
  3308. print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card-rec.php?facid='.$object->id.'&amp;action=create">'.$langs->trans("ChangeIntoRepeatableInvoice").'</a>';
  3309. }
  3310. }
  3311. // Delete
  3312. $isErasable = $object->is_erasable();
  3313. if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($usercancreate && $isErasable == 1))) { // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions)
  3314. //var_dump($isErasable);
  3315. if ($isErasable == -4) {
  3316. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a>';
  3317. } elseif ($isErasable == -3) { // Should never happen with supplier invoice
  3318. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastSituationInvoice").'">'.$langs->trans('Delete').'</a>';
  3319. } elseif ($isErasable == -2) { // Should never happen with supplier invoice
  3320. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInvoice").'">'.$langs->trans('Delete').'</a>';
  3321. } elseif ($isErasable == -1) {
  3322. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Delete').'</a>';
  3323. } elseif ($isErasable <= 0) { // Any other cases
  3324. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a>';
  3325. } else {
  3326. print '<a class="butActionDelete'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>';
  3327. }
  3328. }
  3329. print '</div>';
  3330. if ($action != 'confirm_edit') {
  3331. print '<div class="fichecenter"><div class="fichehalfleft">';
  3332. /*
  3333. * Generated documents
  3334. */
  3335. $ref = dol_sanitizeFileName($object->ref);
  3336. $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref;
  3337. $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir;
  3338. $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id;
  3339. $genallowed = $usercanread;
  3340. $delallowed = $usercancreate;
  3341. $modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->INVOICE_SUPPLIER_ADDON_PDF));
  3342. print $formfile->showdocuments('facture_fournisseur', $subdir, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang);
  3343. $somethingshown = $formfile->numoffiles;
  3344. // Show links to link elements
  3345. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier'));
  3346. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  3347. print '</div><div class="fichehalfright">';
  3348. // List of actions on element
  3349. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  3350. $formactions = new FormActions($db);
  3351. $somethingshown = $formactions->showactions($object, 'invoice_supplier', $socid, 1, 'listaction'.($genallowed ? 'largetitle' : ''));
  3352. print '</div></div>';
  3353. }
  3354. }
  3355. }
  3356. // Select mail models is same action as presend
  3357. if (GETPOST('modelselected')) {
  3358. $action = 'presend';
  3359. }
  3360. // Presend form
  3361. $modelmail = 'invoice_supplier_send';
  3362. $defaulttopic = 'SendBillRef';
  3363. $diroutput = $conf->fournisseur->facture->dir_output;
  3364. $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
  3365. $trackid = 'sinv'.$object->id;
  3366. include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
  3367. }
  3368. }
  3369. // End of page
  3370. llxFooter();
  3371. $db->close();