card.php 187 KB

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