facture.php 174 KB

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