facture.php 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264
  1. <?php
  2. /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  4. * Copyright (C) 2004-2016 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  6. * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@capnetworks.com>
  7. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  8. * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
  9. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  10. * Copyright (C) 2012-2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  11. * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  12. * Copyright (C) 2013 Jean-Francois FERRY <jfefe@aternatik.fr>
  13. * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
  14. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  15. * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
  16. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. */
  31. /**
  32. * \file htdocs/compta/facture.php
  33. * \ingroup facture
  34. * \brief Page to create/see an invoice
  35. */
  36. require '../main.inc.php';
  37. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  38. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php';
  39. require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  40. require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
  41. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  42. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
  43. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
  44. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
  45. require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
  46. require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
  47. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  48. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  49. if (! empty($conf->commande->enabled))
  50. require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
  51. if (! empty($conf->projet->enabled)) {
  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. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  56. $langs->load('bills');
  57. $langs->load('companies');
  58. $langs->load('compta');
  59. $langs->load('products');
  60. $langs->load('banks');
  61. $langs->load('main');
  62. if (!empty($conf->incoterm->enabled)) $langs->load('incoterm');
  63. if (! empty($conf->margin->enabled))
  64. $langs->load('margins');
  65. $sall = trim(GETPOST('sall'));
  66. $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0);
  67. $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
  68. $ref = GETPOST('ref', 'alpha');
  69. $socid = GETPOST('socid', 'int');
  70. $action = GETPOST('action', 'alpha');
  71. $confirm = GETPOST('confirm', 'alpha');
  72. $cancel = GETPOST('cancel', 'alpha');
  73. $lineid = GETPOST('lineid', 'int');
  74. $userid = GETPOST('userid', 'int');
  75. $search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
  76. $search_societe = GETPOST('search_societe', 'alpha');
  77. $search_montant_ht = GETPOST('search_montant_ht', 'alpha');
  78. $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
  79. $origin = GETPOST('origin', 'alpha');
  80. $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
  81. $fac_rec=GETPOST('fac_rec','int');
  82. // PDF
  83. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  84. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  85. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  86. // Security check
  87. $fieldid = (! empty($ref) ? 'facnumber' : 'rowid');
  88. if ($user->societe_id) $socid = $user->societe_id;
  89. $result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid);
  90. // Nombre de ligne pour choix de produit/service predefinis
  91. $NBLINES = 4;
  92. $usehm = (! empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
  93. $object = new Facture($db);
  94. $extrafields = new ExtraFields($db);
  95. // Load object
  96. if ($id > 0 || ! empty($ref)) {
  97. $ret = $object->fetch($id, $ref, '', '', $conf->global->INVOICE_USE_SITUATION);
  98. }
  99. // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
  100. $hookmanager->initHooks(array('invoicecard','globalcard'));
  101. $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php
  102. $permissiondellink=$user->rights->facture->creer; // Used by the include of actions_dellink.inc.php
  103. $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php
  104. /*
  105. * Actions
  106. */
  107. $parameters = array('socid' => $socid);
  108. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  109. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  110. if (empty($reshook))
  111. {
  112. if ($cancel) $action='';
  113. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  114. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  115. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  116. // Link invoice to order
  117. if (GETPOST('linkedOrder') && empty($cancel) && $id > 0)
  118. {
  119. $object->fetch($id);
  120. $object->fetch_thirdparty();
  121. $result = $object->add_object_linked('commande', GETPOST('linkedOrder'));
  122. }
  123. // Action clone object
  124. if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->facture->creer) {
  125. // if (1 == 0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) {
  126. // $mesgs [] = '<div class="error">' . $langs->trans("NoCloneOptionsSpecified") . '</div>';
  127. // } else {
  128. if ($object->fetch($id) > 0) {
  129. $result = $object->createFromClone($socid);
  130. if ($result > 0) {
  131. header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $result);
  132. exit();
  133. } else {
  134. setEventMessages($object->error, $object->errors, 'errors');
  135. $action = '';
  136. }
  137. }
  138. // }
  139. }
  140. // Change status of invoice
  141. else if ($action == 'reopen' && $user->rights->facture->creer) {
  142. $result = $object->fetch($id);
  143. if ($object->statut == 2 || ($object->statut == 3 && $object->close_code != 'replaced') || ($object->statut == 1 && $object->paye == 1)) { // ($object->statut == 1 && $object->paye == 1) should not happened but can be found when data are corrupted
  144. $result = $object->set_unpaid($user);
  145. if ($result > 0) {
  146. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  147. exit();
  148. } else {
  149. setEventMessages($object->error, $object->errors, 'errors');
  150. }
  151. }
  152. }
  153. // Delete invoice
  154. else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->facture->supprimer) {
  155. $result = $object->fetch($id);
  156. $object->fetch_thirdparty();
  157. $idwarehouse = GETPOST('idwarehouse');
  158. $qualified_for_stock_change = 0;
  159. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  160. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  161. } else {
  162. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  163. }
  164. $result = $object->delete(0, 0, $idwarehouse);
  165. if ($result > 0) {
  166. header('Location: ' . DOL_URL_ROOT . '/compta/facture/list.php');
  167. exit();
  168. } else {
  169. setEventMessages($object->error, $object->errors, 'errors');
  170. $action='';
  171. }
  172. }
  173. // Delete line
  174. else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer)
  175. {
  176. $object->fetch($id);
  177. $object->fetch_thirdparty();
  178. $result = $object->deleteline(GETPOST('lineid'));
  179. if ($result > 0) {
  180. // Define output language
  181. $outputlangs = $langs;
  182. $newlang = '';
  183. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id']))
  184. $newlang = $_REQUEST['lang_id'];
  185. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  186. $newlang = $object->thirdparty->default_lang;
  187. if (! empty($newlang)) {
  188. $outputlangs = new Translate("", $conf);
  189. $outputlangs->setDefaultLang($newlang);
  190. }
  191. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  192. $ret = $object->fetch($id); // Reload to get new records
  193. $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  194. }
  195. if ($result >= 0) {
  196. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  197. exit();
  198. }
  199. } else {
  200. setEventMessages($object->error, $object->errors, 'errors');
  201. $action = '';
  202. }
  203. }
  204. // Delete link of credit note to invoice
  205. else if ($action == 'unlinkdiscount' && $user->rights->facture->creer)
  206. {
  207. $discount = new DiscountAbsolute($db);
  208. $result = $discount->fetch(GETPOST("discountid"));
  209. $discount->unlink_invoice();
  210. }
  211. // Validation
  212. else if ($action == 'valid' && $user->rights->facture->creer)
  213. {
  214. $object->fetch($id);
  215. // On verifie signe facture
  216. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  217. // Si avoir, le signe doit etre negatif
  218. if ($object->total_ht >= 0) {
  219. setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
  220. $action = '';
  221. }
  222. } else {
  223. // Si non avoir, le signe doit etre positif
  224. if (empty($conf->global->FACTURE_ENABLE_NEGATIVE) && $object->total_ht < 0) {
  225. setEventMessages($langs->trans("ErrorInvoiceOfThisTypeMustBePositive"), null, 'errors');
  226. $action = '';
  227. }
  228. }
  229. }
  230. else if ($action == 'set_thirdparty' && $user->rights->facture->creer)
  231. {
  232. $object->fetch($id);
  233. $object->setValueFrom('fk_soc', $socid);
  234. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  235. exit();
  236. }
  237. else if ($action == 'classin' && $user->rights->facture->creer)
  238. {
  239. $object->fetch($id);
  240. $object->setProject($_POST['projectid']);
  241. }
  242. else if ($action == 'setmode' && $user->rights->facture->creer)
  243. {
  244. $object->fetch($id);
  245. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  246. if ($result < 0)
  247. dol_print_error($db, $object->error);
  248. }
  249. // Multicurrency Code
  250. else if ($action == 'setmulticurrencycode' && $user->rights->facture->creer) {
  251. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  252. }
  253. // Multicurrency rate
  254. else if ($action == 'setmulticurrencyrate' && $user->rights->facture->creer) {
  255. $result = $object->setMulticurrencyRate(GETPOST('multicurrency_tx', 'int'));
  256. }
  257. else if ($action == 'setinvoicedate' && $user->rights->facture->creer)
  258. {
  259. $object->fetch($id);
  260. $old_date_lim_reglement = $object->date_lim_reglement;
  261. $date = dol_mktime(12, 0, 0, $_POST['invoicedatemonth'], $_POST['invoicedateday'], $_POST['invoicedateyear']);
  262. if (empty($date))
  263. {
  264. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  265. header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate');
  266. exit;
  267. }
  268. $object->date=$date;
  269. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  270. if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement;
  271. if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date;
  272. $result = $object->update($user);
  273. if ($result < 0) dol_print_error($db, $object->error);
  274. }
  275. else if ($action == 'setdate_pointoftax' && $user->rights->facture->creer)
  276. {
  277. $object->fetch($id);
  278. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  279. $object->date_pointoftax=$date_pointoftax;
  280. $result = $object->update($user);
  281. if ($result < 0) dol_print_error($db, $object->error);
  282. }
  283. else if ($action == 'setconditions' && $user->rights->facture->creer)
  284. {
  285. $object->fetch($id);
  286. $object->cond_reglement_code = 0; // To clean property
  287. $object->cond_reglement_id = 0; // To clean property
  288. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  289. if ($result < 0) dol_print_error($db, $object->error);
  290. $old_date_lim_reglement = $object->date_lim_reglement;
  291. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  292. if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement;
  293. if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date;
  294. $result = $object->update($user);
  295. if ($result < 0) dol_print_error($db, $object->error);
  296. }
  297. else if ($action == 'setpaymentterm' && $user->rights->facture->creer)
  298. {
  299. $object->fetch($id);
  300. $object->date_lim_reglement = dol_mktime(12, 0, 0, $_POST['paymenttermmonth'], $_POST['paymenttermday'], $_POST['paymenttermyear']);
  301. if ($object->date_lim_reglement < $object->date) {
  302. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  303. setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
  304. }
  305. $result = $object->update($user);
  306. if ($result < 0)
  307. dol_print_error($db, $object->error);
  308. }
  309. else if ($action == 'setrevenuestamp' && $user->rights->facture->creer)
  310. {
  311. $object->fetch($id);
  312. $object->revenuestamp = GETPOST('revenuestamp');
  313. $result = $object->update($user);
  314. $object->update_price(1);
  315. if ($result < 0)
  316. dol_print_error($db, $object->error);
  317. }
  318. // Set incoterm
  319. elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled))
  320. {
  321. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  322. }
  323. // bank account
  324. else if ($action == 'setbankaccount' && $user->rights->facture->creer)
  325. {
  326. $result=$object->setBankAccount(GETPOST('fk_account', 'int'));
  327. }
  328. else if ($action == 'setremisepercent' && $user->rights->facture->creer)
  329. {
  330. $object->fetch($id);
  331. $result = $object->set_remise($user, $_POST['remise_percent']);
  332. }
  333. else if ($action == "setabsolutediscount" && $user->rights->facture->creer)
  334. {
  335. // POST[remise_id] ou POST[remise_id_for_payment]
  336. if (! empty($_POST["remise_id"])) {
  337. $ret = $object->fetch($id);
  338. if ($ret > 0) {
  339. $result = $object->insert_discount($_POST["remise_id"]);
  340. if ($result < 0) {
  341. setEventMessages($object->error, $object->errors, 'errors');
  342. }
  343. } else {
  344. dol_print_error($db, $object->error);
  345. }
  346. }
  347. if (! empty($_POST["remise_id_for_payment"])) {
  348. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  349. $discount = new DiscountAbsolute($db);
  350. $discount->fetch($_POST["remise_id_for_payment"]);
  351. $result = $discount->link_to_invoice(0, $id);
  352. if ($result < 0) {
  353. setEventMessages($discount->error, $discount->errors, 'errors');
  354. }
  355. }
  356. }
  357. else if ($action == 'set_ref_client' && $user->rights->facture->creer)
  358. {
  359. $object->fetch($id);
  360. $object->set_ref_client($_POST['ref_client']);
  361. }
  362. // Classify to validated
  363. else if ($action == 'confirm_valid' && $confirm == 'yes' &&
  364. ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
  365. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate)))
  366. )
  367. {
  368. $idwarehouse = GETPOST('idwarehouse');
  369. $object->fetch($id);
  370. $object->fetch_thirdparty();
  371. // Check parameters
  372. // Check for mandatory prof id (but only if country is than than ours)
  373. if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id)
  374. {
  375. for ($i = 1; $i <= 6; $i++)
  376. {
  377. $idprof_mandatory = 'SOCIETE_IDPROF' . ($i) . '_INVOICE_MANDATORY';
  378. $idprof = 'idprof' . $i;
  379. if (! $object->thirdparty->$idprof && ! empty($conf->global->$idprof_mandatory))
  380. {
  381. if (! $error) $langs->load("errors");
  382. $error++;
  383. setEventMessages($langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId' . $i, $object->thirdparty->country_code)), null, 'errors');
  384. }
  385. }
  386. }
  387. $qualified_for_stock_change = 0;
  388. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  389. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  390. } else {
  391. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  392. }
  393. // Check for warehouse
  394. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
  395. {
  396. if (! $idwarehouse || $idwarehouse == - 1) {
  397. $error ++;
  398. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  399. $action = '';
  400. }
  401. }
  402. if (! $error)
  403. {
  404. $result = $object->validate($user, '', $idwarehouse);
  405. if ($result >= 0)
  406. {
  407. // Define output language
  408. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  409. {
  410. $outputlangs = $langs;
  411. $newlang = '';
  412. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
  413. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  414. if (! empty($newlang)) {
  415. $outputlangs = new Translate("", $conf);
  416. $outputlangs->setDefaultLang($newlang);
  417. }
  418. $model=$object->modelpdf;
  419. $ret = $object->fetch($id); // Reload to get new records
  420. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  421. if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
  422. }
  423. }
  424. else
  425. {
  426. if (count($object->errors)) setEventMessages(null, $object->errors, 'errors');
  427. else setEventMessages($object->error, $object->errors, 'errors');
  428. }
  429. }
  430. }
  431. // Go back to draft status (unvalidate)
  432. else if ($action == 'confirm_modif' &&
  433. ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
  434. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
  435. )
  436. {
  437. $idwarehouse = GETPOST('idwarehouse');
  438. $object->fetch($id);
  439. $object->fetch_thirdparty();
  440. $qualified_for_stock_change = 0;
  441. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  442. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  443. } else {
  444. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  445. }
  446. // Check parameters
  447. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
  448. {
  449. if (! $idwarehouse || $idwarehouse == - 1) {
  450. $error ++;
  451. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  452. $action = '';
  453. }
  454. }
  455. if (! $error) {
  456. // On verifie si la facture a des paiements
  457. $sql = 'SELECT pf.amount';
  458. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf';
  459. $sql .= ' WHERE pf.fk_facture = ' . $object->id;
  460. $result = $db->query($sql);
  461. if ($result) {
  462. $i = 0;
  463. $num = $db->num_rows($result);
  464. while ($i < $num) {
  465. $objp = $db->fetch_object($result);
  466. $totalpaye += $objp->amount;
  467. $i ++;
  468. }
  469. } else {
  470. dol_print_error($db, '');
  471. }
  472. $resteapayer = $object->total_ttc - $totalpaye;
  473. // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
  474. $ventilExportCompta = $object->getVentilExportCompta();
  475. // On verifie si aucun paiement n'a ete effectue
  476. if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0)
  477. {
  478. $result=$object->set_draft($user, $idwarehouse);
  479. if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
  480. // Define output language
  481. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  482. {
  483. $outputlangs = $langs;
  484. $newlang = '';
  485. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
  486. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  487. if (! empty($newlang)) {
  488. $outputlangs = new Translate("", $conf);
  489. $outputlangs->setDefaultLang($newlang);
  490. }
  491. $model=$object->modelpdf;
  492. $ret = $object->fetch($id); // Reload to get new records
  493. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  494. }
  495. }
  496. }
  497. }
  498. // Classify "paid"
  499. else if ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->facture->paiement)
  500. {
  501. $object->fetch($id);
  502. $result = $object->set_paid($user);
  503. if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
  504. } // Classif "paid partialy"
  505. else if ($action == 'confirm_paid_partially' && $confirm == 'yes' && $user->rights->facture->paiement)
  506. {
  507. $object->fetch($id);
  508. $close_code = $_POST["close_code"];
  509. $close_note = $_POST["close_note"];
  510. if ($close_code) {
  511. $result = $object->set_paid($user, $close_code, $close_note);
  512. if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
  513. } else {
  514. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  515. }
  516. } // Classify "abandoned"
  517. else if ($action == 'confirm_canceled' && $confirm == 'yes') {
  518. $object->fetch($id);
  519. $close_code = $_POST["close_code"];
  520. $close_note = $_POST["close_note"];
  521. if ($close_code) {
  522. $result = $object->set_canceled($user, $close_code, $close_note);
  523. if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
  524. } else {
  525. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  526. }
  527. }
  528. // Convertir en reduc
  529. else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->facture->creer)
  530. {
  531. $object->fetch($id);
  532. $object->fetch_thirdparty();
  533. //$object->fetch_lines(); // Already done into fetch
  534. // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
  535. $discountcheck=new DiscountAbsolute($db);
  536. $result=$discountcheck->fetch(0,$object->id);
  537. $canconvert=0;
  538. if ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 1 && empty($discountcheck->id)) $canconvert=1; // we can convert deposit into discount if deposit is payed completely and not already converted (see real condition into condition used to show button converttoreduc)
  539. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->paye == 0 && empty($discountcheck->id)) $canconvert=1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
  540. if ($canconvert)
  541. {
  542. $db->begin();
  543. // Boucle sur chaque taux de tva
  544. $i = 0;
  545. foreach ($object->lines as $line)
  546. {
  547. if ($line->total_ht!=0)
  548. { // no need to create discount if amount is null
  549. $amount_ht[$line->tva_tx] += $line->total_ht;
  550. $amount_tva[$line->tva_tx] += $line->total_tva;
  551. $amount_ttc[$line->tva_tx] += $line->total_ttc;
  552. $i ++;
  553. }
  554. }
  555. // Insert one discount by VAT rate category
  556. $discount = new DiscountAbsolute($db);
  557. if ($object->type == Facture::TYPE_CREDIT_NOTE)
  558. $discount->description = '(CREDIT_NOTE)';
  559. elseif ($object->type == Facture::TYPE_DEPOSIT)
  560. $discount->description = '(DEPOSIT)';
  561. else {
  562. setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
  563. }
  564. $discount->tva_tx = abs($object->total_ttc);
  565. $discount->fk_soc = $object->socid;
  566. $discount->fk_facture_source = $object->id;
  567. $error = 0;
  568. foreach ($amount_ht as $tva_tx => $xxx)
  569. {
  570. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  571. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  572. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  573. $discount->tva_tx = abs($tva_tx);
  574. $result = $discount->create($user);
  575. if ($result < 0)
  576. {
  577. $error++;
  578. break;
  579. }
  580. }
  581. if (empty($error))
  582. {
  583. // Classe facture
  584. $result = $object->set_paid($user);
  585. if ($result >= 0)
  586. {
  587. $db->commit();
  588. }
  589. else
  590. {
  591. setEventMessages($object->error, $object->errors, 'errors');
  592. $db->rollback();
  593. }
  594. }
  595. else
  596. {
  597. setEventMessages($discount->error, $discount->errors, 'errors');
  598. $db->rollback();
  599. }
  600. }
  601. }
  602. /*
  603. * Insert new invoice in database
  604. */
  605. else if ($action == 'add' && $user->rights->facture->creer)
  606. {
  607. if ($socid > 0) $object->socid = GETPOST('socid', 'int');
  608. $db->begin();
  609. $error = 0;
  610. // Fill array 'array_options' with data from add form
  611. $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
  612. $ret = $extrafields->setOptionalsFromPost($extralabels, $object);
  613. if ($ret < 0) $error++;
  614. // Replacement invoice
  615. if ($_POST['type'] == Facture::TYPE_REPLACEMENT)
  616. {
  617. $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  618. if (empty($dateinvoice))
  619. {
  620. $error++;
  621. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  622. }
  623. if (! ($_POST['fac_replacement'] > 0)) {
  624. $error ++;
  625. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
  626. }
  627. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  628. if (! $error) {
  629. // This is a replacement invoice
  630. $result = $object->fetch($_POST['fac_replacement']);
  631. $object->fetch_thirdparty();
  632. $object->date = $dateinvoice;
  633. $object->date_pointoftax = $date_pointoftax;
  634. $object->note_public = trim($_POST['note_public']);
  635. $object->note = trim($_POST['note']);
  636. $object->ref_client = $_POST['ref_client'];
  637. $object->ref_int = $_POST['ref_int'];
  638. $object->modelpdf = $_POST['model'];
  639. $object->fk_project = $_POST['projectid'];
  640. $object->cond_reglement_id = $_POST['cond_reglement_id'];
  641. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  642. $object->fk_account = GETPOST('fk_account', 'int');
  643. $object->remise_absolue = $_POST['remise_absolue'];
  644. $object->remise_percent = $_POST['remise_percent'];
  645. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  646. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  647. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  648. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  649. // Proprietes particulieres a facture de remplacement
  650. $object->fk_facture_source = $_POST['fac_replacement'];
  651. $object->type = Facture::TYPE_REPLACEMENT;
  652. $id = $object->createFromCurrent($user);
  653. if ($id <= 0) {
  654. setEventMessages($object->error, $object->errors, 'errors');
  655. }
  656. }
  657. }
  658. // Credit note invoice
  659. if ($_POST['type'] == Facture::TYPE_CREDIT_NOTE)
  660. {
  661. $sourceinvoice = GETPOST('fac_avoir');
  662. if (! ($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE))
  663. {
  664. $error ++;
  665. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  666. }
  667. $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  668. if (empty($dateinvoice))
  669. {
  670. $error ++;
  671. setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Date")), null, 'errors');
  672. }
  673. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  674. if (! $error)
  675. {
  676. $object->socid = GETPOST('socid','int');
  677. $object->number = $_POST['facnumber'];
  678. $object->date = $dateinvoice;
  679. $object->date_pointoftax = $date_pointoftax;
  680. $object->note_public = trim($_POST['note_public']);
  681. $object->note = trim($_POST['note']);
  682. $object->ref_client = $_POST['ref_client'];
  683. $object->ref_int = $_POST['ref_int'];
  684. $object->modelpdf = $_POST['model'];
  685. $object->fk_project = $_POST['projectid'];
  686. $object->cond_reglement_id = 0;
  687. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  688. $object->fk_account = GETPOST('fk_account', 'int');
  689. $object->remise_absolue = $_POST['remise_absolue'];
  690. $object->remise_percent = $_POST['remise_percent'];
  691. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  692. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  693. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  694. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  695. // Proprietes particulieres a facture avoir
  696. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  697. $object->type = Facture::TYPE_CREDIT_NOTE;
  698. $id = $object->create($user);
  699. if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0)
  700. {
  701. $facture_source = new Facture($db); // fetch origin object
  702. if ($facture_source->fetch($object->fk_facture_source)>0)
  703. {
  704. $fk_parent_line = 0;
  705. foreach($facture_source->lines as $line)
  706. {
  707. // Reset fk_parent_line for no child products and special product
  708. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  709. $fk_parent_line = 0;
  710. }
  711. $line->fk_facture = $object->id;
  712. $line->fk_parent_line = $fk_parent_line;
  713. $line->subprice =-$line->subprice; // invert price for object
  714. $line->pa_ht = -$line->pa_ht;
  715. $line->total_ht=-$line->total_ht;
  716. $line->total_tva=-$line->total_tva;
  717. $line->total_ttc=-$line->total_ttc;
  718. $line->total_localtax1=-$line->total_localtax1;
  719. $line->total_localtax2=-$line->total_localtax2;
  720. $result = $line->insert();
  721. $object->lines[] = $line; // insert new line in current object
  722. // Defined the new fk_parent_line
  723. if ($result > 0 && $line->product_type == 9) {
  724. $fk_parent_line = $result;
  725. }
  726. }
  727. $object->update_price(1);
  728. }
  729. }
  730. if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0)
  731. {
  732. $facture_source = new Facture($db); // fetch origin object if not previously defined
  733. if ($facture_source->fetch($object->fk_facture_source)>0)
  734. {
  735. $totalpaye = $facture_source->getSommePaiement();
  736. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  737. $totaldeposits = $facture_source->getSumDepositsUsed();
  738. $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits);
  739. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC');
  740. }
  741. }
  742. // Add predefined lines
  743. /*
  744. TODO delete
  745. for($i = 1; $i <= $NBLINES; $i ++) {
  746. if ($_POST['idprod' . $i]) {
  747. $product = new Product($db);
  748. $product->fetch($_POST['idprod' . $i]);
  749. $startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']);
  750. $endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']);
  751. $result = $object->addline($product->description, $product->price, $_POST['qty' . $i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod' . $i], $_POST['remise_percent' . $i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type);
  752. }
  753. }*/
  754. }
  755. }
  756. // Standard invoice or Deposit invoice created from a Predefined template invoice
  757. if (($_POST['type'] == Facture::TYPE_STANDARD || $_POST['type'] == Facture::TYPE_DEPOSIT) && GETPOST('fac_rec') > 0)
  758. {
  759. $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  760. if (empty($dateinvoice))
  761. {
  762. $error++;
  763. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  764. }
  765. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  766. if (! $error)
  767. {
  768. $object->socid = GETPOST('socid','int');
  769. $object->type = $_POST['type'];
  770. $object->number = $_POST['facnumber'];
  771. $object->date = $dateinvoice;
  772. $object->date_pointoftax = $date_pointoftax;
  773. $object->note_public = trim($_POST['note_public']);
  774. $object->note_private = trim($_POST['note_private']);
  775. $object->ref_client = $_POST['ref_client'];
  776. $object->ref_int = $_POST['ref_int'];
  777. $object->modelpdf = $_POST['model'];
  778. $object->fk_project = $_POST['projectid'];
  779. $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']);
  780. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  781. $object->fk_account = GETPOST('fk_account', 'int');
  782. $object->amount = $_POST['amount'];
  783. $object->remise_absolue = $_POST['remise_absolue'];
  784. $object->remise_percent = $_POST['remise_percent'];
  785. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  786. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  787. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  788. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  789. // Source facture
  790. $object->fac_rec = GETPOST('fac_rec');
  791. $id = $object->create($user);
  792. }
  793. }
  794. // Standard or deposit or proforma invoice
  795. if (($_POST['type'] == Facture::TYPE_STANDARD || $_POST['type'] == Facture::TYPE_DEPOSIT || $_POST['type'] == Facture::TYPE_PROFORMA || ($_POST['type'] == Facture::TYPE_SITUATION && empty($_POST['situations']))) && GETPOST('fac_rec') <= 0)
  796. {
  797. if (GETPOST('socid', 'int') < 1)
  798. {
  799. $error ++;
  800. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
  801. }
  802. $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  803. if (empty($dateinvoice))
  804. {
  805. $error++;
  806. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  807. }
  808. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  809. if (! $error)
  810. {
  811. // Si facture standard
  812. $object->socid = GETPOST('socid','int');
  813. $object->type = GETPOST('type');
  814. $object->number = $_POST['facnumber'];
  815. $object->date = $dateinvoice;
  816. $object->date_pointoftax = $date_pointoftax;
  817. $object->note_public = trim($_POST['note_public']);
  818. $object->note_private = trim($_POST['note_private']);
  819. $object->ref_client = $_POST['ref_client'];
  820. $object->ref_int = $_POST['ref_int'];
  821. $object->modelpdf = $_POST['model'];
  822. $object->fk_project = $_POST['projectid'];
  823. $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']);
  824. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  825. $object->fk_account = GETPOST('fk_account', 'int');
  826. $object->amount = $_POST['amount'];
  827. $object->remise_absolue = $_POST['remise_absolue'];
  828. $object->remise_percent = $_POST['remise_percent'];
  829. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  830. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  831. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  832. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  833. if (GETPOST('type') == Facture::TYPE_SITUATION)
  834. {
  835. $object->situation_counter = 1;
  836. $object->situation_final = 0;
  837. $object->situation_cycle_ref = $object->newCycle();
  838. }
  839. $object->fetch_thirdparty();
  840. // If creation from another object of another module (Example: origin=propal, originid=1)
  841. if (! empty($origin) && ! empty($originid))
  842. {
  843. // Parse element/subelement (ex: project_task)
  844. $element = $subelement = $origin;
  845. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  846. $element = $regs [1];
  847. $subelement = $regs [2];
  848. }
  849. // For compatibility
  850. if ($element == 'order') {
  851. $element = $subelement = 'commande';
  852. }
  853. if ($element == 'propal') {
  854. $element = 'comm/propal';
  855. $subelement = 'propal';
  856. }
  857. if ($element == 'contract') {
  858. $element = $subelement = 'contrat';
  859. }
  860. if ($element == 'inter') {
  861. $element = $subelement = 'ficheinter';
  862. }
  863. if ($element == 'shipping') {
  864. $element = $subelement = 'expedition';
  865. }
  866. $object->origin = $origin;
  867. $object->origin_id = $originid;
  868. // Possibility to add external linked objects with hooks
  869. $object->linked_objects[$object->origin] = $object->origin_id;
  870. // link with order if it is a shipping invoice
  871. if ($object->origin == 'shipping')
  872. {
  873. require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
  874. $exp = new Expedition($db);
  875. $exp->fetch($object->origin_id);
  876. $exp->fetchObjectLinked();
  877. if (count($exp->linkedObjectsIds['commande']) > 0) {
  878. foreach ($exp->linkedObjectsIds['commande'] as $key => $value){
  879. $object->linked_objects['commande'] = $value;
  880. }
  881. }
  882. }
  883. if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects']))
  884. {
  885. $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
  886. }
  887. $id = $object->create($user);
  888. if ($id > 0)
  889. {
  890. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  891. $classname = ucfirst($subelement);
  892. $srcobject = new $classname($db);
  893. dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines");
  894. $result = $srcobject->fetch($object->origin_id);
  895. // If deposit invoice
  896. if ($_POST['type'] == Facture::TYPE_DEPOSIT)
  897. {
  898. $typeamount = GETPOST('typedeposit', 'alpha');
  899. $valuedeposit = GETPOST('valuedeposit', 'int');
  900. if ($typeamount == 'amount')
  901. {
  902. $amountdeposit = $valuedeposit;
  903. }
  904. else
  905. {
  906. $amountdeposit = 0;
  907. if ($result > 0)
  908. {
  909. $totalamount = 0;
  910. $lines = $srcobject->lines;
  911. $numlines=count($lines);
  912. for ($i=0; $i<$numlines; $i++)
  913. {
  914. $qualified=1;
  915. if (empty($lines[$i]->qty)) $qualified=0; // We discard qty=0, it is an option
  916. if (! empty($lines[$i]->special_code)) $qualified=0; // We discard special_code (frais port, ecotaxe, option, ...)
  917. if ($qualified) $totalamount += $lines[$i]->total_ht;
  918. }
  919. if ($totalamount != 0) {
  920. $amountdeposit = ($totalamount * $valuedeposit) / 100;
  921. }
  922. } else {
  923. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  924. $error ++;
  925. }
  926. }
  927. $result = $object->addline(
  928. $langs->trans('Deposit'),
  929. $amountdeposit, // subprice
  930. 1, // quantity
  931. $lines[$i]->tva_tx, 0, // localtax1_tx
  932. 0, // localtax2_tx
  933. 0, // fk_product
  934. 0, // remise_percent
  935. 0, // date_start
  936. 0, // date_end
  937. 0, $lines[$i]->info_bits, // info_bits
  938. 0, // info_bits
  939. 'HT',
  940. 0,
  941. 0, // product_type
  942. 1,
  943. $lines[$i]->special_code,
  944. $object->origin,
  945. 0,
  946. 0,
  947. 0,
  948. 0,
  949. $langs->trans('Deposit')
  950. );
  951. }
  952. else
  953. {
  954. if ($result > 0)
  955. {
  956. $lines = $srcobject->lines;
  957. if (empty($lines) && method_exists($srcobject, 'fetch_lines'))
  958. {
  959. $srcobject->fetch_lines();
  960. $lines = $srcobject->lines;
  961. }
  962. $fk_parent_line=0;
  963. $num=count($lines);
  964. for ($i=0;$i<$num;$i++)
  965. {
  966. // Don't add lines with qty 0 when coming from a shipment including all order lines
  967. if($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) continue;
  968. $label=(! empty($lines[$i]->label)?$lines[$i]->label:'');
  969. $desc=(! empty($lines[$i]->desc)?$lines[$i]->desc:$lines[$i]->libelle);
  970. if ($object->situation_counter == 1) $lines[$i]->situation_percent = 0;
  971. if ($lines[$i]->subprice < 0)
  972. {
  973. // Negative line, we create a discount line
  974. $discount = new DiscountAbsolute($db);
  975. $discount->fk_soc = $object->socid;
  976. $discount->amount_ht = abs($lines[$i]->total_ht);
  977. $discount->amount_tva = abs($lines[$i]->total_tva);
  978. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  979. $discount->tva_tx = $lines[$i]->tva_tx;
  980. $discount->fk_user = $user->id;
  981. $discount->description = $desc;
  982. $discountid = $discount->create($user);
  983. if ($discountid > 0) {
  984. $result = $object->insert_discount($discountid); // This include link_to_invoice
  985. } else {
  986. setEventMessages($discount->error, $discount->errors, 'errors');
  987. $error ++;
  988. break;
  989. }
  990. } else {
  991. // Positive line
  992. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  993. // Date start
  994. $date_start = false;
  995. if ($lines[$i]->date_debut_prevue)
  996. $date_start = $lines[$i]->date_debut_prevue;
  997. if ($lines[$i]->date_debut_reel)
  998. $date_start = $lines[$i]->date_debut_reel;
  999. if ($lines[$i]->date_start)
  1000. $date_start = $lines[$i]->date_start;
  1001. // Date end
  1002. $date_end = false;
  1003. if ($lines[$i]->date_fin_prevue)
  1004. $date_end = $lines[$i]->date_fin_prevue;
  1005. if ($lines[$i]->date_fin_reel)
  1006. $date_end = $lines[$i]->date_fin_reel;
  1007. if ($lines[$i]->date_end)
  1008. $date_end = $lines[$i]->date_end;
  1009. // Reset fk_parent_line for no child products and special product
  1010. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  1011. $fk_parent_line = 0;
  1012. }
  1013. // Extrafields
  1014. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
  1015. $lines[$i]->fetch_optionals($lines[$i]->rowid);
  1016. $array_options = $lines[$i]->array_options;
  1017. }
  1018. // View third's localtaxes for now
  1019. $localtax1_tx = get_localtax($lines[$i]->tva_tx, 1, $object->thirdparty);
  1020. $localtax2_tx = get_localtax($lines[$i]->tva_tx, 2, $object->thirdparty);
  1021. $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $localtax1_tx, $localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit);
  1022. if ($result > 0) {
  1023. $lineid = $result;
  1024. } else {
  1025. $lineid = 0;
  1026. $error ++;
  1027. break;
  1028. }
  1029. // Defined the new fk_parent_line
  1030. if ($result > 0 && $lines[$i]->product_type == 9) {
  1031. $fk_parent_line = $result;
  1032. }
  1033. }
  1034. }
  1035. } else {
  1036. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1037. $error ++;
  1038. }
  1039. }
  1040. // Now we create same links to contact than the ones found on origin object
  1041. if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
  1042. {
  1043. $originforcontact = $object->origin;
  1044. $originidforcontact = $object->origin_id;
  1045. if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
  1046. {
  1047. $originforcontact=$srcobject->origin;
  1048. $originidforcontact=$srcobject->origin_id;
  1049. }
  1050. $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  1051. $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
  1052. $resqlcontact = $db->query($sqlcontact);
  1053. if ($resqlcontact)
  1054. {
  1055. while($objcontact = $db->fetch_object($resqlcontact))
  1056. {
  1057. //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
  1058. $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
  1059. }
  1060. }
  1061. else dol_print_error($resqlcontact);
  1062. }
  1063. // Hooks
  1064. $parameters = array('objFrom' => $srcobject);
  1065. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
  1066. // modified by hook
  1067. if ($reshook < 0)
  1068. {
  1069. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1070. $error++;
  1071. }
  1072. } else {
  1073. setEventMessages($object->error, $object->errors, 'errors');
  1074. $error++;
  1075. }
  1076. }
  1077. else
  1078. { // If some invoice's lines coming from page
  1079. $id = $object->create($user);
  1080. for ($i = 1; $i <= $NBLINES; $i ++) {
  1081. if ($_POST['idprod' . $i]) {
  1082. $product = new Product($db);
  1083. $product->fetch($_POST['idprod' . $i]);
  1084. $startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']);
  1085. $endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']);
  1086. $result = $object->addline($product->description, $product->price, $_POST['qty' . $i], $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, $_POST['idprod' . $i], $_POST['remise_percent' . $i], $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, null, 0, '', 0, 100, '', $product->fk_unit);
  1087. }
  1088. }
  1089. }
  1090. }
  1091. }
  1092. if (GETPOST('type') == Facture::TYPE_SITUATION && (!empty($_POST['situations'])))
  1093. {
  1094. $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  1095. if (empty($datefacture)) {
  1096. $error++;
  1097. $mesg = '<div class="error">' . $langs->trans("ErrorFieldRequired", $langs->trans("Date")) . '</div>';
  1098. }
  1099. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  1100. if (!($_POST['situations'] > 0)) {
  1101. $error++;
  1102. $mesg = '<div class="error">' . $langs->trans("ErrorFieldRequired", $langs->trans("InvoiceSituation")) . '</div>';
  1103. }
  1104. if (!$error) {
  1105. $result = $object->fetch($_POST['situations']);
  1106. $object->fk_facture_source = $_POST['situations'];
  1107. $object->type = Facture::TYPE_SITUATION;
  1108. if (!empty($origin) && !empty($originid))
  1109. {
  1110. $object->origin = $origin;
  1111. $object->origin_id = $originid;
  1112. foreach ($object->lines as &$line)
  1113. {
  1114. $line->origin = $object->origin;
  1115. $line->origin_id = $line->id;
  1116. }
  1117. }
  1118. $object->fetch_thirdparty();
  1119. $object->date = $datefacture;
  1120. $object->date_pointoftax = $date_pointoftax;
  1121. $object->note_public = trim($_POST['note_public']);
  1122. $object->note = trim($_POST['note']);
  1123. $object->ref_client = $_POST['ref_client'];
  1124. $object->ref_int = $_POST['ref_int'];
  1125. $object->modelpdf = $_POST['model'];
  1126. $object->fk_project = $_POST['projectid'];
  1127. $object->cond_reglement_id = $_POST['cond_reglement_id'];
  1128. $object->mode_reglement_id = $_POST['mode_reglement_id'];
  1129. $object->remise_absolue = $_POST['remise_absolue'];
  1130. $object->remise_percent = $_POST['remise_percent'];
  1131. // Proprietes particulieres a facture de remplacement
  1132. $object->situation_counter = $object->situation_counter + 1;
  1133. $id = $object->createFromCurrent($user);
  1134. if ($id <= 0) $mesg = $object->error;
  1135. }
  1136. }
  1137. // End of object creation, we show it
  1138. if ($id > 0 && ! $error)
  1139. {
  1140. $db->commit();
  1141. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  1142. exit();
  1143. }
  1144. else
  1145. {
  1146. $db->rollback();
  1147. $action = 'create';
  1148. $_GET["origin"] = $_POST["origin"];
  1149. $_GET["originid"] = $_POST["originid"];
  1150. setEventMessages($object->error, $object->errors, 'errors');
  1151. }
  1152. }
  1153. // Add a new line
  1154. else if ($action == 'addline' && $user->rights->facture->creer)
  1155. {
  1156. $langs->load('errors');
  1157. $error = 0;
  1158. // Set if we used free entry or predefined product
  1159. $predef='';
  1160. $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
  1161. $price_ht = GETPOST('price_ht');
  1162. if (GETPOST('prod_entry_mode') == 'free')
  1163. {
  1164. $idprod=0;
  1165. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  1166. }
  1167. else
  1168. {
  1169. $idprod=GETPOST('idprod', 'int');
  1170. $tva_tx = '';
  1171. }
  1172. $qty = GETPOST('qty' . $predef);
  1173. $remise_percent = GETPOST('remise_percent' . $predef);
  1174. // Extrafields
  1175. $extrafieldsline = new ExtraFields($db);
  1176. $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
  1177. $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
  1178. // Unset extrafield
  1179. if (is_array($extralabelsline)) {
  1180. // Get extra fields
  1181. foreach ($extralabelsline as $key => $value) {
  1182. unset($_POST["options_" . $key . $predef]);
  1183. }
  1184. }
  1185. if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) {
  1186. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1187. $error ++;
  1188. }
  1189. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) {
  1190. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  1191. $error ++;
  1192. }
  1193. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not ''
  1194. {
  1195. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  1196. $error ++;
  1197. }
  1198. if ($qty == '') {
  1199. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1200. $error ++;
  1201. }
  1202. if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) {
  1203. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  1204. $error ++;
  1205. }
  1206. if ($qty < 0) {
  1207. $langs->load("errors");
  1208. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  1209. $error ++;
  1210. }
  1211. if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) {
  1212. $ret = $object->fetch($id);
  1213. if ($ret < 0) {
  1214. dol_print_error($db, $object->error);
  1215. exit();
  1216. }
  1217. $ret = $object->fetch_thirdparty();
  1218. // Clean parameters
  1219. $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'));
  1220. $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'));
  1221. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  1222. // Define special_code for special lines
  1223. $special_code = 0;
  1224. // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices
  1225. // Ecrase $pu par celui du produit
  1226. // Ecrase $desc par celui du produit
  1227. // Ecrase $txtva par celui du produit
  1228. // Ecrase $base_price_type par celui du produit
  1229. // Replaces $fk_unit with the product's
  1230. if (! empty($idprod))
  1231. {
  1232. $prod = new Product($db);
  1233. $prod->fetch($idprod);
  1234. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  1235. // Update if prices fields are defined
  1236. $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
  1237. $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
  1238. if (empty($tva_tx)) $tva_npr=0;
  1239. $pu_ht = $prod->price;
  1240. $pu_ttc = $prod->price_ttc;
  1241. $price_min = $prod->price_min;
  1242. $price_base_type = $prod->price_base_type;
  1243. // We define price for product
  1244. if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
  1245. {
  1246. $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
  1247. $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
  1248. $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
  1249. $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
  1250. if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility
  1251. {
  1252. if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level];
  1253. if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level];
  1254. if (empty($tva_tx)) $tva_npr=0;
  1255. }
  1256. }
  1257. elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  1258. {
  1259. require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
  1260. $prodcustprice = new Productcustomerprice($db);
  1261. $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
  1262. $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
  1263. if ($result) {
  1264. if (count($prodcustprice->lines) > 0) {
  1265. $pu_ht = price($prodcustprice->lines[0]->price);
  1266. $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
  1267. $price_base_type = $prodcustprice->lines[0]->price_base_type;
  1268. $prod->tva_tx = $prodcustprice->lines[0]->tva_tx;
  1269. }
  1270. }
  1271. }
  1272. // if price ht was forced (ie: from gui when calculated by margin rate and cost price)
  1273. if (! empty($price_ht))
  1274. {
  1275. $pu_ht = price2num($price_ht, 'MU');
  1276. $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 100)), 'MU');
  1277. }
  1278. // On reevalue prix selon taux tva car taux tva transaction peut etre different
  1279. // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
  1280. elseif ($tva_tx != $prod->tva_tx)
  1281. {
  1282. if ($price_base_type != 'HT')
  1283. {
  1284. $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU');
  1285. }
  1286. else
  1287. {
  1288. $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 100)), 'MU');
  1289. }
  1290. }
  1291. $desc = '';
  1292. // Define output language
  1293. if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  1294. $outputlangs = $langs;
  1295. $newlang = '';
  1296. if (empty($newlang) && GETPOST('lang_id'))
  1297. $newlang = GETPOST('lang_id');
  1298. if (empty($newlang))
  1299. $newlang = $object->thirdparty->default_lang;
  1300. if (! empty($newlang)) {
  1301. $outputlangs = new Translate("", $conf);
  1302. $outputlangs->setDefaultLang($newlang);
  1303. }
  1304. $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
  1305. } else {
  1306. $desc = $prod->description;
  1307. }
  1308. $desc = dol_concatdesc($desc, $product_desc);
  1309. // Add custom code and origin country into description
  1310. if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) {
  1311. $tmptxt = '(';
  1312. if (! empty($prod->customcode))
  1313. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
  1314. if (! empty($prod->customcode) && ! empty($prod->country_code))
  1315. $tmptxt .= ' - ';
  1316. if (! empty($prod->country_code))
  1317. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0);
  1318. $tmptxt .= ')';
  1319. $desc = dol_concatdesc($desc, $tmptxt);
  1320. }
  1321. $type = $prod->type;
  1322. $fk_unit = $prod->fk_unit;
  1323. } else {
  1324. $pu_ht = price2num($price_ht, 'MU');
  1325. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  1326. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  1327. $tva_tx = str_replace('*', '', $tva_tx);
  1328. if (empty($tva_tx)) $tva_npr=0;
  1329. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1330. $desc = $product_desc;
  1331. $type = GETPOST('type');
  1332. $fk_unit= GETPOST('units', 'alpha');
  1333. }
  1334. // Margin
  1335. $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : '');
  1336. $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value
  1337. // Local Taxes
  1338. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  1339. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  1340. $info_bits = 0;
  1341. if ($tva_npr)
  1342. $info_bits |= 0x01;
  1343. if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) {
  1344. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
  1345. setEventMessages($mesg, null, 'errors');
  1346. } else {
  1347. // Insert line
  1348. $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $date_start, $date_end, 0, $info_bits, '', $price_base_type, $pu_ttc, $type, - 1, $special_code, '', 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, $_POST['progress'], '', $fk_unit);
  1349. if ($result > 0)
  1350. {
  1351. // Define output language
  1352. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
  1353. {
  1354. $outputlangs = $langs;
  1355. $newlang = '';
  1356. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
  1357. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
  1358. if (! empty($newlang)) {
  1359. $outputlangs = new Translate("", $conf);
  1360. $outputlangs->setDefaultLang($newlang);
  1361. }
  1362. $model=$object->modelpdf;
  1363. $ret = $object->fetch($id); // Reload to get new records
  1364. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1365. if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
  1366. }
  1367. unset($_POST['prod_entry_mode']);
  1368. unset($_POST['qty']);
  1369. unset($_POST['type']);
  1370. unset($_POST['remise_percent']);
  1371. unset($_POST['price_ht']);
  1372. unset($_POST['multicurrency_price_ht']);
  1373. unset($_POST['price_ttc']);
  1374. unset($_POST['tva_tx']);
  1375. unset($_POST['product_ref']);
  1376. unset($_POST['product_label']);
  1377. unset($_POST['product_desc']);
  1378. unset($_POST['fournprice']);
  1379. unset($_POST['buying_price']);
  1380. unset($_POST['np_marginRate']);
  1381. unset($_POST['np_markRate']);
  1382. unset($_POST['dp_desc']);
  1383. unset($_POST['idprod']);
  1384. unset($_POST['units']);
  1385. unset($_POST['date_starthour']);
  1386. unset($_POST['date_startmin']);
  1387. unset($_POST['date_startsec']);
  1388. unset($_POST['date_startday']);
  1389. unset($_POST['date_startmonth']);
  1390. unset($_POST['date_startyear']);
  1391. unset($_POST['date_endhour']);
  1392. unset($_POST['date_endmin']);
  1393. unset($_POST['date_endsec']);
  1394. unset($_POST['date_endday']);
  1395. unset($_POST['date_endmonth']);
  1396. unset($_POST['date_endyear']);
  1397. unset($_POST['situations']);
  1398. unset($_POST['progress']);
  1399. } else {
  1400. setEventMessages($object->error, $object->errors, 'errors');
  1401. }
  1402. $action = '';
  1403. }
  1404. }
  1405. }
  1406. elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel'))
  1407. {
  1408. if (! $object->fetch($id) > 0) dol_print_error($db);
  1409. $object->fetch_thirdparty();
  1410. // Clean parameters
  1411. $date_start = '';
  1412. $date_end = '';
  1413. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  1414. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  1415. $description = dol_htmlcleanlastbr(GETPOST('product_desc') ? GETPOST('product_desc') : GETPOST('desc'));
  1416. $pu_ht = GETPOST('price_ht');
  1417. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  1418. $qty = GETPOST('qty');
  1419. // Define info_bits
  1420. $info_bits = 0;
  1421. if (preg_match('/\*/', $vat_rate))
  1422. $info_bits |= 0x01;
  1423. // Define vat_rate
  1424. $vat_rate = str_replace('*', '', $vat_rate);
  1425. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
  1426. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
  1427. // Add buying price
  1428. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  1429. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  1430. // Extrafields
  1431. $extrafieldsline = new ExtraFields($db);
  1432. $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
  1433. $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline);
  1434. // Unset extrafield
  1435. if (is_array($extralabelsline)) {
  1436. // Get extra fields
  1437. foreach ($extralabelsline as $key => $value) {
  1438. unset($_POST["options_" . $key]);
  1439. }
  1440. }
  1441. // Define special_code for special lines
  1442. $special_code=GETPOST('special_code');
  1443. if (! GETPOST('qty')) $special_code=3;
  1444. $line = new FactureLigne($db);
  1445. $line->fetch(GETPOST('lineid'));
  1446. $percent = $line->get_prev_progress($object->id);
  1447. if (GETPOST('progress') < $percent)
  1448. {
  1449. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  1450. setEventMessages($mesg, null, 'warnings');
  1451. $error++;
  1452. $result = -1;
  1453. }
  1454. // Check minimum price
  1455. $productid = GETPOST('productid', 'int');
  1456. if (! empty($productid))
  1457. {
  1458. $product = new Product($db);
  1459. $product->fetch($productid);
  1460. $type = $product->type;
  1461. $price_min = $product->price_min;
  1462. if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
  1463. $price_min = $product->multiprices_min [$object->thirdparty->price_level];
  1464. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  1465. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  1466. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) {
  1467. setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
  1468. $error ++;
  1469. }
  1470. } else {
  1471. $type = GETPOST('type');
  1472. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1473. // Check parameters
  1474. if (GETPOST('type') < 0) {
  1475. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  1476. $error ++;
  1477. }
  1478. }
  1479. if ($qty < 0) {
  1480. $langs->load("errors");
  1481. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  1482. $error ++;
  1483. }
  1484. // Update line
  1485. if (! $error) {
  1486. $result = $object->updateline(GETPOST('lineid'), $description, $pu_ht, $qty, GETPOST('remise_percent'),
  1487. $date_start, $date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $info_bits, $type,
  1488. GETPOST('fk_parent_line'), 0, $fournprice, $buyingprice, $label, $special_code, $array_options, GETPOST('progress'),
  1489. $_POST['units']);
  1490. if ($result >= 0) {
  1491. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1492. // Define output language
  1493. $outputlangs = $langs;
  1494. $newlang = '';
  1495. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id'))
  1496. $newlang = GETPOST('lang_id');
  1497. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  1498. $newlang = $object->thirdparty->default_lang;
  1499. if (! empty($newlang)) {
  1500. $outputlangs = new Translate("", $conf);
  1501. $outputlangs->setDefaultLang($newlang);
  1502. }
  1503. $ret = $object->fetch($id); // Reload to get new records
  1504. $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1505. }
  1506. unset($_POST['qty']);
  1507. unset($_POST['type']);
  1508. unset($_POST['productid']);
  1509. unset($_POST['remise_percent']);
  1510. unset($_POST['price_ht']);
  1511. unset($_POST['multicurrency_price_ht']);
  1512. unset($_POST['price_ttc']);
  1513. unset($_POST['tva_tx']);
  1514. unset($_POST['product_ref']);
  1515. unset($_POST['product_label']);
  1516. unset($_POST['product_desc']);
  1517. unset($_POST['fournprice']);
  1518. unset($_POST['buying_price']);
  1519. unset($_POST['np_marginRate']);
  1520. unset($_POST['np_markRate']);
  1521. unset($_POST['dp_desc']);
  1522. unset($_POST['idprod']);
  1523. unset($_POST['units']);
  1524. unset($_POST['date_starthour']);
  1525. unset($_POST['date_startmin']);
  1526. unset($_POST['date_startsec']);
  1527. unset($_POST['date_startday']);
  1528. unset($_POST['date_startmonth']);
  1529. unset($_POST['date_startyear']);
  1530. unset($_POST['date_endhour']);
  1531. unset($_POST['date_endmin']);
  1532. unset($_POST['date_endsec']);
  1533. unset($_POST['date_endday']);
  1534. unset($_POST['date_endmonth']);
  1535. unset($_POST['date_endyear']);
  1536. unset($_POST['situations']);
  1537. unset($_POST['progress']);
  1538. } else {
  1539. setEventMessages($object->error, $object->errors, 'errors');
  1540. }
  1541. }
  1542. }
  1543. else if ($action == 'updatealllines' && $user->rights->facture->creer && $_POST['all_percent'] == $langs->trans('Modifier'))
  1544. {
  1545. if (!$object->fetch($id) > 0) dol_print_error($db);
  1546. if (!is_null(GETPOST('all_progress')) && GETPOST('all_progress') != "")
  1547. {
  1548. foreach ($object->lines as $line)
  1549. {
  1550. $percent = $line->get_prev_progress($object->id);
  1551. if (GETPOST('all_progress') < $percent) {
  1552. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  1553. $result = -1;
  1554. } else
  1555. $object->update_percent($line, $_POST['all_progress']);
  1556. }
  1557. }
  1558. }
  1559. else if ($action == 'updateligne' && $user->rights->facture->creer && $_POST['cancel'] == $langs->trans('Cancel')) {
  1560. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); // Pour reaffichage de la fiche en cours d'edition
  1561. exit();
  1562. }
  1563. /*
  1564. * Send mail
  1565. */
  1566. // Actions to send emails
  1567. if (empty($id)) $id=$facid;
  1568. $actiontypecode='AC_FAC';
  1569. $trigger_name='BILL_SENTBYMAIL';
  1570. $paramname='id';
  1571. $mode='emailfrominvoice';
  1572. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  1573. // Actions to build doc
  1574. $upload_dir = $conf->facture->dir_output;
  1575. $permissioncreate=$user->rights->facture->creer;
  1576. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  1577. if ($action == 'update_extras') {
  1578. // Fill array 'array_options' with data from add form
  1579. $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
  1580. $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute'));
  1581. if ($ret < 0) $error++;
  1582. if (! $error) {
  1583. // Actions on extra fields (by external module or standard code)
  1584. // TODO le hook fait double emploi avec le trigger !!
  1585. $hookmanager->initHooks(array('invoicedao'));
  1586. $parameters = array('id' => $object->id);
  1587. $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by
  1588. // some hooks
  1589. if (empty($reshook)) {
  1590. $result = $object->insertExtraFields();
  1591. if ($result < 0) {
  1592. $error ++;
  1593. }
  1594. } else if ($reshook < 0)
  1595. $error ++;
  1596. }
  1597. if ($error)
  1598. $action = 'edit_extras';
  1599. }
  1600. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  1601. if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->facture->creer) {
  1602. if ($action == 'addcontact') {
  1603. $result = $object->fetch($id);
  1604. if ($result > 0 && $id > 0) {
  1605. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  1606. $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
  1607. }
  1608. if ($result >= 0) {
  1609. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1610. exit();
  1611. } else {
  1612. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1613. $langs->load("errors");
  1614. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  1615. } else {
  1616. setEventMessages($object->error, $object->errors, 'errors');
  1617. }
  1618. }
  1619. } // bascule du statut d'un contact
  1620. elseif ($action == 'swapstatut') {
  1621. if ($object->fetch($id)) {
  1622. $result = $object->swapContactStatus(GETPOST('ligne'));
  1623. } else {
  1624. dol_print_error($db);
  1625. }
  1626. } // Efface un contact
  1627. elseif ($action == 'deletecontact') {
  1628. $object->fetch($id);
  1629. $result = $object->delete_contact($lineid);
  1630. if ($result >= 0) {
  1631. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1632. exit();
  1633. } else {
  1634. dol_print_error($db);
  1635. }
  1636. }
  1637. if ($error)
  1638. $action = 'edit_extras';
  1639. }
  1640. }
  1641. /*
  1642. * View
  1643. */
  1644. $form = new Form($db);
  1645. $formother = new FormOther($db);
  1646. $formfile = new FormFile($db);
  1647. $formmargin = new FormMargin($db);
  1648. $paymentstatic=new Paiement($db);
  1649. $bankaccountstatic = new Account($db);
  1650. if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
  1651. $now = dol_now();
  1652. llxHeader('', $langs->trans('Bill'), 'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes');
  1653. // Mode creation
  1654. if ($action == 'create')
  1655. {
  1656. $facturestatic = new Facture($db);
  1657. $extralabels = $extrafields->fetch_name_optionals_label($facturestatic->table_element);
  1658. print load_fiche_titre($langs->trans('NewBill'));
  1659. $soc = new Societe($db);
  1660. if ($socid > 0)
  1661. $res = $soc->fetch($socid);
  1662. $currency_code = $conf->currency;
  1663. // Load objectsrc
  1664. $remise_absolue = 0;
  1665. if (! empty($origin) && ! empty($originid))
  1666. {
  1667. // Parse element/subelement (ex: project_task)
  1668. $element = $subelement = $origin;
  1669. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  1670. $element = $regs [1];
  1671. $subelement = $regs [2];
  1672. }
  1673. if ($element == 'project') {
  1674. $projectid = $originid;
  1675. if (!$cond_reglement_id) {
  1676. $cond_reglement_id = $soc->cond_reglement_id;
  1677. }
  1678. if (!$mode_reglement_id) {
  1679. $mode_reglement_id = $soc->mode_reglement_id;
  1680. }
  1681. if (!$remise_percent) {
  1682. $remise_percent = $soc->remise_percent;
  1683. }
  1684. if (!$dateinvoice) {
  1685. // Do not set 0 here (0 for a date is 1970)
  1686. $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice);
  1687. }
  1688. } else {
  1689. // For compatibility
  1690. if ($element == 'order' || $element == 'commande') {
  1691. $element = $subelement = 'commande';
  1692. }
  1693. if ($element == 'propal') {
  1694. $element = 'comm/propal';
  1695. $subelement = 'propal';
  1696. }
  1697. if ($element == 'contract') {
  1698. $element = $subelement = 'contrat';
  1699. }
  1700. if ($element == 'shipping') {
  1701. $element = $subelement = 'expedition';
  1702. }
  1703. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  1704. $classname = ucfirst($subelement);
  1705. $objectsrc = new $classname($db);
  1706. $objectsrc->fetch($originid);
  1707. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines'))
  1708. $objectsrc->fetch_lines();
  1709. $objectsrc->fetch_thirdparty();
  1710. $projectid = (! empty($projectid) ? $projectid : $objectsrc->fk_project);
  1711. $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : (! empty($objectsrc->ref_customer) ? $objectsrc->ref_customer:''));
  1712. $ref_int = (! empty($objectsrc->ref_int) ? $objectsrc->ref_int : '');
  1713. // only if socid not filled else it's allready done upper
  1714. if (empty($socid))
  1715. $soc = $objectsrc->thirdparty;
  1716. $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1));
  1717. $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
  1718. $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0));
  1719. $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0));
  1720. $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0));
  1721. $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice);
  1722. if (!empty($conf->multicurrency->enabled))
  1723. {
  1724. if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code;
  1725. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx;
  1726. }
  1727. // Replicate extrafields
  1728. $objectsrc->fetch_optionals($originid);
  1729. $object->array_options = $objectsrc->array_options;
  1730. }
  1731. }
  1732. else
  1733. {
  1734. $cond_reglement_id = $soc->cond_reglement_id;
  1735. $mode_reglement_id = $soc->mode_reglement_id;
  1736. $fk_account = $soc->fk_account;
  1737. $remise_percent = $soc->remise_percent;
  1738. $remise_absolue = 0;
  1739. $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); // Do not set 0 here (0 for a date is 1970)
  1740. if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code;
  1741. }
  1742. if(!empty($soc->id)) $absolute_discount = $soc->getAvailableDiscounts();
  1743. if (! empty($conf->use_javascript_ajax))
  1744. {
  1745. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1746. print ajax_combobox('fac_replacement');
  1747. print ajax_combobox('fac_avoir');
  1748. print ajax_combobox('situations');
  1749. }
  1750. if ($origin == 'contrat')
  1751. {
  1752. $langs->load("admin");
  1753. $text=$langs->trans("ToCreateARecurringInvoice");
  1754. $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates"));
  1755. if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE))
  1756. {
  1757. $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
  1758. }
  1759. print info_admin($text, 0, 0, 0).'<br>';
  1760. }
  1761. print '<form name="add" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
  1762. print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
  1763. print '<input type="hidden" name="action" value="add">';
  1764. if ($soc->id > 0) print '<input type="hidden" name="socid" value="' . $soc->id . '">' . "\n";
  1765. print '<input name="facnumber" type="hidden" value="provisoire">';
  1766. print '<input name="ref_client" type="hidden" value="' . $ref_client . '">';
  1767. print '<input name="ref_int" type="hidden" value="' . $ref_int . '">';
  1768. print '<input type="hidden" name="origin" value="' . $origin . '">';
  1769. print '<input type="hidden" name="originid" value="' . $originid . '">';
  1770. if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="' . $currency_tx . '">';
  1771. dol_fiche_head('');
  1772. print '<table class="border" width="100%">';
  1773. // Ref
  1774. print '<tr><td class="titlefieldcreate fieldrequired">' . $langs->trans('Ref') . '</td><td colspan="2">' . $langs->trans('Draft') . '</td></tr>';
  1775. // Thirdparty
  1776. print '<td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
  1777. if ($soc->id > 0 && ! GETPOST('fac_rec'))
  1778. {
  1779. print '<td colspan="2">';
  1780. print $soc->getNomUrl(1);
  1781. print '<input type="hidden" name="socid" value="' . $soc->id . '">';
  1782. // Outstanding Bill
  1783. $outstandingBills = $soc->get_OutstandingBill();
  1784. print ' (' . $langs->trans('CurrentOutstandingBill') . ': ';
  1785. print price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency);
  1786. if ($soc->outstanding_limit != '')
  1787. {
  1788. if ($outstandingBills > $soc->outstanding_limit) print img_warning($langs->trans("OutstandingBillReached"));
  1789. print ' / ' . price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
  1790. }
  1791. print ')';
  1792. print '</td>';
  1793. }
  1794. else
  1795. {
  1796. print '<td colspan="2">';
  1797. print $form->select_company($soc->id, 'socid', '(s.client = 1 OR s.client = 3) AND status=1', 'SelectThirdParty');
  1798. // Option to reload page to retrieve customer informations. Note, this clear other input
  1799. if (!empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE))
  1800. {
  1801. print '<script type="text/javascript">
  1802. $(document).ready(function() {
  1803. $("#socid").change(function() {
  1804. var socid = $(this).val();
  1805. var fac_rec = $(\'#fac_rec\').val();
  1806. // reload page
  1807. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  1808. });
  1809. });
  1810. </script>';
  1811. }
  1812. print '</td>';
  1813. }
  1814. print '</tr>' . "\n";
  1815. // Predefined invoices
  1816. if (empty($origin) && empty($originid) && GETPOST('fac_rec','int') > 0)
  1817. {
  1818. $invoice_predefined = new FactureRec($db);
  1819. $invoice_predefined->fetch(GETPOST('fac_rec','int'));
  1820. $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
  1821. $sql = 'SELECT r.rowid, r.titre, r.total_ttc';
  1822. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as r';
  1823. $sql .= ' WHERE r.fk_soc = ' . $invoice_predefined->socid;
  1824. $resql = $db->query($sql);
  1825. if ($resql)
  1826. {
  1827. $num = $db->num_rows($resql);
  1828. $i = 0;
  1829. if ($num > 0)
  1830. {
  1831. print '<tr><td>' . $langs->trans('CreateFromRepeatableInvoice') . '</td><td>';
  1832. print '<select class="flat" id="fac_rec" name="fac_rec">';
  1833. print '<option value="0" selected></option>';
  1834. while ($i < $num)
  1835. {
  1836. $objp = $db->fetch_object($resql);
  1837. print '<option value="' . $objp->rowid . '"';
  1838. if (GETPOST('fac_rec') == $objp->rowid)
  1839. print ' selected';
  1840. print '>' . $objp->titre . ' (' . price($objp->total_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  1841. $i ++;
  1842. }
  1843. print '</select>';
  1844. // Option to reload page to retrieve customer informations. Note, this clear other input
  1845. if (!empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE))
  1846. {
  1847. print '<script type="text/javascript">
  1848. $(document).ready(function() {
  1849. $("#fac_rec").change(function() {
  1850. var fac_rec = $(this).val();
  1851. var socid = $(\'#socid\').val();
  1852. // reload page
  1853. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  1854. });
  1855. });
  1856. </script>';
  1857. }
  1858. print '</td></tr>';
  1859. }
  1860. $db->free($resql);
  1861. } else {
  1862. dol_print_error($db);
  1863. }
  1864. }
  1865. // Type de facture
  1866. $facids = $facturestatic->list_replacable_invoices($soc->id);
  1867. if ($facids < 0) {
  1868. dol_print_error($db, $facturestatic);
  1869. exit();
  1870. }
  1871. $options = "";
  1872. foreach ($facids as $facparam)
  1873. {
  1874. $options .= '<option value="' . $facparam ['id'] . '"';
  1875. if ($facparam ['id'] == $_POST['fac_replacement'])
  1876. $options .= ' selected';
  1877. $options .= '>' . $facparam ['ref'];
  1878. $options .= ' (' . $facturestatic->LibStatut(0, $facparam ['status']) . ')';
  1879. $options .= '</option>';
  1880. }
  1881. // Show link for credit note
  1882. $facids=$facturestatic->list_qualified_avoir_invoices($soc->id);
  1883. if ($facids < 0)
  1884. {
  1885. dol_print_error($db,$facturestatic);
  1886. exit;
  1887. }
  1888. $optionsav = "";
  1889. $newinvoice_static = new Facture($db);
  1890. foreach ($facids as $key => $valarray)
  1891. {
  1892. $newinvoice_static->id = $key;
  1893. $newinvoice_static->ref = $valarray ['ref'];
  1894. $newinvoice_static->statut = $valarray ['status'];
  1895. $newinvoice_static->type = $valarray ['type'];
  1896. $newinvoice_static->paye = $valarray ['paye'];
  1897. $optionsav .= '<option value="' . $key . '"';
  1898. if ($key == GETPOST('fac_avoir'))
  1899. $optionsav .= ' selected';
  1900. $optionsav .= '>';
  1901. $optionsav .= $newinvoice_static->ref;
  1902. $optionsav .= ' (' . $newinvoice_static->getLibStatut(1, $valarray ['paymentornot']) . ')';
  1903. $optionsav .= '</option>';
  1904. }
  1905. print '<tr><td valign="top" class="fieldrequired">' . $langs->trans('Type') . '</td><td colspan="2">';
  1906. print '<div class="tagtable">' . "\n";
  1907. // Standard invoice
  1908. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1909. $tmp='<input type="radio" id="radio_standard" name="type" value="0"' . (GETPOST('type') == 0 ? ' checked' : '') . '> ';
  1910. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
  1911. print $desc;
  1912. print '</div></div>';
  1913. if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (! empty($originid))))
  1914. {
  1915. // Deposit
  1916. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1917. $tmp='<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
  1918. print '<script type="text/javascript" language="javascript">
  1919. jQuery(document).ready(function() {
  1920. jQuery("#typedeposit, #valuedeposit").click(function() {
  1921. jQuery("#radio_deposit").prop("checked", true);
  1922. });
  1923. });
  1924. </script>';
  1925. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
  1926. print '<table class="nobordernopadding"><tr><td>';
  1927. print $desc;
  1928. print '</td>';
  1929. if (($origin == 'propal') || ($origin == 'commande'))
  1930. {
  1931. print '<td class="nowrap" style="padding-left: 5px">';
  1932. $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount');
  1933. print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1);
  1934. print '</td>';
  1935. print '<td class="nowrap" style="padding-left: 5px">' . $langs->trans('Value') . ':<input type="text" id="valuedeposit" name="valuedeposit" size="3" value="' . GETPOST('valuedeposit', 'int') . '"/>';
  1936. }
  1937. print '</td></tr></table>';
  1938. print '</div></div>';
  1939. }
  1940. if ($socid > 0)
  1941. {
  1942. if (! empty($conf->global->INVOICE_USE_SITUATION))
  1943. {
  1944. // First situation invoice
  1945. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1946. $tmp='<input type="radio" name="type" value="5"' . (GETPOST('type') == 5 ? ' checked' : '') . '> ';
  1947. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceFirstSituationAsk"), $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3);
  1948. print $desc;
  1949. print '</div></div>';
  1950. // Next situation invoice
  1951. $opt = $form->selectSituationInvoices(GETPOST('originid'), $socid);
  1952. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1953. $tmp='<input type="radio" name="type" value="5"' . (GETPOST('type') == 5 && GETPOST('originid') ? ' checked' : '');
  1954. if ($opt == ('<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) $tmp.=' disabled';
  1955. $tmp.= '> ';
  1956. $text = $tmp.$langs->trans("InvoiceSituationAsk") . ' ';
  1957. $text .= '<select class="flat" id="situations" name="situations">';
  1958. $text .= $opt;
  1959. $text .= '</select>';
  1960. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceSituationDesc"), 1, 'help', '', 0, 3);
  1961. print $desc;
  1962. print '</div></div>';
  1963. }
  1964. // Replacement
  1965. print '<!-- replacement line --><div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1966. $tmp='<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
  1967. if (! $options) $tmp.=' disabled';
  1968. $tmp.='> ';
  1969. print '<script type="text/javascript" language="javascript">
  1970. jQuery(document).ready(function() {
  1971. jQuery("#fac_replacement").change(function() {
  1972. jQuery("#radio_replacement").prop("checked", true);
  1973. });
  1974. });
  1975. </script>';
  1976. $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' ';
  1977. $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
  1978. if (! $options)
  1979. $text .= ' disabled';
  1980. $text .= '>';
  1981. if ($options) {
  1982. $text .= '<option value="-1">&nbsp;</option>';
  1983. $text .= $options;
  1984. } else {
  1985. $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
  1986. }
  1987. $text .= '</select>';
  1988. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  1989. print $desc;
  1990. print '</div></div>';
  1991. }
  1992. else
  1993. {
  1994. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1995. $tmp='<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
  1996. $text = $tmp.$langs->trans("InvoiceReplacement") . ' ';
  1997. $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') ';
  1998. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  1999. print $desc;
  2000. print '</div></div>';
  2001. }
  2002. if (empty($origin))
  2003. {
  2004. if ($socid > 0)
  2005. {
  2006. // Credit note
  2007. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2008. $tmp='<input type="radio" id="radio_creditnote" name="type" value="2"' . (GETPOST('type') == 2 ? ' checked' : '');
  2009. if (! $optionsav) $tmp.=' disabled';
  2010. $tmp.= '> ';
  2011. // Show credit note options only if we checked credit note
  2012. print '<script type="text/javascript" language="javascript">
  2013. jQuery(document).ready(function() {
  2014. if (! jQuery("#radio_creditnote").is(":checked"))
  2015. {
  2016. jQuery("#credit_note_options").hide();
  2017. }
  2018. jQuery("#radio_creditnote").click(function() {
  2019. jQuery("#credit_note_options").show();
  2020. });
  2021. jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
  2022. jQuery("#credit_note_options").hide();
  2023. });
  2024. });
  2025. </script>';
  2026. $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' ';
  2027. // $text.='<input type="text" value="">';
  2028. $text .= '<select class="flat" name="fac_avoir" id="fac_avoir"';
  2029. if (! $optionsav)
  2030. $text .= ' disabled';
  2031. $text .= '>';
  2032. if ($optionsav) {
  2033. $text .= '<option value="-1"></option>';
  2034. $text .= $optionsav;
  2035. } else {
  2036. $text .= '<option value="-1">' . $langs->trans("NoInvoiceToCorrect") . '</option>';
  2037. }
  2038. $text .= '</select>';
  2039. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  2040. print $desc;
  2041. print '<div id="credit_note_options" class="clearboth">';
  2042. print '&nbsp;&nbsp;&nbsp; <input data-role="none" 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':'').' /> <label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
  2043. print '<br>&nbsp;&nbsp;&nbsp; <input data-role="none" 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':'').' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  2044. print '</div>';
  2045. print '</div></div>';
  2046. }
  2047. else
  2048. {
  2049. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2050. $tmp='<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
  2051. $text = $tmp.$langs->trans("InvoiceAvoir") . ' ';
  2052. $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') ';
  2053. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  2054. print $desc;
  2055. print '</div></div>' . "\n";
  2056. }
  2057. }
  2058. // Template invoice
  2059. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2060. $tmp='<input type="radio" name="type" id="radio_template" value="0" disabled> ';
  2061. $text = $tmp.$langs->trans("RepeatableInvoice") . ' ';
  2062. //$text.= '('.$langs->trans("YouMustCreateStandardInvoiceFirst").') ';
  2063. $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3);
  2064. print $desc;
  2065. print '</div></div>';
  2066. print '</div>';
  2067. print '</td></tr>';
  2068. if ($socid > 0)
  2069. {
  2070. // Discounts for third party
  2071. print '<tr><td>' . $langs->trans('Discounts') . '</td><td colspan="2">';
  2072. if ($soc->remise_percent)
  2073. print $langs->trans("CompanyHasRelativeDiscount", '<a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">' . $soc->remise_percent . '</a>');
  2074. else
  2075. print $langs->trans("CompanyHasNoRelativeDiscount");
  2076. print ' <a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">(' . $langs->trans("EditRelativeDiscount") . ')</a>';
  2077. print '. ';
  2078. print '<br>';
  2079. if ($absolute_discount)
  2080. print $langs->trans("CompanyHasAbsoluteDiscount", '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">' . price($absolute_discount) . '</a>', $langs->trans("Currency" . $conf->currency));
  2081. else
  2082. print $langs->trans("CompanyHasNoAbsoluteDiscount");
  2083. print ' <a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">(' . $langs->trans("EditGlobalDiscounts") . ')</a>';
  2084. print '.';
  2085. print '</td></tr>';
  2086. }
  2087. // Date invoice
  2088. print '<tr><td class="fieldrequired">' . $langs->trans('Date') . '</td><td colspan="2">';
  2089. $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
  2090. print $form->select_date($datefacture?$datefacture:$dateinvoice, '', '', '', '', "add", 1, 1, 1);
  2091. print '</td></tr>';
  2092. // Date point of tax
  2093. if (! empty($conf->global->INVOICE_POINTOFTAX_DATE))
  2094. {
  2095. print '<tr><td class="fieldrequired">' . $langs->trans('DatePointOfTax') . '</td><td colspan="2">';
  2096. $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
  2097. print $form->select_date($date_pointoftax?$date_pointoftax:-1, 'date_pointoftax', '', '', '', "add", 1, 1, 1);
  2098. print '</td></tr>';
  2099. }
  2100. // Payment term
  2101. print '<tr><td class="nowrap">' . $langs->trans('PaymentConditionsShort') . '</td><td colspan="2">';
  2102. $form->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id');
  2103. print '</td></tr>';
  2104. // Payment mode
  2105. print '<tr><td>' . $langs->trans('PaymentMode') . '</td><td colspan="2">';
  2106. $form->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id', 'CRDT');
  2107. print '</td></tr>';
  2108. // Bank Account
  2109. if (isset($_POST['fk_account'])) {
  2110. $fk_account = $_POST['fk_account'];
  2111. }
  2112. print '<tr><td>' . $langs->trans('BankAccount') . '</td><td colspan="2">';
  2113. $form->select_comptes($fk_account, 'fk_account', 0, '', 1);
  2114. print '</td></tr>';
  2115. // Project
  2116. if (! empty($conf->projet->enabled) && $socid > 0)
  2117. {
  2118. $langs->load('projects');
  2119. print '<tr><td>' . $langs->trans('Project') . '</td><td colspan="2">';
  2120. $numprojet = $formproject->select_projects($socid, $projectid, 'projectid', 0);
  2121. print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid=' . $soc->id . '&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id.($fac_rec?'&fac_rec='.$fac_rec:'')).'">' . $langs->trans("AddProject") . '</a>';
  2122. print '</td></tr>';
  2123. }
  2124. // Incoterms
  2125. if (!empty($conf->incoterm->enabled))
  2126. {
  2127. print '<tr>';
  2128. print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $objectsrc->libelle_incoterms, 1).'</label></td>';
  2129. print '<td colspan="2" class="maxwidthonsmartphone">';
  2130. print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:''));
  2131. print '</td></tr>';
  2132. }
  2133. // Other attributes
  2134. $parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"');
  2135. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by
  2136. // hook
  2137. if (empty($reshook) && ! empty($extrafields->attribute_label)) {
  2138. print $object->showOptionals($extrafields, 'edit');
  2139. }
  2140. // Template to use by default
  2141. print '<tr><td>' . $langs->trans('Model') . '</td>';
  2142. print '<td colspan="2">';
  2143. include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
  2144. $liste = ModelePDFFactures::liste_modeles($db);
  2145. print $form->selectarray('model', $liste, $conf->global->FACTURE_ADDON_PDF);
  2146. print "</td></tr>";
  2147. // Multicurrency
  2148. if (! empty($conf->multicurrency->enabled))
  2149. {
  2150. print '<tr>';
  2151. print '<td>'.fieldLabel('Currency','multicurrency_code').'</td>';
  2152. print '<td colspan="2" class="maxwidthonsmartphone">';
  2153. print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
  2154. print '</td></tr>';
  2155. }
  2156. // Public note
  2157. print '<tr>';
  2158. print '<td class="border" valign="top">' . $langs->trans('NotePublic') . '</td>';
  2159. print '<td valign="top" colspan="2">';
  2160. $note_public = $object->getDefaultCreateValueFor('note_public', (is_object($objectsrc)?$objectsrc->note_public:null));
  2161. $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
  2162. print $doleditor->Create(1);
  2163. // Private note
  2164. if (empty($user->societe_id))
  2165. {
  2166. print '<tr>';
  2167. print '<td class="border" valign="top">' . $langs->trans('NotePrivate') . '</td>';
  2168. print '<td valign="top" colspan="2">';
  2169. $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null));
  2170. $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
  2171. print $doleditor->Create(1);
  2172. // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
  2173. print '</td></tr>';
  2174. }
  2175. // Lines from source
  2176. if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
  2177. {
  2178. // TODO for compatibility
  2179. if ($origin == 'contrat') {
  2180. // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
  2181. $objectsrc->remise_absolue = $remise_absolue;
  2182. $objectsrc->remise_percent = $remise_percent;
  2183. $objectsrc->update_price(1, - 1, 1);
  2184. }
  2185. print "\n<!-- " . $classname . " info -->";
  2186. print "\n";
  2187. print '<input type="hidden" name="amount" value="' . $objectsrc->total_ht . '">' . "\n";
  2188. print '<input type="hidden" name="total" value="' . $objectsrc->total_ttc . '">' . "\n";
  2189. print '<input type="hidden" name="tva" value="' . $objectsrc->total_tva . '">' . "\n";
  2190. print '<input type="hidden" name="origin" value="' . $objectsrc->element . '">';
  2191. print '<input type="hidden" name="originid" value="' . $objectsrc->id . '">';
  2192. switch ($classname) {
  2193. case 'Propal':
  2194. $newclassname = 'CommercialProposal';
  2195. break;
  2196. case 'Commande':
  2197. $newclassname = 'Order';
  2198. break;
  2199. case 'Expedition':
  2200. $newclassname = 'Sending';
  2201. break;
  2202. case 'Contrat':
  2203. $newclassname = 'Contract';
  2204. break;
  2205. case 'Fichinter':
  2206. $newclassname = 'Intervention';
  2207. break;
  2208. default:
  2209. $newclassname = $classname;
  2210. }
  2211. print '<tr><td>' . $langs->trans($newclassname) . '</td><td colspan="2">' . $objectsrc->getNomUrl(1);
  2212. // We check if Origin document (id and type is known) has already at least one invoice attached to it
  2213. $objectsrc->fetchObjectLinked($originid,$origin,'','facture');
  2214. $cntinvoice=count($objectsrc->linkedObjects['facture']);
  2215. if ($cntinvoice>=1)
  2216. {
  2217. setEventMessages('WarningBillExist', null, 'warnings');
  2218. echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')';
  2219. }
  2220. echo '</td></tr>';
  2221. print '<tr><td>' . $langs->trans('TotalHT') . '</td><td colspan="2">' . price($objectsrc->total_ht) . '</td></tr>';
  2222. print '<tr><td>' . $langs->trans('TotalVAT') . '</td><td colspan="2">' . price($objectsrc->total_tva) . "</td></tr>";
  2223. if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1
  2224. {
  2225. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax1) . "</td></tr>";
  2226. }
  2227. if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2
  2228. {
  2229. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax2) . "</td></tr>";
  2230. }
  2231. print '<tr><td>' . $langs->trans('TotalTTC') . '</td><td colspan="2">' . price($objectsrc->total_ttc) . "</td></tr>";
  2232. if (!empty($conf->multicurrency->enabled))
  2233. {
  2234. print '<tr><td>' . $langs->trans('MulticurrencyTotalHT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ht) . '</td></tr>';
  2235. print '<tr><td>' . $langs->trans('MulticurrencyTotalVAT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_tva) . "</td></tr>";
  2236. print '<tr><td>' . $langs->trans('MulticurrencyTotalTTC') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>";
  2237. }
  2238. }
  2239. else
  2240. {
  2241. // Show deprecated optional form to add product line here
  2242. if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) {
  2243. print '<tr><td colspan="3">';
  2244. // Zone de choix des produits predefinis a la creation
  2245. print '<table class="noborder" width="100%">';
  2246. print '<tr>';
  2247. print '<td>' . $langs->trans('ProductsAndServices') . '</td>';
  2248. print '<td>' . $langs->trans('Qty') . '</td>';
  2249. print '<td>' . $langs->trans('ReductionShort') . '</td>';
  2250. print '<td> &nbsp; &nbsp; </td>';
  2251. if (! empty($conf->service->enabled)) {
  2252. print '<td>' . $langs->trans('ServiceLimitedDuration') . '</td>';
  2253. }
  2254. print '</tr>';
  2255. for($i = 1; $i <= $NBLINES; $i ++) {
  2256. print '<tr>';
  2257. print '<td>';
  2258. // multiprix
  2259. if (! empty($conf->global->PRODUIT_MULTIPRICES))
  2260. $form->select_produits('', 'idprod' . $i, '', $conf->product->limit_size, $soc->price_level);
  2261. else
  2262. $form->select_produits('', 'idprod' . $i, '', $conf->product->limit_size);
  2263. print '</td>';
  2264. print '<td><input type="text" size="2" name="qty' . $i . '" value="1"></td>';
  2265. print '<td class="nowrap"><input type="text" size="1" name="remise_percent' . $i . '" value="' . $soc->remise_percent . '">%</td>';
  2266. print '<td>&nbsp;</td>';
  2267. // Si le module service est actif, on propose des dates de debut et fin a la ligne
  2268. if (! empty($conf->service->enabled)) {
  2269. print '<td class="nowrap">';
  2270. print '<table class="nobordernopadding"><tr class="nocellnopadd">';
  2271. print '<td class="nobordernopadding nowrap">';
  2272. print $langs->trans('From') . ' ';
  2273. print '</td><td class="nobordernopadding nowrap">';
  2274. print $form->select_date('', 'date_start' . $i, $usehm, $usehm, 1, "add", 1, 0, 1);
  2275. print '</td></tr>';
  2276. print '<td class="nobordernopadding nowrap">';
  2277. print $langs->trans('to') . ' ';
  2278. print '</td><td class="nobordernopadding nowrap">';
  2279. print $form->select_date('', 'date_end' . $i, $usehm, $usehm, 1, "add", 1, 0, 1);
  2280. print '</td></tr></table>';
  2281. print '</td>';
  2282. }
  2283. print "</tr>\n";
  2284. }
  2285. print '</table>';
  2286. print '</td></tr>';
  2287. }
  2288. }
  2289. print "</table>\n";
  2290. dol_fiche_end();
  2291. // Button "Create Draft"
  2292. print '<div class="center">';
  2293. print '<input type="submit" class="button" name="bouton" value="' . $langs->trans('CreateDraft') . '">';
  2294. print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  2295. print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
  2296. print '</div>';
  2297. print "</form>\n";
  2298. // Show origin lines
  2299. if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) {
  2300. print '<br>';
  2301. $title = $langs->trans('ProductsAndServices');
  2302. print load_fiche_titre($title);
  2303. print '<table class="noborder" width="100%">';
  2304. $objectsrc->printOriginLinesList();
  2305. print '</table>';
  2306. }
  2307. print '<br>';
  2308. }
  2309. else if ($id > 0 || ! empty($ref))
  2310. {
  2311. /*
  2312. * Show object in view mode
  2313. */
  2314. $result = $object->fetch($id, $ref);
  2315. if ($result <= 0) {
  2316. dol_print_error($db, $object->error);
  2317. exit();
  2318. }
  2319. // fetch optionals attributes and labels
  2320. $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
  2321. if ($user->societe_id > 0 && $user->societe_id != $object->socid)
  2322. accessforbidden('', 0);
  2323. $result = $object->fetch_thirdparty();
  2324. $soc = new Societe($db);
  2325. $result=$soc->fetch($object->socid);
  2326. if ($result < 0) dol_print_error($db);
  2327. $selleruserevenustamp = $mysoc->useRevenueStamp();
  2328. $totalpaye = $object->getSommePaiement();
  2329. $totalcreditnotes = $object->getSumCreditNotesUsed();
  2330. $totaldeposits = $object->getSumDepositsUsed();
  2331. // print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
  2332. // selleruserrevenuestamp=".$selleruserevenustamp;
  2333. // We can also use bcadd to avoid pb with floating points
  2334. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  2335. // $resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2336. // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2337. $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
  2338. if ($object->paye)
  2339. $resteapayer = 0;
  2340. $resteapayeraffiche = $resteapayer;
  2341. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  2342. $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2343. $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2344. } else {
  2345. $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')";
  2346. $filtercreditnote = "fk_facture_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'";
  2347. }
  2348. $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
  2349. $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
  2350. $absolute_discount = price2num($absolute_discount, 'MT');
  2351. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  2352. $author = new User($db);
  2353. if ($object->user_author) {
  2354. $author->fetch($object->user_author);
  2355. }
  2356. $objectidnext = $object->getIdReplacingInvoice();
  2357. $head = facture_prepare_head($object);
  2358. dol_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), 0, 'bill');
  2359. $formconfirm = '';
  2360. // Confirmation de la conversion de l'avoir en reduc
  2361. if ($action == 'converttoreduc') {
  2362. $text = $langs->trans('ConfirmConvertToReduc');
  2363. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
  2364. }
  2365. // Confirmation to delete invoice
  2366. if ($action == 'delete') {
  2367. $text = $langs->trans('ConfirmDeleteBill', $object->ref);
  2368. $formquestion = array();
  2369. $qualified_for_stock_change = 0;
  2370. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2371. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2372. } else {
  2373. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2374. }
  2375. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change && $object->statut >= 1)
  2376. {
  2377. $langs->load("stocks");
  2378. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  2379. $formproduct = new FormProduct($db);
  2380. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  2381. $formquestion = array(
  2382. // 'text' => $langs->trans("ConfirmClone"),
  2383. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  2384. // 1),
  2385. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  2386. // => 1),
  2387. array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, $langs->trans("NoStockAction"))));
  2388. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
  2389. } else {
  2390. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', '', 1);
  2391. }
  2392. }
  2393. // Confirmation de la validation
  2394. if ($action == 'valid')
  2395. {
  2396. // on verifie si l'objet est en numerotation provisoire
  2397. $objectref = substr($object->ref, 1, 4);
  2398. if ($objectref == 'PROV') {
  2399. $savdate = $object->date;
  2400. if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
  2401. $object->date = dol_now();
  2402. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  2403. }
  2404. $numref = $object->getNextNumRef($soc);
  2405. // $object->date=$savdate;
  2406. } else {
  2407. $numref = $object->ref;
  2408. }
  2409. $text = $langs->trans('ConfirmValidateBill', $numref);
  2410. if (! empty($conf->notification->enabled)) {
  2411. require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
  2412. $notify = new Notify($db);
  2413. $text .= '<br>';
  2414. $text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
  2415. }
  2416. $formquestion = array();
  2417. $qualified_for_stock_change = 0;
  2418. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2419. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2420. } else {
  2421. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2422. }
  2423. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
  2424. {
  2425. $langs->load("stocks");
  2426. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  2427. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2428. $formproduct = new FormProduct($db);
  2429. $warehouse = new Entrepot($db);
  2430. $warehouse_array = $warehouse->list_array();
  2431. if (count($warehouse_array) == 1) {
  2432. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
  2433. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
  2434. } else {
  2435. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
  2436. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1);
  2437. }
  2438. $formquestion = array(
  2439. // 'text' => $langs->trans("ConfirmClone"),
  2440. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  2441. // 1),
  2442. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  2443. // => 1),
  2444. array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value));
  2445. }
  2446. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
  2447. {
  2448. $text .= '<br>' . img_warning() . ' ' . $langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
  2449. }
  2450. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, (($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) ? "no" : "yes"), 2);
  2451. }
  2452. // Confirm back to draft status
  2453. if ($action == 'modif') {
  2454. $text = $langs->trans('ConfirmUnvalidateBill', $object->ref);
  2455. $formquestion = array();
  2456. $qualified_for_stock_change = 0;
  2457. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2458. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2459. } else {
  2460. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2461. }
  2462. if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change) {
  2463. $langs->load("stocks");
  2464. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  2465. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2466. $formproduct = new FormProduct($db);
  2467. $warehouse = new Entrepot($db);
  2468. $warehouse_array = $warehouse->list_array();
  2469. if (count($warehouse_array) == 1) {
  2470. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
  2471. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
  2472. } else {
  2473. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  2474. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1);
  2475. }
  2476. $formquestion = array(
  2477. // 'text' => $langs->trans("ConfirmClone"),
  2478. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  2479. // 1),
  2480. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  2481. // => 1),
  2482. array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value));
  2483. }
  2484. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('UnvalidateBill'), $text, 'confirm_modif', $formquestion, "yes", 1);
  2485. }
  2486. // Confirmation du classement paye
  2487. if ($action == 'paid' && $resteapayer <= 0) {
  2488. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', "yes", 1);
  2489. }
  2490. if ($action == 'paid' && $resteapayer > 0) {
  2491. // Code
  2492. $i = 0;
  2493. $close [$i] ['code'] = 'discount_vat';
  2494. $i ++;
  2495. $close [$i] ['code'] = 'badcustomer';
  2496. $i ++;
  2497. // Help
  2498. $i = 0;
  2499. $close [$i] ['label'] = $langs->trans("HelpEscompte") . '<br><br>' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
  2500. $i ++;
  2501. $close [$i] ['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  2502. $i ++;
  2503. // Texte
  2504. $i = 0;
  2505. $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscountVat", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1);
  2506. $i ++;
  2507. $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1);
  2508. $i ++;
  2509. // arrayreasons[code]=reason
  2510. foreach ($close as $key => $val) {
  2511. $arrayreasons [$close [$key] ['code']] = $close [$key] ['reason'];
  2512. }
  2513. // Cree un tableau formulaire
  2514. $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' => '','size' => '100'));
  2515. // Paiement incomplet. On demande si motif = escompte ou autre
  2516. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes");
  2517. }
  2518. // Confirmation du classement abandonne
  2519. if ($action == 'canceled') {
  2520. // S'il y a une facture de remplacement pas encore validee (etat brouillon),
  2521. // on ne permet pas de classer abandonner la facture.
  2522. if ($objectidnext) {
  2523. $facturereplacement = new Facture($db);
  2524. $facturereplacement->fetch($objectidnext);
  2525. $statusreplacement = $facturereplacement->statut;
  2526. }
  2527. if ($objectidnext && $statusreplacement == 0) {
  2528. print '<div class="error">' . $langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated") . '</div>';
  2529. } else {
  2530. // Code
  2531. $close [1] ['code'] = 'badcustomer';
  2532. $close [2] ['code'] = 'abandon';
  2533. // Help
  2534. $close [1] ['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  2535. $close [2] ['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
  2536. // Texte
  2537. $close [1] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close [1] ['label'], 1);
  2538. $close [2] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close [2] ['label'], 1);
  2539. // arrayreasons
  2540. $arrayreasons [$close [1] ['code']] = $close [1] ['reason'];
  2541. $arrayreasons [$close [2] ['code']] = $close [2] ['reason'];
  2542. // Cree un tableau formulaire
  2543. $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' => '','size' => '100'));
  2544. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes");
  2545. }
  2546. }
  2547. // Confirmation de la suppression d'une ligne produit
  2548. if ($action == 'ask_deleteline') {
  2549. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
  2550. }
  2551. // Clone confirmation
  2552. if ($action == 'clone')
  2553. {
  2554. // Create an array for form
  2555. $formquestion = array(
  2556. // 'text' => $langs->trans("ConfirmClone"),
  2557. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1)
  2558. array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company($object->socid, 'socid', '(s.client=1 OR s.client=2 OR s.client=3)', 1)));
  2559. // Paiement incomplet. On demande si motif = escompte ou autre
  2560. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('CloneInvoice'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  2561. }
  2562. if (! $formconfirm)
  2563. {
  2564. $parameters = array('lineid' => $lineid);
  2565. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2566. if (empty($reshook)) $formconfirm.=$hookmanager->resPrint;
  2567. elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint;
  2568. }
  2569. // Print form confirm
  2570. print $formconfirm;
  2571. // Invoice content
  2572. print '<table class="border" width="100%">';
  2573. $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php' . (! empty($socid) ? '?socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
  2574. // Ref
  2575. print '<tr><td width="20%">' . $langs->trans('Ref') . '</td>';
  2576. print '<td colspan="5">';
  2577. $morehtmlright = '';
  2578. $discount = new DiscountAbsolute($db);
  2579. $result = $discount->fetch(0, $object->id);
  2580. if ($result > 0) {
  2581. $morehtmlright = '&nbsp; (' . $langs->trans("CreditNoteConvertedIntoDiscount", $discount->getNomUrl(1, 'discount')) . ')';
  2582. }
  2583. if ($result < 0) {
  2584. dol_print_error('', $discount->error);
  2585. }
  2586. print $form->showrefnav($object, 'ref', $linkback, 1, 'facnumber', 'ref', '', '', 0, '', '', $morehtmlright);
  2587. print '</td></tr>';
  2588. // Ref customer
  2589. print '<tr><td width="20%">';
  2590. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2591. print $langs->trans('RefCustomer');
  2592. print '</td>';
  2593. if ($action != 'refclient' && ! empty($object->brouillon))
  2594. print '<td align="right"><a href="' . $_SERVER['PHP_SELF'] . '?action=refclient&amp;id=' . $object->id . '">' . img_edit($langs->trans('Modify')) . '</a></td>';
  2595. print '</tr></table>';
  2596. print '</td>';
  2597. print '<td colspan="5">';
  2598. if ($user->rights->facture->creer && $action == 'refclient') {
  2599. print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
  2600. print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
  2601. print '<input type="hidden" name="action" value="set_ref_client">';
  2602. print '<input type="text" class="flat" size="20" name="ref_client" value="' . $object->ref_client . '">';
  2603. print ' <input type="submit" class="button" value="' . $langs->trans('Modify') . '">';
  2604. print '</form>';
  2605. } else {
  2606. print $object->ref_client;
  2607. }
  2608. print '</td></tr>';
  2609. // Third party
  2610. print '<tr><td>';
  2611. print '<table class="nobordernopadding" width="100%">';
  2612. print '<tr><td>' . $langs->trans('Company') . '</td>';
  2613. print '</td><td colspan="5">';
  2614. if (! empty($conf->global->FACTURE_CHANGE_THIRDPARTY) && $action != 'editthirdparty' && $object->brouillon && $user->rights->facture->creer)
  2615. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editthirdparty&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetLinkToAnotherThirdParty'), 1) . '</a></td>';
  2616. print '</tr></table>';
  2617. print '</td><td colspan="5">';
  2618. if ($action == 'editthirdparty') {
  2619. $form->form_thirdparty($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, 'socid','client>0');
  2620. } else {
  2621. print ' &nbsp;' . $soc->getNomUrl(1, 'compta');
  2622. print ' &nbsp; ';
  2623. print '(<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?socid=' . $object->socid . '">' . $langs->trans('OtherBills') . '</a>';
  2624. // Outstanding Bill
  2625. $outstandingBills = $soc->get_OutstandingBill();
  2626. print ' - ' . $langs->trans('CurrentOutstandingBill') . ': ';
  2627. print price($outstandingBills, '', $langs, 0, 0, - 1, $conf->currency);
  2628. if ($soc->outstanding_limit != '')
  2629. {
  2630. if ($outstandingBills > $soc->outstanding_limit)
  2631. print img_warning($langs->trans("OutstandingBillReached"));
  2632. print ' / ' . price($soc->outstanding_limit);
  2633. }
  2634. print ')';
  2635. }
  2636. print '</tr>';
  2637. // Type
  2638. print '<tr><td>' . $langs->trans('Type') . '</td><td colspan="5">';
  2639. print $object->getLibType();
  2640. if ($object->type == Facture::TYPE_REPLACEMENT) {
  2641. $facreplaced = new Facture($db);
  2642. $facreplaced->fetch($object->fk_facture_source);
  2643. print ' (' . $langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)) . ')';
  2644. }
  2645. if ($object->type == Facture::TYPE_CREDIT_NOTE && !empty($object->fk_facture_source)) {
  2646. $facusing = new Facture($db);
  2647. $facusing->fetch($object->fk_facture_source);
  2648. print ' (' . $langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)) . ')';
  2649. }
  2650. $facidavoir = $object->getListIdAvoirFromInvoice();
  2651. if (count($facidavoir) > 0) {
  2652. print ' (' . $langs->transnoentities("InvoiceHasAvoir");
  2653. $i = 0;
  2654. foreach ($facidavoir as $id) {
  2655. if ($i == 0)
  2656. print ' ';
  2657. else
  2658. print ',';
  2659. $facavoir = new Facture($db);
  2660. $facavoir->fetch($id);
  2661. print $facavoir->getNomUrl(1);
  2662. }
  2663. print ')';
  2664. }
  2665. if ($objectidnext > 0) {
  2666. $facthatreplace = new Facture($db);
  2667. $facthatreplace->fetch($objectidnext);
  2668. print ' (' . $langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)) . ')';
  2669. }
  2670. print '</td></tr>';
  2671. // Relative and absolute discounts
  2672. $addrelativediscount = '<a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("EditRelativeDiscounts") . '</a>';
  2673. $addabsolutediscount = '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("EditGlobalDiscounts") . '</a>';
  2674. $addcreditnote = '<a href="' . DOL_URL_ROOT . '/compta/facture.php?action=create&socid=' . $soc->id . '&type=2&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("AddCreditNote") . '</a>';
  2675. print '<tr><td>' . $langs->trans('Discounts');
  2676. print '</td><td colspan="5">';
  2677. if ($soc->remise_percent)
  2678. print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
  2679. else
  2680. print $langs->trans("CompanyHasNoRelativeDiscount");
  2681. // print ' ('.$addrelativediscount.')';
  2682. if ($absolute_discount > 0) {
  2683. print '. ';
  2684. if ($object->statut > 0 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  2685. if ($object->statut == 0) {
  2686. print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
  2687. print '. ';
  2688. } else {
  2689. if ($object->statut < 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  2690. $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
  2691. print '<br>' . $text . '.<br>';
  2692. } else {
  2693. $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
  2694. $text2 = $langs->trans("AbsoluteDiscountUse");
  2695. print $form->textwithpicto($text, $text2);
  2696. }
  2697. }
  2698. } else {
  2699. // Remise dispo de type remise fixe (not credit note)
  2700. print '<br>';
  2701. $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')');
  2702. }
  2703. } else {
  2704. if ($absolute_creditnote > 0) // If not, link will be added later
  2705. {
  2706. if ($object->statut == 0 && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT)
  2707. print ' (' . $addabsolutediscount . ')<br>';
  2708. else
  2709. print '. ';
  2710. } else
  2711. print '. ';
  2712. }
  2713. if ($absolute_creditnote > 0)
  2714. {
  2715. // If validated, we show link "add credit note to payment"
  2716. if ($object->statut != 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  2717. if ($object->statut == 0 && $object->type != Facture::TYPE_DEPOSIT) {
  2718. $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency));
  2719. print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse"));
  2720. } else {
  2721. print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.';
  2722. }
  2723. } else {
  2724. // Remise dispo de type avoir
  2725. if (! $absolute_discount)
  2726. print '<br>';
  2727. // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer
  2728. $more=' ('.$addcreditnote.')';
  2729. $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0, $more); // We allow credit note even if amount is higher
  2730. }
  2731. }
  2732. if (! $absolute_discount && ! $absolute_creditnote) {
  2733. print $langs->trans("CompanyHasNoAbsoluteDiscount");
  2734. if ($object->statut == 0 && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT)
  2735. print ' (' . $addabsolutediscount . ')<br>';
  2736. else
  2737. print '. ';
  2738. }
  2739. // if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
  2740. // {
  2741. // if (! $absolute_discount && ! $absolute_creditnote) print '<br>';
  2742. // print ' &nbsp; - &nbsp; ';
  2743. // print $addabsolutediscount;
  2744. // print ' &nbsp; - &nbsp; '.$addcreditnote; // We disbale link to credit note
  2745. // }
  2746. print '</td></tr>';
  2747. // Date invoice
  2748. print '<tr><td>';
  2749. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2750. print $langs->trans('Date');
  2751. print '</td>';
  2752. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editinvoicedate' && ! empty($object->brouillon) && $user->rights->facture->creer && empty($conf->global->FAC_FORCE_DATE_VALIDATION))
  2753. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editinvoicedate&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  2754. print '</tr></table>';
  2755. print '</td><td colspan="3">';
  2756. if ($object->type != Facture::TYPE_CREDIT_NOTE) {
  2757. if ($action == 'editinvoicedate') {
  2758. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date, 'invoicedate');
  2759. } else {
  2760. print dol_print_date($object->date, 'daytext');
  2761. }
  2762. } else {
  2763. print dol_print_date($object->date, 'daytext');
  2764. }
  2765. print '</td>';
  2766. // List of payments
  2767. $sign = 1;
  2768. if ($object->type == Facture::TYPE_CREDIT_NOTE)
  2769. $sign = - 1;
  2770. $nbrows = 8;
  2771. $nbcols = 3;
  2772. if (! empty($conf->projet->enabled))
  2773. $nbrows ++;
  2774. if (! empty($conf->banque->enabled)) {
  2775. $nbrows ++; $nbcols++;
  2776. }
  2777. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0)
  2778. $nbrows ++;
  2779. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0)
  2780. $nbrows ++;
  2781. if ($selleruserevenustamp)
  2782. $nbrows ++;
  2783. if (! empty($conf->multicurrency->enabled)) $nbrows+=5;
  2784. if (! empty($conf->incoterm->enabled)) $nbrows+=1;
  2785. print '<td rowspan="' . $nbrows . '" colspan="2" valign="top">';
  2786. if ($object->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
  2787. {
  2788. if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) print '<table class="nobordernopadding paymenttable" width="100%">';
  2789. if (count($object->tab_previous_situation_invoice) > 0)
  2790. {
  2791. //List of previous invoices
  2792. print '<tr class="liste_titre">';
  2793. print '<td>' . $langs->trans('ListOfPreviousSituationInvoices') . '</td>';
  2794. print '<td></td>';
  2795. if (! empty($conf->banque->enabled))
  2796. print '<td align="right"></td>';
  2797. print '<td align="right">' . $langs->trans('AmountHT') . '</td>';
  2798. print '<td align="right">' . $langs->trans('AmountTTC') . '</td>';
  2799. print '<td width="18">&nbsp;</td>';
  2800. print '</tr>';
  2801. $total_prev_ht = $total_prev_ttc = 0;
  2802. $var = true;
  2803. foreach ($object->tab_previous_situation_invoice as $prev_invoice)
  2804. {
  2805. $totalpaye = $prev_invoice->getSommePaiement();
  2806. $total_prev_ht += $prev_invoice->total_ht;
  2807. $total_prev_ttc += $prev_invoice->total_ttc;
  2808. print '<tr '.$bc [$var].'>';
  2809. print '<td>'.$prev_invoice->getNomUrl(1).'</td>';
  2810. print '<td></td>';
  2811. if (! empty($conf->banque->enabled))
  2812. print '<td align="right"></td>';
  2813. print '<td align="right">' . price($prev_invoice->total_ht) . '</td>';
  2814. print '<td align="right">' . price($prev_invoice->total_ttc) . '</td>';
  2815. print '<td align="right">'.$prev_invoice->getLibStatut(3, $totalpaye).'</td>';
  2816. print '</tr>';
  2817. $var = !$var;
  2818. }
  2819. print '<tr '.$bc [$var].'>';
  2820. print '<td colspan="2" align="right"></td>';
  2821. print '<td align="right"><b>' . price($total_prev_ht) . '</b></td>';
  2822. print '<td align="right"><b>' . price($total_prev_ttc) . '</b></td>';
  2823. print '<td width="18">&nbsp;</td>';
  2824. print '</tr>';
  2825. }
  2826. if (count($object->tab_next_situation_invoice) > 0)
  2827. {
  2828. //List of next invoices
  2829. print '<tr class="liste_titre">';
  2830. print '<td>' . $langs->trans('ListOfNextSituationInvoices') . '</td>';
  2831. print '<td></td>';
  2832. if (! empty($conf->banque->enabled))
  2833. print '<td align="right"></td>';
  2834. print '<td align="right">' . $langs->trans('AmountHT') . '</td>';
  2835. print '<td align="right">' . $langs->trans('AmountTTC') . '</td>';
  2836. print '<td width="18">&nbsp;</td>';
  2837. print '</tr>';
  2838. $total_next_ht = $total_next_ttc = 0;
  2839. $var = true;
  2840. foreach ($object->tab_next_situation_invoice as $next_invoice)
  2841. {
  2842. $totalpaye = $next_invoice->getSommePaiement();
  2843. $total_next_ht += $next_invoice->total_ht;
  2844. $total_next_ttc += $next_invoice->total_ttc;
  2845. print '<tr '.$bc [$var].'>';
  2846. print '<td>'.$next_invoice->getNomUrl(1).'</td>';
  2847. print '<td></td>';
  2848. if (! empty($conf->banque->enabled))
  2849. print '<td align="right"></td>';
  2850. print '<td align="right">' . price($next_invoice->total_ht) . '</td>';
  2851. print '<td align="right">' . price($next_invoice->total_ttc) . '</td>';
  2852. print '<td align="right">'.$next_invoice->getLibStatut(3, $totalpaye).'</td>';
  2853. print '</tr>';
  2854. $var = !$var;
  2855. }
  2856. print '<tr '.$bc [$var].'>';
  2857. print '<td colspan="2" align="right"></td>';
  2858. print '<td align="right"><b>' . price($total_next_ht) . '</b></td>';
  2859. print '<td align="right"><b>' . price($total_next_ttc) . '</b></td>';
  2860. print '<td width="18">&nbsp;</td>';
  2861. print '</tr>';
  2862. }
  2863. if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) print '</table>';
  2864. }
  2865. print '<table class="nobordernopadding paymenttable" width="100%">';
  2866. // List of payments already done
  2867. print '<tr class="liste_titre">';
  2868. print '<td class="liste_titre">' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '</td>';
  2869. print '<td class="liste_titre">' . $langs->trans('Date') . '</td>';
  2870. print '<td class="liste_titre">' . $langs->trans('Type') . '</td>';
  2871. if (! empty($conf->banque->enabled))
  2872. print '<td class="liste_titre" align="right">' . $langs->trans('BankAccount') . '</td>';
  2873. print '<td class="liste_titre" align="right">' . $langs->trans('Amount') . '</td>';
  2874. print '<td class="liste_titre" width="18">&nbsp;</td>';
  2875. print '</tr>';
  2876. $var = true;
  2877. // Payments already done (from payment on this invoice)
  2878. $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,';
  2879. $sql .= ' c.code as payment_code, c.libelle as payment_label,';
  2880. $sql .= ' pf.amount,';
  2881. $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label';
  2882. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p';
  2883. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid';
  2884. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid';
  2885. $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid';
  2886. $sql .= ' ORDER BY p.datep, p.tms';
  2887. $result = $db->query($sql);
  2888. if ($result)
  2889. {
  2890. $num = $db->num_rows($result);
  2891. $i = 0;
  2892. // if ($object->type != 2)
  2893. // {
  2894. if ($num > 0)
  2895. {
  2896. while ($i < $num)
  2897. {
  2898. $objp = $db->fetch_object($result);
  2899. $var = ! $var;
  2900. print '<tr ' . $bc [$var] . '><td>';
  2901. $paymentstatic->id=$objp->rowid;
  2902. $paymentstatic->datepaye=$db->jdate($objp->dp);
  2903. $paymentstatic->ref=$objp->ref;
  2904. $paymentstatic->num_paiement=$objp->num_paiement;
  2905. $paymentstatic->payment_code=$objp->payment_code;
  2906. print $paymentstatic->getNomUrl(1);
  2907. print '</td>';
  2908. print '<td>'.dol_print_date($db->jdate($objp->dp), 'day') . '</td>';
  2909. $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label;
  2910. print '<td>' . $label . ' ' . $objp->num_paiement . '</td>';
  2911. if (! empty($conf->banque->enabled))
  2912. {
  2913. $bankaccountstatic->id = $objp->baid;
  2914. $bankaccountstatic->ref = $objp->baref;
  2915. $bankaccountstatic->label = $objp->baref;
  2916. print '<td align="right">';
  2917. if ($bankaccountstatic->id)
  2918. print $bankaccountstatic->getNomUrl(1, 'transactions');
  2919. print '</td>';
  2920. }
  2921. print '<td align="right">' . price($sign * $objp->amount) . '</td>';
  2922. print '<td>&nbsp;</td>';
  2923. print '</tr>';
  2924. $i ++;
  2925. }
  2926. } else {
  2927. print '<tr ' . $bc[false] . '><td colspan="' . $nbcols . '" class="opacitymedium">' . $langs->trans("None") . '</td><td></td><td></td></tr>';
  2928. }
  2929. // }
  2930. $db->free($result);
  2931. } else {
  2932. dol_print_error($db);
  2933. }
  2934. if ($object->type != Facture::TYPE_CREDIT_NOTE)
  2935. {
  2936. // Total already paid
  2937. print '<tr><td colspan="' . $nbcols . '" align="right">';
  2938. if ($object->type != Facture::TYPE_DEPOSIT)
  2939. print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
  2940. else
  2941. print $langs->trans('AlreadyPaid');
  2942. print ' :</td><td align="right">' . price($totalpaye) . '</td><td>&nbsp;</td></tr>';
  2943. $resteapayeraffiche = $resteapayer;
  2944. // Loop on each credit note or deposit amount applied
  2945. $creditnoteamount = 0;
  2946. $depositamount = 0;
  2947. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  2948. $sql .= " re.description, re.fk_facture_source";
  2949. $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re";
  2950. $sql .= " WHERE fk_facture = " . $object->id;
  2951. $resql = $db->query($sql);
  2952. if ($resql)
  2953. {
  2954. $num = $db->num_rows($resql);
  2955. $i = 0;
  2956. $invoice = new Facture($db);
  2957. while ($i < $num)
  2958. {
  2959. $obj = $db->fetch_object($resql);
  2960. $invoice->fetch($obj->fk_facture_source);
  2961. print '<tr><td colspan="' . $nbcols . '" align="right">';
  2962. if ($invoice->type == Facture::TYPE_CREDIT_NOTE)
  2963. print $langs->trans("CreditNote") . ' ';
  2964. if ($invoice->type == Facture::TYPE_DEPOSIT)
  2965. print $langs->trans("Deposit") . ' ';
  2966. print $invoice->getNomUrl(0);
  2967. print ' :</td>';
  2968. print '<td align="right">' . price($obj->amount_ttc) . '</td>';
  2969. print '<td align="right">';
  2970. print '<a href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=unlinkdiscount&discountid=' . $obj->rowid . '">' . img_delete() . '</a>';
  2971. print '</td></tr>';
  2972. $i ++;
  2973. if ($invoice->type == Facture::TYPE_CREDIT_NOTE)
  2974. $creditnoteamount += $obj->amount_ttc;
  2975. if ($invoice->type == Facture::TYPE_DEPOSIT)
  2976. $depositamount += $obj->amount_ttc;
  2977. }
  2978. } else {
  2979. dol_print_error($db);
  2980. }
  2981. // Paye partiellement 'escompte'
  2982. if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'discount_vat') {
  2983. print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
  2984. print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1);
  2985. print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
  2986. $resteapayeraffiche = 0;
  2987. }
  2988. // Paye partiellement ou Abandon 'badcustomer'
  2989. if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'badcustomer') {
  2990. print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
  2991. print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1);
  2992. print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
  2993. // $resteapayeraffiche=0;
  2994. }
  2995. // Paye partiellement ou Abandon 'product_returned'
  2996. if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'product_returned') {
  2997. print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
  2998. print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1);
  2999. print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
  3000. $resteapayeraffiche = 0;
  3001. }
  3002. // Paye partiellement ou Abandon 'abandon'
  3003. if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'abandon') {
  3004. print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
  3005. $text = $langs->trans("HelpAbandonOther");
  3006. if ($object->close_note)
  3007. $text .= '<br><br><b>' . $langs->trans("Reason") . '</b>:' . $object->close_note;
  3008. print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1);
  3009. print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
  3010. $resteapayeraffiche = 0;
  3011. }
  3012. // Billed
  3013. print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("Billed") . ' :</td><td align="right" style="border: 1px solid;">' . price($object->total_ttc) . '</td><td>&nbsp;</td></tr>';
  3014. // Remainder to pay
  3015. print '<tr><td colspan="' . $nbcols . '" align="right">';
  3016. if ($resteapayeraffiche >= 0)
  3017. print $langs->trans('RemainderToPay');
  3018. else
  3019. print $langs->trans('ExcessReceived');
  3020. print ' :</td>';
  3021. print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>' . price($resteapayeraffiche) . '</b></td>';
  3022. print '<td class="nowrap">&nbsp;</td></tr>';
  3023. }
  3024. else // Credit note
  3025. {
  3026. // Total already paid back
  3027. print '<tr><td colspan="' . $nbcols . '" align="right">';
  3028. print $langs->trans('AlreadyPaidBack');
  3029. print ' :</td><td align="right">' . price($sign * $totalpaye) . '</td><td>&nbsp;</td></tr>';
  3030. // Billed
  3031. print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("Billed") . ' :</td><td align="right" style="border: 1px solid;">' . price($sign * $object->total_ttc) . '</td><td>&nbsp;</td></tr>';
  3032. // Remainder to pay back
  3033. print '<tr><td colspan="' . $nbcols . '" align="right">';
  3034. if ($resteapayeraffiche <= 0)
  3035. print $langs->trans('RemainderToPayBack');
  3036. else
  3037. print $langs->trans('ExcessPaydBack');
  3038. print ' :</td>';
  3039. print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>' . price($sign * $resteapayeraffiche) . '</b></td>';
  3040. print '<td class="nowrap">&nbsp;</td></tr>';
  3041. // Sold credit note
  3042. // print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('TotalTTC').' :</td>';
  3043. // print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
  3044. // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
  3045. }
  3046. print '</table>';
  3047. // Margin Infos
  3048. if (! empty($conf->margin->enabled))
  3049. {
  3050. print '<br>';
  3051. $formmargin->displayMarginInfos($object, $object->statut > 0);
  3052. }
  3053. print '</td></tr>';
  3054. if (! empty($conf->global->INVOICE_POINTOFTAX_DATE))
  3055. {
  3056. // Date invoice
  3057. print '<tr><td>';
  3058. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3059. print $langs->trans('DatePointOfTax');
  3060. print '</td>';
  3061. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editdate_pointoftax&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  3062. print '</tr></table>';
  3063. print '</td><td colspan="3">';
  3064. if ($action == 'editdate_pointoftax') {
  3065. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_pointoftax, 'date_pointoftax');
  3066. } else {
  3067. print dol_print_date($object->date_pointoftax, 'daytext');
  3068. }
  3069. print '</td></tr>';
  3070. }
  3071. // Conditions de reglement
  3072. print '<tr><td>';
  3073. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3074. print $langs->trans('PaymentConditionsShort');
  3075. print '</td>';
  3076. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer)
  3077. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editconditions&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetConditions'), 1) . '</a></td>';
  3078. print '</tr></table>';
  3079. print '</td><td colspan="3">';
  3080. if ($object->type != Facture::TYPE_CREDIT_NOTE)
  3081. {
  3082. if ($action == 'editconditions') {
  3083. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id');
  3084. } else {
  3085. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none');
  3086. }
  3087. } else {
  3088. print '&nbsp;';
  3089. }
  3090. print '</td></tr>';
  3091. // Date payment term
  3092. print '<tr><td>';
  3093. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3094. print $langs->trans('DateMaxPayment');
  3095. print '</td>';
  3096. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && ! empty($object->brouillon) && $user->rights->facture->creer)
  3097. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editpaymentterm&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  3098. print '</tr></table>';
  3099. print '</td><td colspan="3">';
  3100. if ($object->type != Facture::TYPE_CREDIT_NOTE)
  3101. {
  3102. if ($action == 'editpaymentterm') {
  3103. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_lim_reglement, 'paymentterm');
  3104. } else {
  3105. print dol_print_date($object->date_lim_reglement, 'daytext');
  3106. if ($object->hasDelay()) {
  3107. print img_warning($langs->trans('Late'));
  3108. }
  3109. }
  3110. } else {
  3111. print '&nbsp;';
  3112. }
  3113. print '</td></tr>';
  3114. // Payment mode
  3115. print '<tr><td>';
  3116. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3117. print $langs->trans('PaymentMode');
  3118. print '</td>';
  3119. if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer)
  3120. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmode&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetMode'), 1) . '</a></td>';
  3121. print '</tr></table>';
  3122. print '</td><td colspan="3">';
  3123. if ($action == 'editmode')
  3124. {
  3125. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT');
  3126. }
  3127. else
  3128. {
  3129. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none', 'CRDT');
  3130. }
  3131. print '</td></tr>';
  3132. // Multicurrency
  3133. if (! empty($conf->multicurrency->enabled))
  3134. {
  3135. // Multicurrency code
  3136. print '<tr>';
  3137. print '<td>';
  3138. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3139. print fieldLabel('Currency','multicurrency_code');
  3140. print '</td>';
  3141. if ($action != 'editmulticurrencycode' && ! empty($object->brouillon))
  3142. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencycode&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
  3143. print '</tr></table>';
  3144. print '</td><td colspan="3">';
  3145. if ($action == 'editmulticurrencycode') {
  3146. $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code');
  3147. } else {
  3148. $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none');
  3149. }
  3150. print '</td></tr>';
  3151. // Multicurrency rate
  3152. print '<tr>';
  3153. print '<td>';
  3154. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3155. print fieldLabel('Rate','multicurrency_tx');
  3156. print '</td>';
  3157. if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon))
  3158. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencyrate&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
  3159. print '</tr></table>';
  3160. print '</td><td colspan="3">';
  3161. if ($action == 'editmulticurrencyrate') {
  3162. $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
  3163. } else {
  3164. $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  3165. }
  3166. print '</td></tr>';
  3167. }
  3168. // Bank Account
  3169. print '<tr><td class="nowrap">';
  3170. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  3171. print $langs->trans('BankAccount');
  3172. print '<td>';
  3173. if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon))
  3174. print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'),1).'</a></td>';
  3175. print '</tr></table>';
  3176. print '</td><td colspan="3">';
  3177. if ($action == 'editbankaccount')
  3178. {
  3179. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  3180. }
  3181. else
  3182. {
  3183. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  3184. }
  3185. print "</td>";
  3186. print '</tr>';
  3187. // Situations
  3188. if (! empty($conf->global->INVOICE_US_SITUATION))
  3189. {
  3190. if ($object->type == 5 && ($object->situation_counter > 1))
  3191. {
  3192. $prevsits = $object->get_prev_sits();
  3193. print '<tr><td>';
  3194. print $langs->trans('SituationAmount');
  3195. print ' ';
  3196. print $prevsits[0]->situation_counter;
  3197. $cprevsits = count($prevsits);
  3198. for ($i = 1; $i < $cprevsits; $i++) {
  3199. print ' + ';
  3200. print $prevsits[$i]->situation_counter;
  3201. }
  3202. print ' + ';
  3203. print $object->situation_counter;
  3204. print '</td>';
  3205. print '<td align="right" colspan="2" class="nowrap">';
  3206. $prevsits_total_amount = 0;
  3207. foreach ($prevsits as $situation) {
  3208. $prevsits_total_amount += $situation->total_ht;
  3209. }
  3210. $prevsits_total_amount += $object->total_ht;
  3211. print price($prevsits_total_amount);
  3212. print '</td>';
  3213. print '<td>' . $langs->trans('Currency' . $conf->currency) . '</td></tr>';
  3214. // Previous situation(s) deduction(s)
  3215. for ($i = 0; $i < $cprevsits; $i++) {
  3216. print '<tr><td>';
  3217. print '<a href="' . $_SERVER['PHP_SELF'] . '?facid=' . $prevsits[$i]->id . '">';
  3218. print $langs->trans('SituationDeduction');
  3219. print ' ';
  3220. print $prevsits[$i]->situation_counter;
  3221. print '</a></td>';
  3222. print '<td align="right" colspan="2" class="nowrap">';
  3223. print '- ' . price($prevsits[$i]->total_ht);
  3224. print '</td>';
  3225. print '<td>' . $langs->trans('Currency' . $conf->currency) . '</td></tr>';
  3226. }
  3227. }
  3228. }
  3229. // Amount
  3230. print '<tr><td>' . $langs->trans('AmountHT') . '</td>';
  3231. print '<td colspan="3" class="nowrap">' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3232. print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td colspan="3" class="nowrap">' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3233. print '</tr>';
  3234. // Amount Local Taxes
  3235. if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1
  3236. {
  3237. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
  3238. print '<td colspan="3" class="nowrap">' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3239. }
  3240. if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2
  3241. {
  3242. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
  3243. print '<td colspan="3" class=nowrap">' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3244. }
  3245. // Revenue stamp
  3246. if ($selleruserevenustamp) // Test company use revenue stamp
  3247. {
  3248. print '<tr><td>';
  3249. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3250. print $langs->trans('RevenueStamp');
  3251. print '</td>';
  3252. if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer)
  3253. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editrevenuestamp&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '</a></td>';
  3254. print '</tr></table>';
  3255. print '</td><td colspan="3">';
  3256. if ($action == 'editrevenuestamp') {
  3257. print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
  3258. print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
  3259. print '<input type="hidden" name="action" value="setrevenuestamp">';
  3260. print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code);
  3261. // print '<input type="text" class="flat" size="4" name="revenuestamp" value="'.price2num($object->revenuestamp).'">';
  3262. print ' <input type="submit" class="button" value="' . $langs->trans('Modify') . '">';
  3263. print '</form>';
  3264. } else {
  3265. print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency);
  3266. }
  3267. print '</td></tr>';
  3268. }
  3269. // Total with tax
  3270. print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td colspan="3" class="nowrap">' . price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
  3271. if (!empty($conf->multicurrency->enabled))
  3272. {
  3273. // Multicurrency Amount HT
  3274. print '<tr><td height="10">' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '</td>';
  3275. print '<td class="nowrap" colspan="2">' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  3276. print '</tr>';
  3277. // Multicurrency Amount VAT
  3278. print '<tr><td height="10">' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '</td>';
  3279. print '<td class="nowrap" colspan="2">' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  3280. print '</tr>';
  3281. // Multicurrency Amount TTC
  3282. print '<tr><td height="10">' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '</td>';
  3283. print '<td class="nowrap" colspan="2">' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  3284. print '</tr>';
  3285. }
  3286. // Statut
  3287. print '<tr><td>' . $langs->trans('Status') . '</td>';
  3288. print '<td colspan="3">' . ($object->getLibStatut(4, $totalpaye)) . '</td></tr>';
  3289. // Project
  3290. if (! empty($conf->projet->enabled)) {
  3291. $langs->load('projects');
  3292. print '<tr>';
  3293. print '<td>';
  3294. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3295. print $langs->trans('Project');
  3296. print '</td>';
  3297. if ($action != 'classify') {
  3298. print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=classify&amp;facid=' . $object->id . '">';
  3299. print img_edit($langs->trans('SetProject'), 1);
  3300. print '</a></td>';
  3301. }
  3302. print '</tr></table>';
  3303. print '</td><td colspan="3">';
  3304. if ($action == 'classify') {
  3305. $form->form_project($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1);
  3306. } else {
  3307. $form->form_project($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0);
  3308. }
  3309. print '</td>';
  3310. print '</tr>';
  3311. }
  3312. // Incoterms
  3313. if (!empty($conf->incoterm->enabled))
  3314. {
  3315. print '<tr><td>';
  3316. print '<table width="100%" class="nobordernopadding"><tr><td>';
  3317. print $langs->trans('IncotermLabel');
  3318. print '<td><td align="right">';
  3319. if ($user->rights->facture->creer) print '<a href="'.DOL_URL_ROOT.'/compta/facture.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>';
  3320. else print '&nbsp;';
  3321. print '</td></tr></table>';
  3322. print '</td>';
  3323. print '<td colspan="3">';
  3324. if ($action != 'editincoterm')
  3325. {
  3326. print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1);
  3327. }
  3328. else
  3329. {
  3330. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id);
  3331. }
  3332. print '</td></tr>';
  3333. }
  3334. // Other attributes
  3335. $cols = 5;
  3336. include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
  3337. print '</table><br>';
  3338. if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  3339. $blocname = 'contacts';
  3340. $title = $langs->trans('ContactsAddresses');
  3341. include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
  3342. }
  3343. if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  3344. $blocname = 'notes';
  3345. $title = $langs->trans('Notes');
  3346. include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
  3347. }
  3348. // Lines
  3349. $result = $object->getLinesArray();
  3350. print ' <form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (($action != 'editline') ? '#add' : '#line_' . GETPOST('lineid')) . '" method="POST">
  3351. <input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">
  3352. <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateligne') . '">
  3353. <input type="hidden" name="mode" value="">
  3354. <input type="hidden" name="id" value="' . $object->id . '">
  3355. ';
  3356. if (! empty($conf->use_javascript_ajax) && $object->statut == 0) {
  3357. include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
  3358. }
  3359. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  3360. // Show global modifiers
  3361. if (! empty($conf->global->INVOICE_US_SITUATION))
  3362. {
  3363. if ($object->situation_cycle_ref && $object->statut == 0) {
  3364. print '<tr class="liste_titre nodrag nodrop">';
  3365. print '<form name="updatealllines" id="updatealllines" action="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '"#updatealllines" method="POST">';
  3366. print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '" />';
  3367. print '<input type="hidden" name="action" value="updatealllines" />';
  3368. print '<input type="hidden" name="id" value="' . $object->id . '" />';
  3369. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  3370. print '<td align="center" width="5">&nbsp;</td>';
  3371. }
  3372. print '<td>' . $langs->trans('ModifyAllLines') . '</td>';
  3373. print '<td align="right" width="50">&nbsp;</td>';
  3374. print '<td align="right" width="80">&nbsp;</td>';
  3375. if ($inputalsopricewithtax) print '<td align="right" width="80">&nbsp;</td>';
  3376. print '<td align="right" width="50">&nbsp</td>';
  3377. print '<td align="right" width="50">&nbsp</td>';
  3378. print '<td align="right" width="50">' . $langs->trans('Progress') . '</td>';
  3379. if (! empty($conf->margin->enabled) && empty($user->societe_id))
  3380. {
  3381. print '<td align="right" class="margininfos" width="80">&nbsp;</td>';
  3382. if ((! empty($conf->global->DISPLAY_MARGIN_RATES) || ! empty($conf->global->DISPLAY_MARK_RATES)) && $user->rights->margins->liretous) {
  3383. print '<td align="right" class="margininfos" width="50">&nbsp;</td>';
  3384. }
  3385. }
  3386. print '<td align="right" width="50">&nbsp;</td>';
  3387. print '<td>&nbsp;</td>';
  3388. print '<td width="10">&nbsp;</td>';
  3389. print '<td width="10">&nbsp;</td>';
  3390. print "</tr>\n";
  3391. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  3392. print '<td align="center" width="5">&nbsp;</td>';
  3393. }
  3394. print '<tr width="100%" class="nodrag nodrop">';
  3395. print '<td>&nbsp;</td>';
  3396. print '<td width="50">&nbsp;</td>';
  3397. print '<td width="80">&nbsp;</td>';
  3398. print '<td width="50">&nbsp;</td>';
  3399. print '<td width="50">&nbsp;</td>';
  3400. print '<td align="right" class="nowrap"><input type="text" size="1" value="" name="all_progress">%</td>';
  3401. print '<td colspan="4" align="right"><input class="button" type="submit" name="all_percent" value="Modifier" /></td>';
  3402. print '</tr>';
  3403. print '</form>';
  3404. }
  3405. }
  3406. // Show object lines
  3407. if (! empty($object->lines))
  3408. $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
  3409. // Form to add new line
  3410. if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline' && ($object->is_first() || !$object->situation_cycle_ref))
  3411. {
  3412. if ($action != 'editline')
  3413. {
  3414. $var = true;
  3415. // Add free products/services
  3416. $object->formAddObjectLine(1, $mysoc, $soc);
  3417. $parameters = array();
  3418. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  3419. }
  3420. }
  3421. print "</table>\n";
  3422. print "</form>\n";
  3423. dol_fiche_end();
  3424. // Actions buttons
  3425. if ($action != 'prerelance' && $action != 'presend' && $action != 'valid' && $action != 'editline')
  3426. {
  3427. print '<div class="tabsAction">';
  3428. $parameters = array();
  3429. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
  3430. // modified by hook
  3431. if (empty($reshook)) {
  3432. // Editer une facture deja validee, sans paiement effectue et pas exporte en compta
  3433. if ($object->statut == 1)
  3434. {
  3435. // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
  3436. $ventilExportCompta = $object->getVentilExportCompta();
  3437. if ($resteapayer == $object->total_ttc && empty($object->paye) && $ventilExportCompta == 0)
  3438. {
  3439. if (! $objectidnext && $object->is_last_in_cycle())
  3440. {
  3441. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
  3442. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
  3443. {
  3444. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=modif">' . $langs->trans('Modify') . '</a></div>';
  3445. } else {
  3446. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("NotEnoughPermissions") . '">' . $langs->trans('Modify') . '</span></div>';
  3447. }
  3448. } else if (!$object->is_last_in_cycle()) {
  3449. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("NotLastInCycle") . '">' . $langs->trans('Modify') . '</span></div>';
  3450. } else {
  3451. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('Modify') . '</span></div>';
  3452. }
  3453. }
  3454. }
  3455. // Reopen a standard paid invoice
  3456. if ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)
  3457. || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id))
  3458. || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id)))
  3459. && ($object->statut == 2 || $object->statut == 3 || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data
  3460. && $user->rights->facture->creer) // A paid invoice (partially or completely)
  3461. {
  3462. if (! $objectidnext && $object->close_code != 'replaced') // Not replaced by another invoice
  3463. {
  3464. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=reopen">' . $langs->trans('ReOpen') . '</a></div>';
  3465. } else {
  3466. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('ReOpen') . '</span></div>';
  3467. }
  3468. }
  3469. // Validate
  3470. if ($object->statut == 0 && count($object->lines) > 0 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0)) || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) {
  3471. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
  3472. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate)))
  3473. {
  3474. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=valid">' . $langs->trans('Validate') . '</a></div>';
  3475. }
  3476. }
  3477. // Send by mail
  3478. if (($object->statut == 1 || $object->statut == 2) || ! empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) {
  3479. if ($objectidnext) {
  3480. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('SendByMail') . '</span></div>';
  3481. } else {
  3482. if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send) {
  3483. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=presend&amp;mode=init">' . $langs->trans('SendByMail') . '</a></div>';
  3484. } else
  3485. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">' . $langs->trans('SendByMail') . '</a></div>';
  3486. }
  3487. }
  3488. // deprecated. Useless because now we can use templates
  3489. if (! empty($conf->global->FACTURE_SHOW_SEND_REMINDER)) // For backward compatibility
  3490. {
  3491. if (($object->statut == 1 || $object->statut == 2) && $resteapayer > 0) {
  3492. if ($objectidnext) {
  3493. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('SendRemindByMail') . '</span></div>';
  3494. } else {
  3495. if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send) {
  3496. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=prerelance&amp;mode=init">' . $langs->trans('SendRemindByMail') . '</a></div>';
  3497. } else
  3498. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">' . $langs->trans('SendRemindByMail') . '</a></div>';
  3499. }
  3500. }
  3501. }
  3502. // Create payment
  3503. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement) {
  3504. if ($objectidnext) {
  3505. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('DoPayment') . '</span></div>';
  3506. } else {
  3507. if ($resteapayer == 0) {
  3508. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseRemainderToPayIsZero") . '">' . $langs->trans('DoPayment') . '</span></div>';
  3509. } else {
  3510. print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid=' . $object->id . '&amp;action=create&amp;accountid='.$object->fk_account.'">' . $langs->trans('DoPayment') . '</a></div>';
  3511. }
  3512. }
  3513. }
  3514. // Reverse back money or convert to reduction
  3515. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  3516. // For credit note only
  3517. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
  3518. {
  3519. if ($resteapayer == 0)
  3520. {
  3521. print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span></div>';
  3522. }
  3523. else
  3524. {
  3525. print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a></div>';
  3526. }
  3527. }
  3528. // For credit note
  3529. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0) {
  3530. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc">' . $langs->trans('ConvertToReduc') . '</a></div>';
  3531. }
  3532. // For deposit invoice
  3533. if ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $user->rights->facture->creer && empty($discount->id))
  3534. {
  3535. print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>';
  3536. }
  3537. }
  3538. // Classify paid
  3539. if ($object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement && (($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && $resteapayer <= 0) || ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0))
  3540. || ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 0 && $object->total_ttc > 0 && $resteapayer == 0 && $user->rights->facture->paiement && empty($discount->id))
  3541. )
  3542. {
  3543. print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a></div>';
  3544. }
  3545. // Classify 'closed not completely paid' (possible si validee et pas encore classee payee)
  3546. if ($object->statut == 1 && $object->paye == 0 && $resteapayer > 0 && $user->rights->facture->paiement)
  3547. {
  3548. if ($totalpaye > 0 || $totalcreditnotes > 0)
  3549. {
  3550. // If one payment or one credit note was linked to this invoice
  3551. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=paid">' . $langs->trans('ClassifyPaidPartially') . '</a></div>';
  3552. }
  3553. else
  3554. {
  3555. if ( empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED))
  3556. {
  3557. if ($objectidnext)
  3558. {
  3559. print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('ClassifyCanceled') . '</span></div>';
  3560. }
  3561. else
  3562. {
  3563. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=canceled">' . $langs->trans('ClassifyCanceled') . '</a></div>';
  3564. }
  3565. }
  3566. }
  3567. }
  3568. // Clone
  3569. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $user->rights->facture->creer)
  3570. {
  3571. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=clone&amp;object=invoice">' . $langs->trans("ToClone") . '</a></div>';
  3572. }
  3573. // Clone as predefined / Create template
  3574. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut == 0 && $user->rights->facture->creer)
  3575. {
  3576. if (! $objectidnext && count($object->lines) > 0)
  3577. {
  3578. print '<div class="inline-block divButAction"><a class="butAction" href="facture/fiche-rec.php?facid=' . $object->id . '&amp;action=create">' . $langs->trans("ChangeIntoRepeatableInvoice") . '</a></div>';
  3579. }
  3580. }
  3581. // Create a credit note
  3582. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $user->rights->facture->creer)
  3583. {
  3584. if (! $objectidnext)
  3585. {
  3586. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?socid=' . $object->socid .'&amp;fac_avoir=' . $object->id . '&amp;action=create&amp;type=2">' . $langs->trans("CreateCreditNote") . '</a></div>';
  3587. }
  3588. }
  3589. // Create next situation invoice
  3590. if ($user->rights->facture->creer && ($object->type == 5) && ($object->statut == 1 || $object->statut == 2)) {
  3591. if ($object->is_last_in_cycle() && $object->situation_final != 1) {
  3592. print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=create&amp;type=5&amp;origin=facture&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '" >' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
  3593. } else if (!$object->is_last_in_cycle()) {
  3594. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotLastInCycle") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
  3595. } else {
  3596. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseFinal") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
  3597. }
  3598. }
  3599. // Delete
  3600. if ($user->rights->facture->supprimer)
  3601. {
  3602. if (! $object->is_erasable()) {
  3603. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotErasable") . '">' . $langs->trans('Delete') . '</a></div>';
  3604. } else if ($objectidnext) {
  3605. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('Delete') . '</a></div>';
  3606. } elseif ($object->getSommePaiement()) {
  3607. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecausePayments") . '">' . $langs->trans('Delete') . '</a></div>';
  3608. } else {
  3609. print '<div class="inline-block divButAction"><a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=delete">' . $langs->trans('Delete') . '</a></div>';
  3610. }
  3611. } else {
  3612. print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("NotAllowed") . '">' . $langs->trans('Delete') . '</a></div>';
  3613. }
  3614. print '</div>';
  3615. }
  3616. }
  3617. print '<br>';
  3618. // Select mail models is same action as presend
  3619. if (GETPOST('modelselected')) {
  3620. $action = 'presend';
  3621. }
  3622. if ($action != 'prerelance' && $action != 'presend')
  3623. {
  3624. print '<div class="fichecenter"><div class="fichehalfleft">';
  3625. print '<a name="builddoc"></a>'; // ancre
  3626. // Documents generes
  3627. $filename = dol_sanitizeFileName($object->ref);
  3628. $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
  3629. $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id;
  3630. $genallowed = $user->rights->facture->creer;
  3631. $delallowed = $user->rights->facture->supprimer;
  3632. print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
  3633. $somethingshown = $formfile->numoffiles;
  3634. // Linked object block
  3635. $somethingshown = $form->showLinkedObjectBlock($object);
  3636. // Show links to link elements
  3637. $linktoelem = $form->showLinkToObjectBlock($object,array('order'));
  3638. if ($linktoelem) print '<br>'.$linktoelem;
  3639. // Link for paypal payment
  3640. if (! empty($conf->paypal->enabled) && $object->statut != 0) {
  3641. include_once DOL_DOCUMENT_ROOT . '/paypal/lib/paypal.lib.php';
  3642. print showPaypalPaymentUrl('invoice', $object->ref);
  3643. }
  3644. print '</div><div class="fichehalfright"><div class="ficheaddleft">';
  3645. // List of actions on element
  3646. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
  3647. $formactions = new FormActions($db);
  3648. $somethingshown = $formactions->showactions($object, 'invoice', $socid);
  3649. print '</div></div></div>';
  3650. }
  3651. else
  3652. {
  3653. /*
  3654. * Action presend (or prerelance)
  3655. */
  3656. $object->fetch_projet();
  3657. // By default if $action=='presend'
  3658. $titreform = 'SendBillByMail';
  3659. $topicmail = 'SendBillRef';
  3660. $modelmail = 'facture_send';
  3661. if ($action == 'prerelance') // For backward compatibility
  3662. {
  3663. $titrefrom = 'SendReminderBillByMail';
  3664. $topicmail = 'SendReminderBillRef';
  3665. $modelmail = 'facture_relance';
  3666. $action = 'relance';
  3667. } else
  3668. $action = 'send';
  3669. $ref = dol_sanitizeFileName($object->ref);
  3670. include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  3671. $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+');
  3672. $file = $fileparams['fullname'];
  3673. // Define output language
  3674. $outputlangs = $langs;
  3675. $newlang = '';
  3676. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id']))
  3677. $newlang = $_REQUEST['lang_id'];
  3678. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  3679. $newlang = $object->thirdparty->default_lang;
  3680. if (!empty($newlang))
  3681. {
  3682. $outputlangs = new Translate('', $conf);
  3683. $outputlangs->setDefaultLang($newlang);
  3684. $outputlangs->load('bills');
  3685. }
  3686. // Build document if it not exists
  3687. if (! $file || ! is_readable($file)) {
  3688. $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  3689. if ($result <= 0) {
  3690. dol_print_error($db, $object->error, $object->errors);
  3691. exit();
  3692. }
  3693. $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+');
  3694. $file = $fileparams['fullname'];
  3695. }
  3696. print '<div class="clearboth"></div>';
  3697. print '<br>';
  3698. print load_fiche_titre($langs->trans($titreform));
  3699. // Cree l'objet formulaire mail
  3700. dol_fiche_head();
  3701. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  3702. $formmail = new FormMail($db);
  3703. $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang);
  3704. $formmail->fromtype = 'user';
  3705. $formmail->fromid = $user->id;
  3706. $formmail->fromname = $user->getFullName($langs);
  3707. $formmail->frommail = $user->email;
  3708. $formmail->trackid='inv'.$object->id;
  3709. if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set
  3710. {
  3711. include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  3712. $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'inv'.$object->id);
  3713. }
  3714. $formmail->withfrom = 1;
  3715. $liste = array();
  3716. foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) {
  3717. $liste [$key] = $value;
  3718. }
  3719. $formmail->withto = GETPOST('sendto') ? GETPOST('sendto') : $liste; // List suggested for send to
  3720. $formmail->withtocc = $liste; // List suggested for CC
  3721. $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC;
  3722. if (empty($object->ref_client)) {
  3723. $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__REF__');
  3724. } else if (! empty($object->ref_client)) {
  3725. $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__REF__ (__REFCLIENT__)');
  3726. }
  3727. $formmail->withfile = 2;
  3728. $formmail->withbody = 1;
  3729. $formmail->withdeliveryreceipt = 1;
  3730. $formmail->withcancel = 1;
  3731. // Tableau des substitutions
  3732. $formmail->setSubstitFromObject($object, $outputlangs);
  3733. $formmail->substit['__INVREF__'] = $object->ref;
  3734. // Find the good contact adress
  3735. $custcontact = '';
  3736. $contactarr = array();
  3737. $contactarr = $object->liste_contact(- 1, 'external');
  3738. if (is_array($contactarr) && count($contactarr) > 0) {
  3739. foreach ($contactarr as $contact) {
  3740. if ($contact['libelle'] == $langs->trans('TypeContact_facture_external_BILLING')) { // TODO Use code and not label
  3741. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  3742. $contactstatic = new Contact($db);
  3743. $contactstatic->fetch($contact ['id']);
  3744. $custcontact = $contactstatic->getFullName($langs, 1);
  3745. }
  3746. }
  3747. if (! empty($custcontact)) {
  3748. $formmail->substit['__CONTACTCIVNAME__'] = $custcontact;
  3749. }
  3750. }
  3751. // Tableau des parametres complementaires du post
  3752. $formmail->param['action'] = $action;
  3753. $formmail->param['models'] = $modelmail;
  3754. $formmail->param['models_id']=GETPOST('modelmailselected','int');
  3755. $formmail->param['facid'] = $object->id;
  3756. $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id;
  3757. // Init list of files
  3758. if (GETPOST("mode") == 'init') {
  3759. $formmail->clear_attached_files();
  3760. $formmail->add_attached_files($file, basename($file), dol_mimetype($file));
  3761. }
  3762. print $formmail->get_form();
  3763. dol_fiche_end();
  3764. }
  3765. }
  3766. llxFooter();
  3767. $db->close();