card.php 165 KB

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