1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213 |
- <?php
- /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
- * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
- * Copyright (C) 2004-2016 Laurent Destailleur <eldy@users.sourceforge.net>
- * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
- * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@capnetworks.com>
- * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
- * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
- * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
- * Copyright (C) 2012-2013 Cédric Salvador <csalvador@gpcsolutions.fr>
- * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
- * Copyright (C) 2013 Jean-Francois FERRY <jfefe@aternatik.fr>
- * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
- * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
- * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
- * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- /**
- * \file htdocs/compta/facture.php
- * \ingroup facture
- * \brief Page to create/see an invoice
- */
- require '../main.inc.php';
- require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
- require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php';
- require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
- require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
- require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
- require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
- require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
- require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
- require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
- require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
- require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
- require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
- if (! empty($conf->commande->enabled))
- require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
- if (! empty($conf->projet->enabled)) {
- require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
- require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
- }
- require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
- $langs->load('bills');
- $langs->load('companies');
- $langs->load('compta');
- $langs->load('products');
- $langs->load('banks');
- $langs->load('main');
- if (!empty($conf->incoterm->enabled)) $langs->load('incoterm');
- if (! empty($conf->margin->enabled))
- $langs->load('margins');
- $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0);
- $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
- $ref = GETPOST('ref', 'alpha');
- $socid = GETPOST('socid', 'int');
- $action = GETPOST('action', 'alpha');
- $confirm = GETPOST('confirm', 'alpha');
- $cancel = GETPOST('cancel', 'alpha');
- $lineid = GETPOST('lineid', 'int');
- $userid = GETPOST('userid', 'int');
- $search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
- $search_societe = GETPOST('search_societe', 'alpha');
- $search_montant_ht = GETPOST('search_montant_ht', 'alpha');
- $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
- $origin = GETPOST('origin', 'alpha');
- $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
- $fac_rec=GETPOST('fac_rec','int');
- // PDF
- $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
- $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
- $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
- // Security check
- $fieldid = (! empty($ref) ? 'facnumber' : 'rowid');
- if ($user->societe_id) $socid = $user->societe_id;
- $result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid);
- // Nombre de ligne pour choix de produit/service predefinis
- $NBLINES = 4;
- $usehm = (! empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
- $object = new Facture($db);
- $extrafields = new ExtraFields($db);
- // Load object
- if ($id > 0 || ! empty($ref)) {
- $ret = $object->fetch($id, $ref, '', '', $conf->global->INVOICE_USE_SITUATION);
- }
- // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
- $hookmanager->initHooks(array('invoicecard','globalcard'));
- $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php
- $permissiondellink=$user->rights->facture->creer; // Used by the include of actions_dellink.inc.php
- $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php
- /*
- * Actions
- */
- $parameters = array('socid' => $socid);
- $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
- if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
- if (empty($reshook))
- {
- if ($cancel) $action='';
- include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
- include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
- include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
- // Action clone object
- if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->facture->creer) {
- // if (1 == 0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) {
- // $mesgs [] = '<div class="error">' . $langs->trans("NoCloneOptionsSpecified") . '</div>';
- // } else {
- if ($object->fetch($id) > 0) {
- $result = $object->createFromClone($socid);
- if ($result > 0) {
- header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $result);
- exit();
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- $action = '';
- }
- }
- // }
- }
- // Change status of invoice
- else if ($action == 'reopen' && $user->rights->facture->creer) {
- $result = $object->fetch($id);
- 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
- $result = $object->set_unpaid($user);
- if ($result > 0) {
- header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
- exit();
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- }
- // Delete invoice
- else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->facture->supprimer) {
- $result = $object->fetch($id);
- $object->fetch_thirdparty();
- $idwarehouse = GETPOST('idwarehouse');
- $qualified_for_stock_change = 0;
- if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
- $qualified_for_stock_change = $object->hasProductsOrServices(2);
- } else {
- $qualified_for_stock_change = $object->hasProductsOrServices(1);
- }
- $result = $object->delete($user, 0, $idwarehouse);
- if ($result > 0) {
- header('Location: ' . DOL_URL_ROOT . '/compta/facture/list.php');
- exit();
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- $action='';
- }
- }
- // Delete line
- else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $object->fetch_thirdparty();
- $result = $object->deleteline(GETPOST('lineid'));
- if ($result > 0) {
- // Define output language
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id']))
- $newlang = $_REQUEST['lang_id'];
- if ($conf->global->MAIN_MULTILANGS && empty($newlang))
- $newlang = $object->thirdparty->default_lang;
- if (! empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
- $ret = $object->fetch($id); // Reload to get new records
- $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- if ($result >= 0) {
- header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
- exit();
- }
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- $action = '';
- }
- }
- // Delete link of credit note to invoice
- else if ($action == 'unlinkdiscount' && $user->rights->facture->creer)
- {
- $discount = new DiscountAbsolute($db);
- $result = $discount->fetch(GETPOST("discountid"));
- $discount->unlink_invoice();
- }
- // Validation
- else if ($action == 'valid' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- // On verifie signe facture
- if ($object->type == Facture::TYPE_CREDIT_NOTE) {
- // Si avoir, le signe doit etre negatif
- if ($object->total_ht >= 0) {
- setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
- $action = '';
- }
- } else {
- // Si non avoir, le signe doit etre positif
- if (empty($conf->global->FACTURE_ENABLE_NEGATIVE) && $object->total_ht < 0) {
- setEventMessages($langs->trans("ErrorInvoiceOfThisTypeMustBePositive"), null, 'errors');
- $action = '';
- }
- }
- }
- else if ($action == 'set_thirdparty' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $object->setValueFrom('fk_soc', $socid, '', null, 'int', '', $user, 'BILL_MODIFY');
- header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
- exit();
- }
- else if ($action == 'classin' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $object->setProject($_POST['projectid']);
- }
- else if ($action == 'setmode' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
- if ($result < 0)
- dol_print_error($db, $object->error);
- }
- // Multicurrency Code
- else if ($action == 'setmulticurrencycode' && $user->rights->facture->creer) {
- $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
- }
- // Multicurrency rate
- else if ($action == 'setmulticurrencyrate' && $user->rights->facture->creer) {
- $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')));
- }
- else if ($action == 'setinvoicedate' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $old_date_lim_reglement = $object->date_lim_reglement;
- $date = dol_mktime(12, 0, 0, $_POST['invoicedatemonth'], $_POST['invoicedateday'], $_POST['invoicedateyear']);
- if (empty($date))
- {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
- header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate');
- exit;
- }
- $object->date=$date;
- $new_date_lim_reglement = $object->calculate_date_lim_reglement();
- if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement;
- if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date;
- $result = $object->update($user);
- if ($result < 0) dol_print_error($db, $object->error);
- }
- else if ($action == 'setdate_pointoftax' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
- $object->date_pointoftax=$date_pointoftax;
- $result = $object->update($user);
- if ($result < 0) dol_print_error($db, $object->error);
- }
- else if ($action == 'setconditions' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $object->cond_reglement_code = 0; // To clean property
- $object->cond_reglement_id = 0; // To clean property
- $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
- if ($result < 0) dol_print_error($db, $object->error);
- $old_date_lim_reglement = $object->date_lim_reglement;
- $new_date_lim_reglement = $object->calculate_date_lim_reglement();
- if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement;
- if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date;
- $result = $object->update($user);
- if ($result < 0) dol_print_error($db, $object->error);
- }
- else if ($action == 'setpaymentterm' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $object->date_lim_reglement = dol_mktime(12, 0, 0, $_POST['paymenttermmonth'], $_POST['paymenttermday'], $_POST['paymenttermyear']);
- if ($object->date_lim_reglement < $object->date) {
- $object->date_lim_reglement = $object->calculate_date_lim_reglement();
- setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
- }
- $result = $object->update($user);
- if ($result < 0)
- dol_print_error($db, $object->error);
- }
- else if ($action == 'setrevenuestamp' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $object->revenuestamp = GETPOST('revenuestamp');
- $result = $object->update($user);
- $object->update_price(1);
- if ($result < 0)
- dol_print_error($db, $object->error);
- }
- // Set incoterm
- elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled))
- {
- $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
- }
- // bank account
- else if ($action == 'setbankaccount' && $user->rights->facture->creer)
- {
- $result=$object->setBankAccount(GETPOST('fk_account', 'int'));
- }
- else if ($action == 'setremisepercent' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $result = $object->set_remise($user, $_POST['remise_percent']);
- }
- else if ($action == "setabsolutediscount" && $user->rights->facture->creer)
- {
- // POST[remise_id] ou POST[remise_id_for_payment]
- if (! empty($_POST["remise_id"])) {
- $ret = $object->fetch($id);
- if ($ret > 0) {
- $result = $object->insert_discount($_POST["remise_id"]);
- if ($result < 0) {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- } else {
- dol_print_error($db, $object->error);
- }
- }
- if (! empty($_POST["remise_id_for_payment"])) {
- require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
- $discount = new DiscountAbsolute($db);
- $discount->fetch($_POST["remise_id_for_payment"]);
- $result = $discount->link_to_invoice(0, $id);
- if ($result < 0) {
- setEventMessages($discount->error, $discount->errors, 'errors');
- }
- }
- }
- else if ($action == 'set_ref_client' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $object->set_ref_client($_POST['ref_client']);
- }
- // Classify to validated
- else if ($action == 'confirm_valid' && $confirm == 'yes' &&
- ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
- || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate)))
- )
- {
- $idwarehouse = GETPOST('idwarehouse');
- $object->fetch($id);
- $object->fetch_thirdparty();
- // Check parameters
- // Check for mandatory prof id (but only if country is than than ours)
- if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id)
- {
- for ($i = 1; $i <= 6; $i++)
- {
- $idprof_mandatory = 'SOCIETE_IDPROF' . ($i) . '_INVOICE_MANDATORY';
- $idprof = 'idprof' . $i;
- if (! $object->thirdparty->$idprof && ! empty($conf->global->$idprof_mandatory))
- {
- if (! $error) $langs->load("errors");
- $error++;
- setEventMessages($langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId' . $i, $object->thirdparty->country_code)), null, 'errors');
- }
- }
- }
- $qualified_for_stock_change = 0;
- if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
- $qualified_for_stock_change = $object->hasProductsOrServices(2);
- } else {
- $qualified_for_stock_change = $object->hasProductsOrServices(1);
- }
- // Check for warehouse
- if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
- {
- if (! $idwarehouse || $idwarehouse == - 1) {
- $error ++;
- setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
- $action = '';
- }
- }
- if (! $error)
- {
- $result = $object->validate($user, '', $idwarehouse);
- if ($result >= 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (! empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model=$object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
- $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- else
- {
- if (count($object->errors)) setEventMessages(null, $object->errors, 'errors');
- else setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- }
- // Go back to draft status (unvalidate)
- else if ($action == 'confirm_modif' &&
- ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
- || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
- )
- {
- $idwarehouse = GETPOST('idwarehouse');
- $object->fetch($id);
- $object->fetch_thirdparty();
- $qualified_for_stock_change = 0;
- if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
- $qualified_for_stock_change = $object->hasProductsOrServices(2);
- } else {
- $qualified_for_stock_change = $object->hasProductsOrServices(1);
- }
- // Check parameters
- if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
- {
- if (! $idwarehouse || $idwarehouse == - 1) {
- $error ++;
- setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
- $action = '';
- }
- }
- if (! $error) {
- // On verifie si la facture a des paiements
- $sql = 'SELECT pf.amount';
- $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf';
- $sql .= ' WHERE pf.fk_facture = ' . $object->id;
- $result = $db->query($sql);
- if ($result) {
- $i = 0;
- $num = $db->num_rows($result);
- while ($i < $num) {
- $objp = $db->fetch_object($result);
- $totalpaye += $objp->amount;
- $i ++;
- }
- } else {
- dol_print_error($db, '');
- }
- $resteapayer = $object->total_ttc - $totalpaye;
- // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
- $ventilExportCompta = $object->getVentilExportCompta();
- // On verifie si aucun paiement n'a ete effectue
- if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0)
- {
- $result=$object->set_draft($user, $idwarehouse);
- if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (! empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model=$object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
- }
- }
- // Classify "paid"
- else if ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->facture->paiement)
- {
- $object->fetch($id);
- $result = $object->set_paid($user);
- if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
- } // Classif "paid partialy"
- else if ($action == 'confirm_paid_partially' && $confirm == 'yes' && $user->rights->facture->paiement)
- {
- $object->fetch($id);
- $close_code = $_POST["close_code"];
- $close_note = $_POST["close_note"];
- if ($close_code) {
- $result = $object->set_paid($user, $close_code, $close_note);
- if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
- } else {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
- }
- } // Classify "abandoned"
- else if ($action == 'confirm_canceled' && $confirm == 'yes') {
- $object->fetch($id);
- $close_code = $_POST["close_code"];
- $close_note = $_POST["close_note"];
- if ($close_code) {
- $result = $object->set_canceled($user, $close_code, $close_note);
- if ($result<0) setEventMessages($object->error, $object->errors, 'errors');
- } else {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
- }
- }
- // Convertir en reduc
- else if ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $user->rights->facture->creer)
- {
- $object->fetch($id);
- $object->fetch_thirdparty();
- //$object->fetch_lines(); // Already done into fetch
- // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
- $discountcheck=new DiscountAbsolute($db);
- $result=$discountcheck->fetch(0,$object->id);
- $canconvert=0;
- 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)
- if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->paye == 0 && empty($discountcheck->id)) $canconvert=1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
- if ($canconvert)
- {
- $db->begin();
- // Boucle sur chaque taux de tva
- $i = 0;
- foreach ($object->lines as $line)
- {
- if ($line->total_ht!=0)
- { // no need to create discount if amount is null
- $amount_ht[$line->tva_tx] += $line->total_ht;
- $amount_tva[$line->tva_tx] += $line->total_tva;
- $amount_ttc[$line->tva_tx] += $line->total_ttc;
- $i ++;
- }
- }
- // Insert one discount by VAT rate category
- $discount = new DiscountAbsolute($db);
- if ($object->type == Facture::TYPE_CREDIT_NOTE)
- $discount->description = '(CREDIT_NOTE)';
- elseif ($object->type == Facture::TYPE_DEPOSIT)
- $discount->description = '(DEPOSIT)';
- else {
- setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
- }
- $discount->tva_tx = abs($object->total_ttc);
- $discount->fk_soc = $object->socid;
- $discount->fk_facture_source = $object->id;
- $error = 0;
- foreach ($amount_ht as $tva_tx => $xxx)
- {
- $discount->amount_ht = abs($amount_ht[$tva_tx]);
- $discount->amount_tva = abs($amount_tva[$tva_tx]);
- $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
- $discount->tva_tx = abs($tva_tx);
- $result = $discount->create($user);
- if ($result < 0)
- {
- $error++;
- break;
- }
- }
- if (empty($error))
- {
- // Classe facture
- $result = $object->set_paid($user);
- if ($result >= 0)
- {
- $db->commit();
- }
- else
- {
- setEventMessages($object->error, $object->errors, 'errors');
- $db->rollback();
- }
- }
- else
- {
- setEventMessages($discount->error, $discount->errors, 'errors');
- $db->rollback();
- }
- }
- }
- /*
- * Insert new invoice in database
- */
- else if ($action == 'add' && $user->rights->facture->creer)
- {
- if ($socid > 0) $object->socid = GETPOST('socid', 'int');
- $db->begin();
- $error = 0;
- // Fill array 'array_options' with data from add form
- $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
- $ret = $extrafields->setOptionalsFromPost($extralabels, $object);
- if ($ret < 0) $error++;
- // Replacement invoice
- if ($_POST['type'] == Facture::TYPE_REPLACEMENT)
- {
- $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
- if (empty($dateinvoice))
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
- }
- if (! ($_POST['fac_replacement'] > 0)) {
- $error ++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
- }
- $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
- if (! $error) {
- // This is a replacement invoice
- $result = $object->fetch($_POST['fac_replacement']);
- $object->fetch_thirdparty();
- $object->date = $dateinvoice;
- $object->date_pointoftax = $date_pointoftax;
- $object->note_public = trim($_POST['note_public']);
- $object->note = trim($_POST['note']);
- $object->ref_client = $_POST['ref_client'];
- $object->ref_int = $_POST['ref_int'];
- $object->modelpdf = $_POST['model'];
- $object->fk_project = $_POST['projectid'];
- $object->cond_reglement_id = $_POST['cond_reglement_id'];
- $object->mode_reglement_id = $_POST['mode_reglement_id'];
- $object->fk_account = GETPOST('fk_account', 'int');
- $object->remise_absolue = $_POST['remise_absolue'];
- $object->remise_percent = $_POST['remise_percent'];
- $object->fk_incoterms = GETPOST('incoterm_id', 'int');
- $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
- $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
- $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
- // Proprietes particulieres a facture de remplacement
- $object->fk_facture_source = $_POST['fac_replacement'];
- $object->type = Facture::TYPE_REPLACEMENT;
- $id = $object->createFromCurrent($user);
- if ($id <= 0) {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- }
- // Credit note invoice
- if ($_POST['type'] == Facture::TYPE_CREDIT_NOTE)
- {
- $sourceinvoice = GETPOST('fac_avoir');
- if (! ($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE))
- {
- $error ++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
- }
- $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
- if (empty($dateinvoice))
- {
- $error ++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Date")), null, 'errors');
- }
- $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
- if (! $error)
- {
- $object->socid = GETPOST('socid','int');
- $object->number = $_POST['facnumber'];
- $object->date = $dateinvoice;
- $object->date_pointoftax = $date_pointoftax;
- $object->note_public = trim($_POST['note_public']);
- $object->note = trim($_POST['note']);
- $object->ref_client = $_POST['ref_client'];
- $object->ref_int = $_POST['ref_int'];
- $object->modelpdf = $_POST['model'];
- $object->fk_project = $_POST['projectid'];
- $object->cond_reglement_id = 0;
- $object->mode_reglement_id = $_POST['mode_reglement_id'];
- $object->fk_account = GETPOST('fk_account', 'int');
- $object->remise_absolue = $_POST['remise_absolue'];
- $object->remise_percent = $_POST['remise_percent'];
- $object->fk_incoterms = GETPOST('incoterm_id', 'int');
- $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
- $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
- $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
- // Proprietes particulieres a facture avoir
- $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
- $object->type = Facture::TYPE_CREDIT_NOTE;
- $id = $object->create($user);
- if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0)
- {
- $facture_source = new Facture($db); // fetch origin object
- if ($facture_source->fetch($object->fk_facture_source)>0)
- {
- $fk_parent_line = 0;
- foreach($facture_source->lines as $line)
- {
- // Reset fk_parent_line for no child products and special product
- if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
- $fk_parent_line = 0;
- }
- $line->fk_facture = $object->id;
- $line->fk_parent_line = $fk_parent_line;
- $line->subprice =-$line->subprice; // invert price for object
- $line->pa_ht = -$line->pa_ht;
- $line->total_ht=-$line->total_ht;
- $line->total_tva=-$line->total_tva;
- $line->total_ttc=-$line->total_ttc;
- $line->total_localtax1=-$line->total_localtax1;
- $line->total_localtax2=-$line->total_localtax2;
- $result = $line->insert();
- $object->lines[] = $line; // insert new line in current object
- // Defined the new fk_parent_line
- if ($result > 0 && $line->product_type == 9) {
- $fk_parent_line = $result;
- }
- }
- $object->update_price(1);
- }
- }
- if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0)
- {
- $facture_source = new Facture($db); // fetch origin object if not previously defined
- if ($facture_source->fetch($object->fk_facture_source)>0)
- {
- $totalpaye = $facture_source->getSommePaiement();
- $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
- $totaldeposits = $facture_source->getSumDepositsUsed();
- $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits);
- $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC');
- }
- }
- // Add predefined lines
- /*
- TODO delete
- for($i = 1; $i <= $NBLINES; $i ++) {
- if ($_POST['idprod' . $i]) {
- $product = new Product($db);
- $product->fetch($_POST['idprod' . $i]);
- $startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']);
- $endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']);
- $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);
- }
- }*/
- }
- }
- // Standard invoice or Deposit invoice, created from a Predefined template invoice
- if (($_POST['type'] == Facture::TYPE_STANDARD || $_POST['type'] == Facture::TYPE_DEPOSIT) && GETPOST('fac_rec') > 0)
- {
- $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
- if (empty($dateinvoice))
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
- }
- $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
- if (! $error)
- {
- $object->socid = GETPOST('socid','int');
- $object->type = $_POST['type'];
- $object->number = $_POST['facnumber'];
- $object->date = $dateinvoice;
- $object->date_pointoftax = $date_pointoftax;
- $object->note_public = trim($_POST['note_public']);
- $object->note_private = trim($_POST['note_private']);
- $object->ref_client = $_POST['ref_client'];
- $object->ref_int = $_POST['ref_int'];
- $object->modelpdf = $_POST['model'];
- $object->fk_project = $_POST['projectid'];
- $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']);
- $object->mode_reglement_id = $_POST['mode_reglement_id'];
- $object->fk_account = GETPOST('fk_account', 'int');
- $object->amount = $_POST['amount'];
- $object->remise_absolue = $_POST['remise_absolue'];
- $object->remise_percent = $_POST['remise_percent'];
- $object->fk_incoterms = GETPOST('incoterm_id', 'int');
- $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
- $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
- $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
- // Source facture
- $object->fac_rec = GETPOST('fac_rec');
- $id = $object->create($user);
- var_dump('ggg');
- }
- }
- // Standard or deposit or proforma invoice
- 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)
- {
- if (GETPOST('socid', 'int') < 1)
- {
- $error ++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
- }
- $dateinvoice = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
- if (empty($dateinvoice))
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
- }
- $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
- if (! $error)
- {
- // Si facture standard
- $object->socid = GETPOST('socid','int');
- $object->type = GETPOST('type');
- $object->number = $_POST['facnumber'];
- $object->date = $dateinvoice;
- $object->date_pointoftax = $date_pointoftax;
- $object->note_public = trim($_POST['note_public']);
- $object->note_private = trim($_POST['note_private']);
- $object->ref_client = $_POST['ref_client'];
- $object->ref_int = $_POST['ref_int'];
- $object->modelpdf = $_POST['model'];
- $object->fk_project = $_POST['projectid'];
- $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']);
- $object->mode_reglement_id = $_POST['mode_reglement_id'];
- $object->fk_account = GETPOST('fk_account', 'int');
- $object->amount = $_POST['amount'];
- $object->remise_absolue = $_POST['remise_absolue'];
- $object->remise_percent = $_POST['remise_percent'];
- $object->fk_incoterms = GETPOST('incoterm_id', 'int');
- $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
- $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
- $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
- if (GETPOST('type') == Facture::TYPE_SITUATION)
- {
- $object->situation_counter = 1;
- $object->situation_final = 0;
- $object->situation_cycle_ref = $object->newCycle();
- }
- $object->fetch_thirdparty();
- // If creation from another object of another module (Example: origin=propal, originid=1)
- if (! empty($origin) && ! empty($originid))
- {
- // Parse element/subelement (ex: project_task)
- $element = $subelement = $origin;
- if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
- $element = $regs [1];
- $subelement = $regs [2];
- }
- // For compatibility
- if ($element == 'order') {
- $element = $subelement = 'commande';
- }
- if ($element == 'propal') {
- $element = 'comm/propal';
- $subelement = 'propal';
- }
- if ($element == 'contract') {
- $element = $subelement = 'contrat';
- }
- if ($element == 'inter') {
- $element = $subelement = 'ficheinter';
- }
- if ($element == 'shipping') {
- $element = $subelement = 'expedition';
- }
- $object->origin = $origin;
- $object->origin_id = $originid;
- // Possibility to add external linked objects with hooks
- $object->linked_objects[$object->origin] = $object->origin_id;
- // link with order if it is a shipping invoice
- if ($object->origin == 'shipping')
- {
- require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
- $exp = new Expedition($db);
- $exp->fetch($object->origin_id);
- $exp->fetchObjectLinked();
- if (count($exp->linkedObjectsIds['commande']) > 0) {
- foreach ($exp->linkedObjectsIds['commande'] as $key => $value){
- $object->linked_objects['commande'] = $value;
- }
- }
- }
- if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects']))
- {
- $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
- }
- $id = $object->create($user); // This include class to add_object_linked() and add add_contact()
-
- if ($id > 0)
- {
- dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
- $classname = ucfirst($subelement);
- $srcobject = new $classname($db);
- dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines");
- $result = $srcobject->fetch($object->origin_id);
- // If deposit invoice
- if ($_POST['type'] == Facture::TYPE_DEPOSIT)
- {
- $typeamount = GETPOST('typedeposit', 'alpha');
- $valuedeposit = GETPOST('valuedeposit', 'int');
- if ($typeamount == 'amount')
- {
- $amountdeposit = $valuedeposit;
- }
- else
- {
- $amountdeposit = 0;
- if ($result > 0)
- {
- $totalamount = 0;
- $lines = $srcobject->lines;
- $numlines=count($lines);
- for ($i=0; $i<$numlines; $i++)
- {
- $qualified=1;
- if (empty($lines[$i]->qty)) $qualified=0; // We discard qty=0, it is an option
- if (! empty($lines[$i]->special_code)) $qualified=0; // We discard special_code (frais port, ecotaxe, option, ...)
- if ($qualified) $totalamount += $lines[$i]->total_ht;
- }
- if ($totalamount != 0) {
- $amountdeposit = ($totalamount * $valuedeposit) / 100;
- }
- } else {
- setEventMessages($srcobject->error, $srcobject->errors, 'errors');
- $error ++;
- }
- }
- $result = $object->addline(
- $langs->trans('Deposit'),
- $amountdeposit, // subprice
- 1, // quantity
- $lines[$i]->tva_tx, 0, // localtax1_tx
- 0, // localtax2_tx
- 0, // fk_product
- 0, // remise_percent
- 0, // date_start
- 0, // date_end
- 0, $lines[$i]->info_bits, // info_bits
- 0, // info_bits
- 'HT',
- 0,
- 0, // product_type
- 1,
- $lines[$i]->special_code,
- $object->origin,
- 0,
- 0,
- 0,
- 0,
- $langs->trans('Deposit')
- );
- }
- else
- {
- if ($result > 0)
- {
- $lines = $srcobject->lines;
- if (empty($lines) && method_exists($srcobject, 'fetch_lines'))
- {
- $srcobject->fetch_lines();
- $lines = $srcobject->lines;
- }
- $fk_parent_line=0;
- $num=count($lines);
- for ($i=0;$i<$num;$i++)
- {
- // Don't add lines with qty 0 when coming from a shipment including all order lines
- if($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) continue;
- $label=(! empty($lines[$i]->label)?$lines[$i]->label:'');
- $desc=(! empty($lines[$i]->desc)?$lines[$i]->desc:$lines[$i]->libelle);
- if ($object->situation_counter == 1) $lines[$i]->situation_percent = 0;
- if ($lines[$i]->subprice < 0)
- {
- // Negative line, we create a discount line
- $discount = new DiscountAbsolute($db);
- $discount->fk_soc = $object->socid;
- $discount->amount_ht = abs($lines[$i]->total_ht);
- $discount->amount_tva = abs($lines[$i]->total_tva);
- $discount->amount_ttc = abs($lines[$i]->total_ttc);
- $discount->tva_tx = $lines[$i]->tva_tx;
- $discount->fk_user = $user->id;
- $discount->description = $desc;
- $discountid = $discount->create($user);
- if ($discountid > 0) {
- $result = $object->insert_discount($discountid); // This include link_to_invoice
- } else {
- setEventMessages($discount->error, $discount->errors, 'errors');
- $error ++;
- break;
- }
- } else {
- // Positive line
- $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
- // Date start
- $date_start = false;
- if ($lines[$i]->date_debut_prevue)
- $date_start = $lines[$i]->date_debut_prevue;
- if ($lines[$i]->date_debut_reel)
- $date_start = $lines[$i]->date_debut_reel;
- if ($lines[$i]->date_start)
- $date_start = $lines[$i]->date_start;
- // Date end
- $date_end = false;
- if ($lines[$i]->date_fin_prevue)
- $date_end = $lines[$i]->date_fin_prevue;
- if ($lines[$i]->date_fin_reel)
- $date_end = $lines[$i]->date_fin_reel;
- if ($lines[$i]->date_end)
- $date_end = $lines[$i]->date_end;
- // Reset fk_parent_line for no child products and special product
- if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
- $fk_parent_line = 0;
- }
- // Extrafields
- if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
- $lines[$i]->fetch_optionals($lines[$i]->rowid);
- $array_options = $lines[$i]->array_options;
- }
- // View third's localtaxes for now
- $localtax1_tx = get_localtax($lines[$i]->tva_tx, 1, $object->thirdparty);
- $localtax2_tx = get_localtax($lines[$i]->tva_tx, 2, $object->thirdparty);
- $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $localtax1_tx, $localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit);
- if ($result > 0) {
- $lineid = $result;
- } else {
- $lineid = 0;
- $error ++;
- break;
- }
- // Defined the new fk_parent_line
- if ($result > 0 && $lines[$i]->product_type == 9) {
- $fk_parent_line = $result;
- }
- }
- }
- } else {
- setEventMessages($srcobject->error, $srcobject->errors, 'errors');
- $error ++;
- }
- }
- // Now we create same links to contact than the ones found on origin object
- if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
- {
- $originforcontact = $object->origin;
- $originidforcontact = $object->origin_id;
- if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
- {
- $originforcontact=$srcobject->origin;
- $originidforcontact=$srcobject->origin_id;
- }
- $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
- $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
- $resqlcontact = $db->query($sqlcontact);
- if ($resqlcontact)
- {
- while($objcontact = $db->fetch_object($resqlcontact))
- {
- //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
- $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
- }
- }
- else dol_print_error($resqlcontact);
- }
- // Hooks
- $parameters = array('objFrom' => $srcobject);
- $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
- // modified by hook
- if ($reshook < 0)
- {
- setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
- $error++;
- }
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- $error++;
- }
- }
- else
- { // If some invoice's lines coming from page
- $id = $object->create($user);
- for ($i = 1; $i <= $NBLINES; $i ++) {
- if ($_POST['idprod' . $i]) {
- $product = new Product($db);
- $product->fetch($_POST['idprod' . $i]);
- $startday = dol_mktime(12, 0, 0, $_POST['date_start' . $i . 'month'], $_POST['date_start' . $i . 'day'], $_POST['date_start' . $i . 'year']);
- $endday = dol_mktime(12, 0, 0, $_POST['date_end' . $i . 'month'], $_POST['date_end' . $i . 'day'], $_POST['date_end' . $i . 'year']);
- $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);
- }
- }
- }
- }
- }
- if (GETPOST('type') == Facture::TYPE_SITUATION && (!empty($_POST['situations'])))
- {
- $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
- if (empty($datefacture)) {
- $error++;
- $mesg = '<div class="error">' . $langs->trans("ErrorFieldRequired", $langs->trans("Date")) . '</div>';
- }
- $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
- if (!($_POST['situations'] > 0)) {
- $error++;
- $mesg = '<div class="error">' . $langs->trans("ErrorFieldRequired", $langs->trans("InvoiceSituation")) . '</div>';
- }
- if (!$error) {
- $result = $object->fetch($_POST['situations']);
- $object->fk_facture_source = $_POST['situations'];
- $object->type = Facture::TYPE_SITUATION;
- if (!empty($origin) && !empty($originid))
- {
- $object->origin = $origin;
- $object->origin_id = $originid;
- foreach ($object->lines as &$line)
- {
- $line->origin = $object->origin;
- $line->origin_id = $line->id;
- }
- }
- $object->fetch_thirdparty();
- $object->date = $datefacture;
- $object->date_pointoftax = $date_pointoftax;
- $object->note_public = trim($_POST['note_public']);
- $object->note = trim($_POST['note']);
- $object->ref_client = $_POST['ref_client'];
- $object->ref_int = $_POST['ref_int'];
- $object->modelpdf = $_POST['model'];
- $object->fk_project = $_POST['projectid'];
- $object->cond_reglement_id = $_POST['cond_reglement_id'];
- $object->mode_reglement_id = $_POST['mode_reglement_id'];
- $object->remise_absolue = $_POST['remise_absolue'];
- $object->remise_percent = $_POST['remise_percent'];
- // Proprietes particulieres a facture de remplacement
- $object->situation_counter = $object->situation_counter + 1;
- $id = $object->createFromCurrent($user);
- if ($id <= 0) $mesg = $object->error;
- }
- }
- // End of object creation, we show it
- if ($id > 0 && ! $error)
- {
- $db->commit();
- header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
- exit();
- }
- else
- {
- $db->rollback();
- $action = 'create';
- $_GET["origin"] = $_POST["origin"];
- $_GET["originid"] = $_POST["originid"];
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- // Add a new line
- else if ($action == 'addline' && $user->rights->facture->creer)
- {
- $langs->load('errors');
- $error = 0;
- // Set if we used free entry or predefined product
- $predef='';
- $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
- $price_ht = GETPOST('price_ht');
- if (GETPOST('prod_entry_mode') == 'free')
- {
- $idprod=0;
- $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
- }
- else
- {
- $idprod=GETPOST('idprod', 'int');
- $tva_tx = '';
- }
- $qty = GETPOST('qty' . $predef);
- $remise_percent = GETPOST('remise_percent' . $predef);
- // Extrafields
- $extrafieldsline = new ExtraFields($db);
- $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
- $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
- // Unset extrafield
- if (is_array($extralabelsline)) {
- // Get extra fields
- foreach ($extralabelsline as $key => $value) {
- unset($_POST["options_" . $key . $predef]);
- }
- }
- if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) {
- setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
- $error ++;
- }
- if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) {
- setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
- $error ++;
- }
- if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not ''
- {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
- $error ++;
- }
- if ($qty == '') {
- setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
- $error ++;
- }
- if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) {
- setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
- $error ++;
- }
- if ($qty < 0) {
- $langs->load("errors");
- setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
- $error ++;
- }
- if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) {
- $ret = $object->fetch($id);
- if ($ret < 0) {
- dol_print_error($db, $object->error);
- exit();
- }
- $ret = $object->fetch_thirdparty();
- // Clean parameters
- $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'));
- $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'));
- $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
- // Define special_code for special lines
- $special_code = 0;
- // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices
- // Ecrase $pu par celui du produit
- // Ecrase $desc par celui du produit
- // Ecrase $txtva par celui du produit
- // Ecrase $base_price_type par celui du produit
- // Replaces $fk_unit with the product's
- if (! empty($idprod))
- {
- $prod = new Product($db);
- $prod->fetch($idprod);
- $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
- // Update if prices fields are defined
- $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
- $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
- if (empty($tva_tx)) $tva_npr=0;
- $pu_ht = $prod->price;
- $pu_ttc = $prod->price_ttc;
- $price_min = $prod->price_min;
- $price_base_type = $prod->price_base_type;
- // We define price for product
- if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
- {
- $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
- $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
- $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
- $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
- if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility
- {
- if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level];
- if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level];
- if (empty($tva_tx)) $tva_npr=0;
- }
- }
- elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
- {
- require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
- $prodcustprice = new Productcustomerprice($db);
- $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
- $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
- if ($result) {
- if (count($prodcustprice->lines) > 0) {
- $pu_ht = price($prodcustprice->lines[0]->price);
- $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
- $price_base_type = $prodcustprice->lines[0]->price_base_type;
- $prod->tva_tx = $prodcustprice->lines[0]->tva_tx;
- }
- }
- }
- // if price ht was forced (ie: from gui when calculated by margin rate and cost price)
- if (! empty($price_ht))
- {
- $pu_ht = price2num($price_ht, 'MU');
- $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 100)), 'MU');
- }
- // On reevalue prix selon taux tva car taux tva transaction peut etre different
- // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
- elseif ($tva_tx != $prod->tva_tx)
- {
- if ($price_base_type != 'HT')
- {
- $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU');
- }
- else
- {
- $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 100)), 'MU');
- }
- }
- $desc = '';
- // Define output language
- if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
- $outputlangs = $langs;
- $newlang = '';
- if (empty($newlang) && GETPOST('lang_id'))
- $newlang = GETPOST('lang_id');
- if (empty($newlang))
- $newlang = $object->thirdparty->default_lang;
- if (! empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
- } else {
- $desc = $prod->description;
- }
- $desc = dol_concatdesc($desc, $product_desc);
- // Add custom code and origin country into description
- if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) {
- $tmptxt = '(';
- if (! empty($prod->customcode))
- $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
- if (! empty($prod->customcode) && ! empty($prod->country_code))
- $tmptxt .= ' - ';
- if (! empty($prod->country_code))
- $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0);
- $tmptxt .= ')';
- $desc = dol_concatdesc($desc, $tmptxt);
- }
- $type = $prod->type;
- $fk_unit = $prod->fk_unit;
- } else {
- $pu_ht = price2num($price_ht, 'MU');
- $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
- $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
- $tva_tx = str_replace('*', '', $tva_tx);
- if (empty($tva_tx)) $tva_npr=0;
- $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
- $desc = $product_desc;
- $type = GETPOST('type');
- $fk_unit= GETPOST('units', 'alpha');
- }
- // Margin
- $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : '');
- $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value
- // Local Taxes
- $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
- $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
- $info_bits = 0;
- if ($tva_npr)
- $info_bits |= 0x01;
- if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) {
- $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
- setEventMessages($mesg, null, 'errors');
- } else {
- // Insert line
- $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);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (! empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model=$object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
- $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
- }
- unset($_POST['prod_entry_mode']);
- unset($_POST['qty']);
- unset($_POST['type']);
- unset($_POST['remise_percent']);
- unset($_POST['price_ht']);
- unset($_POST['multicurrency_price_ht']);
- unset($_POST['price_ttc']);
- unset($_POST['tva_tx']);
- unset($_POST['product_ref']);
- unset($_POST['product_label']);
- unset($_POST['product_desc']);
- unset($_POST['fournprice']);
- unset($_POST['buying_price']);
- unset($_POST['np_marginRate']);
- unset($_POST['np_markRate']);
- unset($_POST['dp_desc']);
- unset($_POST['idprod']);
- unset($_POST['units']);
- unset($_POST['date_starthour']);
- unset($_POST['date_startmin']);
- unset($_POST['date_startsec']);
- unset($_POST['date_startday']);
- unset($_POST['date_startmonth']);
- unset($_POST['date_startyear']);
- unset($_POST['date_endhour']);
- unset($_POST['date_endmin']);
- unset($_POST['date_endsec']);
- unset($_POST['date_endday']);
- unset($_POST['date_endmonth']);
- unset($_POST['date_endyear']);
- unset($_POST['situations']);
- unset($_POST['progress']);
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- $action = '';
- }
- }
- }
- elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel'))
- {
- if (! $object->fetch($id) > 0) dol_print_error($db);
- $object->fetch_thirdparty();
- // Clean parameters
- $date_start = '';
- $date_end = '';
- $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
- $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
- $description = dol_htmlcleanlastbr(GETPOST('product_desc') ? GETPOST('product_desc') : GETPOST('desc'));
- $pu_ht = GETPOST('price_ht');
- $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
- $qty = GETPOST('qty');
- // Define info_bits
- $info_bits = 0;
- if (preg_match('/\*/', $vat_rate))
- $info_bits |= 0x01;
- // Define vat_rate
- $vat_rate = str_replace('*', '', $vat_rate);
- $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
- $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
- // Add buying price
- $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
- $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
- // Extrafields
- $extrafieldsline = new ExtraFields($db);
- $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
- $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline);
- // Unset extrafield
- if (is_array($extralabelsline)) {
- // Get extra fields
- foreach ($extralabelsline as $key => $value) {
- unset($_POST["options_" . $key]);
- }
- }
- // Define special_code for special lines
- $special_code=GETPOST('special_code');
- if (! GETPOST('qty')) $special_code=3;
- $line = new FactureLigne($db);
- $line->fetch(GETPOST('lineid'));
- $percent = $line->get_prev_progress($object->id);
- if (GETPOST('progress') < $percent)
- {
- $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
- setEventMessages($mesg, null, 'warnings');
- $error++;
- $result = -1;
- }
- // Check minimum price
- $productid = GETPOST('productid', 'int');
- if (! empty($productid))
- {
- $product = new Product($db);
- $product->fetch($productid);
- $type = $product->type;
- $price_min = $product->price_min;
- if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level))
- $price_min = $product->multiprices_min [$object->thirdparty->price_level];
- $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
- // Check price is not lower than minimum (check is done only for standard or replacement invoices)
- 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))) {
- setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
- $error ++;
- }
- } else {
- $type = GETPOST('type');
- $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
- // Check parameters
- if (GETPOST('type') < 0) {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
- $error ++;
- }
- }
- if ($qty < 0) {
- $langs->load("errors");
- setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
- $error ++;
- }
- // Update line
- if (! $error) {
- $result = $object->updateline(GETPOST('lineid'), $description, $pu_ht, $qty, GETPOST('remise_percent'),
- $date_start, $date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $info_bits, $type,
- GETPOST('fk_parent_line'), 0, $fournprice, $buyingprice, $label, $special_code, $array_options, GETPOST('progress'),
- $_POST['units']);
- if ($result >= 0) {
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
- // Define output language
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id'))
- $newlang = GETPOST('lang_id');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang))
- $newlang = $object->thirdparty->default_lang;
- if (! empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- unset($_POST['qty']);
- unset($_POST['type']);
- unset($_POST['productid']);
- unset($_POST['remise_percent']);
- unset($_POST['price_ht']);
- unset($_POST['multicurrency_price_ht']);
- unset($_POST['price_ttc']);
- unset($_POST['tva_tx']);
- unset($_POST['product_ref']);
- unset($_POST['product_label']);
- unset($_POST['product_desc']);
- unset($_POST['fournprice']);
- unset($_POST['buying_price']);
- unset($_POST['np_marginRate']);
- unset($_POST['np_markRate']);
- unset($_POST['dp_desc']);
- unset($_POST['idprod']);
- unset($_POST['units']);
- unset($_POST['date_starthour']);
- unset($_POST['date_startmin']);
- unset($_POST['date_startsec']);
- unset($_POST['date_startday']);
- unset($_POST['date_startmonth']);
- unset($_POST['date_startyear']);
- unset($_POST['date_endhour']);
- unset($_POST['date_endmin']);
- unset($_POST['date_endsec']);
- unset($_POST['date_endday']);
- unset($_POST['date_endmonth']);
- unset($_POST['date_endyear']);
- unset($_POST['situations']);
- unset($_POST['progress']);
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- }
- else if ($action == 'updatealllines' && $user->rights->facture->creer && $_POST['all_percent'] == $langs->trans('Modifier'))
- {
- if (!$object->fetch($id) > 0) dol_print_error($db);
- if (!is_null(GETPOST('all_progress')) && GETPOST('all_progress') != "")
- {
- foreach ($object->lines as $line)
- {
- $percent = $line->get_prev_progress($object->id);
- if (GETPOST('all_progress') < $percent) {
- $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
- $result = -1;
- } else
- $object->update_percent($line, $_POST['all_progress']);
- }
- }
- }
- else if ($action == 'updateligne' && $user->rights->facture->creer && $_POST['cancel'] == $langs->trans('Cancel')) {
- header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); // Pour reaffichage de la fiche en cours d'edition
- exit();
- }
- /*
- * Send mail
- */
- // Actions to send emails
- if (empty($id)) $id=$facid;
- $actiontypecode='AC_FAC';
- $trigger_name='BILL_SENTBYMAIL';
- $paramname='id';
- $mode='emailfrominvoice';
- include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
- // Actions to build doc
- $upload_dir = $conf->facture->dir_output;
- $permissioncreate=$user->rights->facture->creer;
- include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
- if ($action == 'update_extras') {
- // Fill array 'array_options' with data from add form
- $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
- $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute'));
- if ($ret < 0) $error++;
- if (! $error) {
- // Actions on extra fields (by external module or standard code)
- // TODO le hook fait double emploi avec le trigger !!
- $hookmanager->initHooks(array('invoicedao'));
- $parameters = array('id' => $object->id);
- $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by
- // some hooks
- if (empty($reshook)) {
- $result = $object->insertExtraFields();
- if ($result < 0) {
- $error ++;
- }
- } else if ($reshook < 0)
- $error ++;
- }
- if ($error)
- $action = 'edit_extras';
- }
- include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
- if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->facture->creer) {
- if ($action == 'addcontact') {
- $result = $object->fetch($id);
- if ($result > 0 && $id > 0) {
- $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
- $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
- }
- if ($result >= 0) {
- header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
- exit();
- } else {
- if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
- $langs->load("errors");
- setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- } // bascule du statut d'un contact
- elseif ($action == 'swapstatut') {
- if ($object->fetch($id)) {
- $result = $object->swapContactStatus(GETPOST('ligne'));
- } else {
- dol_print_error($db);
- }
- } // Efface un contact
- elseif ($action == 'deletecontact') {
- $object->fetch($id);
- $result = $object->delete_contact($lineid);
- if ($result >= 0) {
- header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
- exit();
- } else {
- dol_print_error($db);
- }
- }
- if ($error)
- $action = 'edit_extras';
- }
- }
- /*
- * View
- */
- $form = new Form($db);
- $formother = new FormOther($db);
- $formfile = new FormFile($db);
- $formmargin = new FormMargin($db);
- $paymentstatic=new Paiement($db);
- $bankaccountstatic = new Account($db);
- if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
- $now = dol_now();
- $title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('Card');
- $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
- llxHeader('', $title, $helpurl);
- // Mode creation
- if ($action == 'create')
- {
- $facturestatic = new Facture($db);
- $extralabels = $extrafields->fetch_name_optionals_label($facturestatic->table_element);
- print load_fiche_titre($langs->trans('NewBill'));
- $soc = new Societe($db);
- if ($socid > 0)
- $res = $soc->fetch($socid);
- $currency_code = $conf->currency;
- // Load objectsrc
- $remise_absolue = 0;
- if (! empty($origin) && ! empty($originid))
- {
- // Parse element/subelement (ex: project_task)
- $element = $subelement = $origin;
- if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
- $element = $regs [1];
- $subelement = $regs [2];
- }
- if ($element == 'project') {
- $projectid = $originid;
- if (!$cond_reglement_id) {
- $cond_reglement_id = $soc->cond_reglement_id;
- }
- if (!$mode_reglement_id) {
- $mode_reglement_id = $soc->mode_reglement_id;
- }
- if (!$remise_percent) {
- $remise_percent = $soc->remise_percent;
- }
- if (!$dateinvoice) {
- // Do not set 0 here (0 for a date is 1970)
- $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice);
- }
- } else {
- // For compatibility
- if ($element == 'order' || $element == 'commande') {
- $element = $subelement = 'commande';
- }
- if ($element == 'propal') {
- $element = 'comm/propal';
- $subelement = 'propal';
- }
- if ($element == 'contract') {
- $element = $subelement = 'contrat';
- }
- if ($element == 'shipping') {
- $element = $subelement = 'expedition';
- }
- dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
- $classname = ucfirst($subelement);
- $objectsrc = new $classname($db);
- $objectsrc->fetch($originid);
- if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines'))
- $objectsrc->fetch_lines();
- $objectsrc->fetch_thirdparty();
- $projectid = (! empty($projectid) ? $projectid : $objectsrc->fk_project);
- $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : (! empty($objectsrc->ref_customer) ? $objectsrc->ref_customer:''));
- $ref_int = (! empty($objectsrc->ref_int) ? $objectsrc->ref_int : '');
- // only if socid not filled else it's allready done upper
- if (empty($socid))
- $soc = $objectsrc->thirdparty;
- $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1));
- $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
- $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0));
- $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0));
- $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0));
- $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice);
- if (!empty($conf->multicurrency->enabled))
- {
- if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code;
- if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx;
- }
- // Replicate extrafields
- $objectsrc->fetch_optionals($originid);
- $object->array_options = $objectsrc->array_options;
- }
- }
- else
- {
- $cond_reglement_id = $soc->cond_reglement_id;
- $mode_reglement_id = $soc->mode_reglement_id;
- $fk_account = $soc->fk_account;
- $remise_percent = $soc->remise_percent;
- $remise_absolue = 0;
- $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); // Do not set 0 here (0 for a date is 1970)
- if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code;
- }
- if(!empty($soc->id)) $absolute_discount = $soc->getAvailableDiscounts();
- if (! empty($conf->use_javascript_ajax))
- {
- require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
- print ajax_combobox('fac_replacement');
- print ajax_combobox('fac_avoir');
- print ajax_combobox('situations');
- }
- if ($origin == 'contrat')
- {
- $langs->load("admin");
- $text=$langs->trans("ToCreateARecurringInvoice");
- $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates"));
- if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE))
- {
- $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
- }
- print info_admin($text, 0, 0, 0).'<br>';
- }
- print '<form name="add" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
- print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
- print '<input type="hidden" name="action" value="add">';
- if ($soc->id > 0) print '<input type="hidden" name="socid" value="' . $soc->id . '">' . "\n";
- print '<input name="facnumber" type="hidden" value="provisoire">';
- print '<input name="ref_client" type="hidden" value="' . $ref_client . '">';
- print '<input name="ref_int" type="hidden" value="' . $ref_int . '">';
- print '<input type="hidden" name="origin" value="' . $origin . '">';
- print '<input type="hidden" name="originid" value="' . $originid . '">';
- if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="' . $currency_tx . '">';
- dol_fiche_head('');
- print '<table class="border" width="100%">';
- // Ref
- print '<tr><td class="titlefieldcreate fieldrequired">' . $langs->trans('Ref') . '</td><td colspan="2">' . $langs->trans('Draft') . '</td></tr>';
- // Thirdparty
- print '<td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
- if ($soc->id > 0 && ! GETPOST('fac_rec'))
- {
- print '<td colspan="2">';
- print $soc->getNomUrl(1);
- print '<input type="hidden" name="socid" value="' . $soc->id . '">';
- // Outstanding Bill
- $outstandingBills = $soc->get_OutstandingBill();
- print ' (' . $langs->trans('CurrentOutstandingBill') . ': ';
- print price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency);
- if ($soc->outstanding_limit != '')
- {
- if ($outstandingBills > $soc->outstanding_limit) print img_warning($langs->trans("OutstandingBillReached"));
- print ' / ' . price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
- }
- print ')';
- print '</td>';
- }
- else
- {
- print '<td colspan="2">';
- print $form->select_company($soc->id, 'socid', '(s.client = 1 OR s.client = 3) AND status=1', 'SelectThirdParty');
- // Option to reload page to retrieve customer informations. Note, this clear other input
- if (!empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE))
- {
- print '<script type="text/javascript">
- $(document).ready(function() {
- $("#socid").change(function() {
- var socid = $(this).val();
- var fac_rec = $(\'#fac_rec\').val();
- // reload page
- window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
- });
- });
- </script>';
- }
- print '</td>';
- }
- print '</tr>' . "\n";
- // Predefined invoices
- if (empty($origin) && empty($originid) && GETPOST('fac_rec','int') > 0)
- {
- $invoice_predefined = new FactureRec($db);
- $invoice_predefined->fetch(GETPOST('fac_rec','int'));
- $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
- $sql = 'SELECT r.rowid, r.titre, r.total_ttc';
- $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as r';
- $sql .= ' WHERE r.fk_soc = ' . $invoice_predefined->socid;
- $resql = $db->query($sql);
- if ($resql)
- {
- $num = $db->num_rows($resql);
- $i = 0;
- if ($num > 0)
- {
- print '<tr><td>' . $langs->trans('CreateFromRepeatableInvoice') . '</td><td>';
- print '<select class="flat" id="fac_rec" name="fac_rec">';
- print '<option value="0" selected></option>';
- while ($i < $num)
- {
- $objp = $db->fetch_object($resql);
- print '<option value="' . $objp->rowid . '"';
- if (GETPOST('fac_rec') == $objp->rowid)
- print ' selected';
- print '>' . $objp->titre . ' (' . price($objp->total_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
- $i ++;
- }
- print '</select>';
- // Option to reload page to retrieve customer informations. Note, this clear other input
- if (!empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE))
- {
- print '<script type="text/javascript">
- $(document).ready(function() {
- $("#fac_rec").change(function() {
- var fac_rec = $(this).val();
- var socid = $(\'#socid\').val();
- // reload page
- window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
- });
- });
- </script>';
- }
- print '</td></tr>';
- }
- $db->free($resql);
- } else {
- dol_print_error($db);
- }
- }
- // Type de facture
- $facids = $facturestatic->list_replacable_invoices($soc->id);
- if ($facids < 0) {
- dol_print_error($db, $facturestatic);
- exit();
- }
- $options = "";
- foreach ($facids as $facparam)
- {
- $options .= '<option value="' . $facparam ['id'] . '"';
- if ($facparam ['id'] == $_POST['fac_replacement'])
- $options .= ' selected';
- $options .= '>' . $facparam ['ref'];
- $options .= ' (' . $facturestatic->LibStatut(0, $facparam ['status']) . ')';
- $options .= '</option>';
- }
- // Show link for credit note
- $facids=$facturestatic->list_qualified_avoir_invoices($soc->id);
- if ($facids < 0)
- {
- dol_print_error($db,$facturestatic);
- exit;
- }
- $optionsav = "";
- $newinvoice_static = new Facture($db);
- foreach ($facids as $key => $valarray)
- {
- $newinvoice_static->id = $key;
- $newinvoice_static->ref = $valarray ['ref'];
- $newinvoice_static->statut = $valarray ['status'];
- $newinvoice_static->type = $valarray ['type'];
- $newinvoice_static->paye = $valarray ['paye'];
- $optionsav .= '<option value="' . $key . '"';
- if ($key == GETPOST('fac_avoir'))
- $optionsav .= ' selected';
- $optionsav .= '>';
- $optionsav .= $newinvoice_static->ref;
- $optionsav .= ' (' . $newinvoice_static->getLibStatut(1, $valarray ['paymentornot']) . ')';
- $optionsav .= '</option>';
- }
- print '<tr><td valign="top" class="fieldrequired">' . $langs->trans('Type') . '</td><td colspan="2">';
- print '<div class="tagtable">' . "\n";
- // Standard invoice
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" id="radio_standard" name="type" value="0"' . (GETPOST('type') == 0 ? ' checked' : '') . '> ';
- $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
- print $desc;
- print '</div></div>';
- if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (! empty($originid))))
- {
- // Deposit
- if (empty($conf->global->INVOICE_DISABLE_DEPOSIT))
- {
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
- print '<script type="text/javascript" language="javascript">
- jQuery(document).ready(function() {
- jQuery("#typedeposit, #valuedeposit").click(function() {
- jQuery("#radio_deposit").prop("checked", true);
- });
- });
- </script>';
-
- $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
- print '<table class="nobordernopadding"><tr><td>';
- print $desc;
- print '</td>';
- if (($origin == 'propal') || ($origin == 'commande'))
- {
- print '<td class="nowrap" style="padding-left: 5px">';
- $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount');
- print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1);
- print '</td>';
- print '<td class="nowrap" style="padding-left: 5px">' . $langs->trans('Value') . ':<input type="text" id="valuedeposit" name="valuedeposit" size="3" value="' . GETPOST('valuedeposit', 'int') . '"/>';
- }
- print '</td></tr></table>';
-
- print '</div></div>';
- }
- }
- if ($socid > 0)
- {
- if (! empty($conf->global->INVOICE_USE_SITUATION))
- {
- // First situation invoice
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" name="type" value="5"' . (GETPOST('type') == 5 ? ' checked' : '') . '> ';
- $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceFirstSituationAsk"), $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3);
- print $desc;
- print '</div></div>';
- // Next situation invoice
- $opt = $form->selectSituationInvoices(GETPOST('originid'), $socid);
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" name="type" value="5"' . (GETPOST('type') == 5 && GETPOST('originid') ? ' checked' : '');
- if ($opt == ('<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) $tmp.=' disabled';
- $tmp.= '> ';
- $text = $tmp.$langs->trans("InvoiceSituationAsk") . ' ';
- $text .= '<select class="flat" id="situations" name="situations">';
- $text .= $opt;
- $text .= '</select>';
- $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceSituationDesc"), 1, 'help', '', 0, 3);
- print $desc;
- print '</div></div>';
- }
- // Replacement
- if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT))
- {
- print '<!-- replacement line -->';
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
- if (! $options) $tmp.=' disabled';
- $tmp.='> ';
- print '<script type="text/javascript" language="javascript">
- jQuery(document).ready(function() {
- jQuery("#fac_replacement").change(function() {
- jQuery("#radio_replacement").prop("checked", true);
- });
- });
- </script>';
- $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' ';
- $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
- if (! $options)
- $text .= ' disabled';
- $text .= '>';
- if ($options) {
- $text .= '<option value="-1"> </option>';
- $text .= $options;
- } else {
- $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
- }
- $text .= '</select>';
- $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
- print $desc;
- print '</div></div>';
- }
- }
- else
- {
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
- $text = $tmp.$langs->trans("InvoiceReplacement") . ' ';
- $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') ';
- $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
- print $desc;
- print '</div></div>';
- }
- if (empty($origin))
- {
- if ($socid > 0)
- {
- // Credit note
- if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE))
- {
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" id="radio_creditnote" name="type" value="2"' . (GETPOST('type') == 2 ? ' checked' : '');
- if (! $optionsav) $tmp.=' disabled';
- $tmp.= '> ';
- // Show credit note options only if we checked credit note
- print '<script type="text/javascript" language="javascript">
- jQuery(document).ready(function() {
- if (! jQuery("#radio_creditnote").is(":checked"))
- {
- jQuery("#credit_note_options").hide();
- }
- jQuery("#radio_creditnote").click(function() {
- jQuery("#credit_note_options").show();
- });
- jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
- jQuery("#credit_note_options").hide();
- });
- });
- </script>';
- $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' ';
- // $text.='<input type="text" value="">';
- $text .= '<select class="flat" name="fac_avoir" id="fac_avoir"';
- if (! $optionsav)
- $text .= ' disabled';
- $text .= '>';
- if ($optionsav) {
- $text .= '<option value="-1"></option>';
- $text .= $optionsav;
- } else {
- $text .= '<option value="-1">' . $langs->trans("NoInvoiceToCorrect") . '</option>';
- }
- $text .= '</select>';
- $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
- print $desc;
-
- print '<div id="credit_note_options" class="clearboth">';
- print ' <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>";
- print '<br> <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>";
- print '</div>';
-
- print '</div></div>';
- }
- }
- else
- {
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
- $text = $tmp.$langs->trans("InvoiceAvoir") . ' ';
- $text.= '('.$langs->trans("YouMustCreateInvoiceFromThird").') ';
- $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
- print $desc;
- print '</div></div>' . "\n";
- }
- }
- // Template invoice
- print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
- $tmp='<input type="radio" name="type" id="radio_template" value="0" disabled> ';
- $text = $tmp.$langs->trans("RepeatableInvoice") . ' ';
- //$text.= '('.$langs->trans("YouMustCreateStandardInvoiceFirst").') ';
- $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3);
- print $desc;
- print '</div></div>';
- print '</div>';
- print '</td></tr>';
- if ($socid > 0)
- {
- // Discounts for third party
- print '<tr><td>' . $langs->trans('Discounts') . '</td><td colspan="2">';
- if ($soc->remise_percent)
- 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>');
- else
- print $langs->trans("CompanyHasNoRelativeDiscount");
- 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>';
- print '. ';
- print '<br>';
- if ($absolute_discount)
- 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));
- else
- print $langs->trans("CompanyHasNoAbsoluteDiscount");
- 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>';
- print '.';
- print '</td></tr>';
- }
- // Date invoice
- print '<tr><td class="fieldrequired">' . $langs->trans('DateInvoice') . '</td><td colspan="2">';
- $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
- print $form->select_date($datefacture?$datefacture:$dateinvoice, '', '', '', '', "add", 1, 1, 1);
- print '</td></tr>';
- // Date point of tax
- if (! empty($conf->global->INVOICE_POINTOFTAX_DATE))
- {
- print '<tr><td class="fieldrequired">' . $langs->trans('DatePointOfTax') . '</td><td colspan="2">';
- $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']);
- print $form->select_date($date_pointoftax?$date_pointoftax:-1, 'date_pointoftax', '', '', '', "add", 1, 1, 1);
- print '</td></tr>';
- }
- // Payment term
- print '<tr><td class="nowrap fieldrequired">' . $langs->trans('PaymentConditionsShort') . '</td><td colspan="2">';
- $form->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id');
- print '</td></tr>';
- // Payment mode
- print '<tr><td>' . $langs->trans('PaymentMode') . '</td><td colspan="2">';
- $form->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id', 'CRDT');
- print '</td></tr>';
- // Bank Account
- if (isset($_POST['fk_account'])) {
- $fk_account = $_POST['fk_account'];
- }
- print '<tr><td>' . $langs->trans('BankAccount') . '</td><td colspan="2">';
- $form->select_comptes($fk_account, 'fk_account', 0, '', 1);
- print '</td></tr>';
- // Project
- if (! empty($conf->projet->enabled) && $socid > 0)
- {
- $langs->load('projects');
- print '<tr><td>' . $langs->trans('Project') . '</td><td colspan="2">';
- $numprojet = $formproject->select_projects($socid, $projectid, 'projectid', 0);
- print ' <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>';
- print '</td></tr>';
- }
- // Incoterms
- if (!empty($conf->incoterm->enabled))
- {
- print '<tr>';
- print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $objectsrc->libelle_incoterms, 1).'</label></td>';
- print '<td colspan="2" class="maxwidthonsmartphone">';
- print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:''));
- print '</td></tr>';
- }
- // Other attributes
- $parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"');
- $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by
- // hook
- if (empty($reshook) && ! empty($extrafields->attribute_label)) {
- print $object->showOptionals($extrafields, 'edit');
- }
- // Template to use by default
- print '<tr><td>' . $langs->trans('Model') . '</td>';
- print '<td colspan="2">';
- include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
- $liste = ModelePDFFactures::liste_modeles($db);
- print $form->selectarray('model', $liste, $conf->global->FACTURE_ADDON_PDF);
- print "</td></tr>";
- // Multicurrency
- if (! empty($conf->multicurrency->enabled))
- {
- print '<tr>';
- print '<td>'.fieldLabel('Currency','multicurrency_code').'</td>';
- print '<td colspan="2" class="maxwidthonsmartphone">';
- print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
- print '</td></tr>';
- }
- // Public note
- print '<tr>';
- print '<td class="border" valign="top">' . $langs->trans('NotePublic') . '</td>';
- print '<td valign="top" colspan="2">';
- $note_public = $object->getDefaultCreateValueFor('note_public', (is_object($objectsrc)?$objectsrc->note_public:null));
- $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
- print $doleditor->Create(1);
- // Private note
- if (empty($user->societe_id))
- {
- print '<tr>';
- print '<td class="border" valign="top">' . $langs->trans('NotePrivate') . '</td>';
- print '<td valign="top" colspan="2">';
- $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null));
- $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
- print $doleditor->Create(1);
- // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
- print '</td></tr>';
- }
- // Lines from source
- if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
- {
- // TODO for compatibility
- if ($origin == 'contrat') {
- // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
- $objectsrc->remise_absolue = $remise_absolue;
- $objectsrc->remise_percent = $remise_percent;
- $objectsrc->update_price(1, - 1, 1);
- }
- print "\n<!-- " . $classname . " info -->";
- print "\n";
- print '<input type="hidden" name="amount" value="' . $objectsrc->total_ht . '">' . "\n";
- print '<input type="hidden" name="total" value="' . $objectsrc->total_ttc . '">' . "\n";
- print '<input type="hidden" name="tva" value="' . $objectsrc->total_tva . '">' . "\n";
- print '<input type="hidden" name="origin" value="' . $objectsrc->element . '">';
- print '<input type="hidden" name="originid" value="' . $objectsrc->id . '">';
- switch ($classname) {
- case 'Propal':
- $newclassname = 'CommercialProposal';
- break;
- case 'Commande':
- $newclassname = 'Order';
- break;
- case 'Expedition':
- $newclassname = 'Sending';
- break;
- case 'Contrat':
- $newclassname = 'Contract';
- break;
- case 'Fichinter':
- $newclassname = 'Intervention';
- break;
- default:
- $newclassname = $classname;
- }
- print '<tr><td>' . $langs->trans($newclassname) . '</td><td colspan="2">' . $objectsrc->getNomUrl(1);
- // We check if Origin document (id and type is known) has already at least one invoice attached to it
- $objectsrc->fetchObjectLinked($originid,$origin,'','facture');
- $cntinvoice=count($objectsrc->linkedObjects['facture']);
- if ($cntinvoice>=1)
- {
- setEventMessages('WarningBillExist', null, 'warnings');
- echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')';
- }
- echo '</td></tr>';
- print '<tr><td>' . $langs->trans('TotalHT') . '</td><td colspan="2">' . price($objectsrc->total_ht) . '</td></tr>';
- print '<tr><td>' . $langs->trans('TotalVAT') . '</td><td colspan="2">' . price($objectsrc->total_tva) . "</td></tr>";
- if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1
- {
- print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax1) . "</td></tr>";
- }
- if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2
- {
- print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax2) . "</td></tr>";
- }
- print '<tr><td>' . $langs->trans('TotalTTC') . '</td><td colspan="2">' . price($objectsrc->total_ttc) . "</td></tr>";
- if (!empty($conf->multicurrency->enabled))
- {
- print '<tr><td>' . $langs->trans('MulticurrencyTotalHT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ht) . '</td></tr>';
- print '<tr><td>' . $langs->trans('MulticurrencyTotalVAT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_tva) . "</td></tr>";
- print '<tr><td>' . $langs->trans('MulticurrencyTotalTTC') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>";
- }
- }
- print "</table>\n";
- dol_fiche_end();
- // Button "Create Draft"
- print '<div class="center">';
- print '<input type="submit" class="button" name="bouton" value="' . $langs->trans('CreateDraft') . '">';
- print ' ';
- print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
- print '</div>';
- print "</form>\n";
- // Show origin lines
- if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) {
- print '<br>';
- $title = $langs->trans('ProductsAndServices');
- print load_fiche_titre($title);
- print '<table class="noborder" width="100%">';
- $objectsrc->printOriginLinesList();
- print '</table>';
- }
- print '<br>';
- }
- else if ($id > 0 || ! empty($ref))
- {
- /*
- * Show object in view mode
- */
- $result = $object->fetch($id, $ref);
- if ($result <= 0) {
- dol_print_error($db, $object->error);
- exit();
- }
- // fetch optionals attributes and labels
- $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
- if ($user->societe_id > 0 && $user->societe_id != $object->socid)
- accessforbidden('', 0);
- $result = $object->fetch_thirdparty();
- $soc = new Societe($db);
- $result=$soc->fetch($object->socid);
- if ($result < 0) dol_print_error($db);
- $selleruserevenustamp = $mysoc->useRevenueStamp();
- $totalpaye = $object->getSommePaiement();
- $totalcreditnotes = $object->getSumCreditNotesUsed();
- $totaldeposits = $object->getSumDepositsUsed();
- // print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
- // selleruserrevenuestamp=".$selleruserevenustamp;
- // We can also use bcadd to avoid pb with floating points
- // For example print 239.2 - 229.3 - 9.9; does not return 0.
- // $resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
- // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
- $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
- if ($object->paye)
- $resteapayer = 0;
- $resteapayeraffiche = $resteapayer;
- if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
- $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
- $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
- } else {
- $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')";
- $filtercreditnote = "fk_facture_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'";
- }
- $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
- $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
- $absolute_discount = price2num($absolute_discount, 'MT');
- $absolute_creditnote = price2num($absolute_creditnote, 'MT');
- $author = new User($db);
- if ($object->user_author) {
- $author->fetch($object->user_author);
- }
- $objectidnext = $object->getIdReplacingInvoice();
- $head = facture_prepare_head($object);
- dol_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), 0, 'bill');
- $formconfirm = '';
- // Confirmation de la conversion de l'avoir en reduc
- if ($action == 'converttoreduc') {
- $text = $langs->trans('ConfirmConvertToReduc');
- $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
- }
- // Confirmation to delete invoice
- if ($action == 'delete') {
- $text = $langs->trans('ConfirmDeleteBill', $object->ref);
- $formquestion = array();
- $qualified_for_stock_change = 0;
- if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
- $qualified_for_stock_change = $object->hasProductsOrServices(2);
- } else {
- $qualified_for_stock_change = $object->hasProductsOrServices(1);
- }
- if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change && $object->statut >= 1)
- {
- $langs->load("stocks");
- require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
- $formproduct = new FormProduct($db);
- $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
- $formquestion = array(
- // 'text' => $langs->trans("ConfirmClone"),
- // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
- // 1),
- // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
- // => 1),
- array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, $langs->trans("NoStockAction"))));
- $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
- } else {
- $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', '', 1);
- }
- }
- // Confirmation de la validation
- if ($action == 'valid')
- {
- // on verifie si l'objet est en numerotation provisoire
- $objectref = substr($object->ref, 1, 4);
- if ($objectref == 'PROV') {
- $savdate = $object->date;
- if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
- $object->date = dol_now();
- $object->date_lim_reglement = $object->calculate_date_lim_reglement();
- }
- $numref = $object->getNextNumRef($soc);
- // $object->date=$savdate;
- } else {
- $numref = $object->ref;
- }
- $text = $langs->trans('ConfirmValidateBill', $numref);
- if (! empty($conf->notification->enabled)) {
- require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
- $notify = new Notify($db);
- $text .= '<br>';
- $text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
- }
- $formquestion = array();
- $qualified_for_stock_change = 0;
- if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
- $qualified_for_stock_change = $object->hasProductsOrServices(2);
- } else {
- $qualified_for_stock_change = $object->hasProductsOrServices(1);
- }
- if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change)
- {
- $langs->load("stocks");
- require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
- require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
- $formproduct = new FormProduct($db);
- $warehouse = new Entrepot($db);
- $warehouse_array = $warehouse->list_array();
- if (count($warehouse_array) == 1) {
- $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
- $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
- } else {
- $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
- $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1);
- }
- $formquestion = array(
- // 'text' => $langs->trans("ConfirmClone"),
- // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
- // 1),
- // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
- // => 1),
- array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value));
- }
- if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
- {
- $text .= '<br>' . img_warning() . ' ' . $langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
- }
- $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);
- }
- // Confirm back to draft status
- if ($action == 'modif') {
- $text = $langs->trans('ConfirmUnvalidateBill', $object->ref);
- $formquestion = array();
- $qualified_for_stock_change = 0;
- if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
- $qualified_for_stock_change = $object->hasProductsOrServices(2);
- } else {
- $qualified_for_stock_change = $object->hasProductsOrServices(1);
- }
- if ($object->type != Facture::TYPE_DEPOSIT && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $qualified_for_stock_change) {
- $langs->load("stocks");
- require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
- require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
- $formproduct = new FormProduct($db);
- $warehouse = new Entrepot($db);
- $warehouse_array = $warehouse->list_array();
- if (count($warehouse_array) == 1) {
- $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
- $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
- } else {
- $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
- $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1);
- }
- $formquestion = array(
- // 'text' => $langs->trans("ConfirmClone"),
- // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
- // 1),
- // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
- // => 1),
- array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value));
- }
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('UnvalidateBill'), $text, 'confirm_modif', $formquestion, "yes", 1);
- }
- // Confirmation du classement paye
- if ($action == 'paid' && $resteapayer <= 0) {
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', "yes", 1);
- }
- if ($action == 'paid' && $resteapayer > 0) {
- // Code
- $i = 0;
- $close [$i] ['code'] = 'discount_vat';
- $i ++;
- $close [$i] ['code'] = 'badcustomer';
- $i ++;
- // Help
- $i = 0;
- $close [$i] ['label'] = $langs->trans("HelpEscompte") . '<br><br>' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
- $i ++;
- $close [$i] ['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
- $i ++;
- // Texte
- $i = 0;
- $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscountVat", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1);
- $i ++;
- $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1);
- $i ++;
- // arrayreasons[code]=reason
- foreach ($close as $key => $val) {
- $arrayreasons [$close [$key] ['code']] = $close [$key] ['reason'];
- }
- // Cree un tableau formulaire
- $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'));
- // Paiement incomplet. On demande si motif = escompte ou autre
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes");
- }
- // Confirmation du classement abandonne
- if ($action == 'canceled') {
- // S'il y a une facture de remplacement pas encore validee (etat brouillon),
- // on ne permet pas de classer abandonner la facture.
- if ($objectidnext) {
- $facturereplacement = new Facture($db);
- $facturereplacement->fetch($objectidnext);
- $statusreplacement = $facturereplacement->statut;
- }
- if ($objectidnext && $statusreplacement == 0) {
- print '<div class="error">' . $langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated") . '</div>';
- } else {
- // Code
- $close [1] ['code'] = 'badcustomer';
- $close [2] ['code'] = 'abandon';
- // Help
- $close [1] ['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
- $close [2] ['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
- // Texte
- $close [1] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close [1] ['label'], 1);
- $close [2] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close [2] ['label'], 1);
- // arrayreasons
- $arrayreasons [$close [1] ['code']] = $close [1] ['reason'];
- $arrayreasons [$close [2] ['code']] = $close [2] ['reason'];
- // Cree un tableau formulaire
- $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'));
- $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes");
- }
- }
- // Confirmation de la suppression d'une ligne produit
- if ($action == 'ask_deleteline') {
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
- }
- // Clone confirmation
- if ($action == 'clone')
- {
- // Create an array for form
- $formquestion = array(
- // 'text' => $langs->trans("ConfirmClone"),
- // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1)
- 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)));
- // Paiement incomplet. On demande si motif = escompte ou autre
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('CloneInvoice'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
- }
- if (! $formconfirm)
- {
- $parameters = array('lineid' => $lineid);
- $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
- if (empty($reshook)) $formconfirm.=$hookmanager->resPrint;
- elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint;
- }
- // Print form confirm
- print $formconfirm;
- // Invoice content
- print '<table class="border" width="100%">';
- $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php' . (! empty($socid) ? '?socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
- // Ref
- print '<tr><td class="titlefield">' . $langs->trans('Ref') . '</td>';
- print '<td colspan="5">';
- $morehtmlright = '';
- $discount = new DiscountAbsolute($db);
- $result = $discount->fetch(0, $object->id);
- if ($result > 0) {
- $morehtmlright = ' (' . $langs->trans("CreditNoteConvertedIntoDiscount", $discount->getNomUrl(1, 'discount')) . ')';
- }
- if ($result < 0) {
- dol_print_error('', $discount->error);
- }
- print $form->showrefnav($object, 'ref', $linkback, 1, 'facnumber', 'ref', '', '', 0, '', '', $morehtmlright);
- print '</td></tr>';
- // Ref customer
- print '<tr><td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print $langs->trans('RefCustomer');
- print '</td>';
- if ($action != 'refclient' && ! empty($object->brouillon))
- print '<td align="right"><a href="' . $_SERVER['PHP_SELF'] . '?action=refclient&id=' . $object->id . '">' . img_edit($langs->trans('Modify')) . '</a></td>';
- print '</tr></table>';
- print '</td>';
- print '<td colspan="5">';
- if ($user->rights->facture->creer && $action == 'refclient') {
- print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
- print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
- print '<input type="hidden" name="action" value="set_ref_client">';
- print '<input type="text" class="flat" size="20" name="ref_client" value="' . $object->ref_client . '">';
- print ' <input type="submit" class="button" value="' . $langs->trans('Modify') . '">';
- print '</form>';
- } else {
- print $object->ref_client;
- }
- print '</td></tr>';
- // Third party
- print '<tr><td>';
- print '<table class="nobordernopadding" width="100%">';
- print '<tr><td>' . $langs->trans('Company') . '</td>';
- print '</td><td colspan="5">';
- if (! empty($conf->global->FACTURE_CHANGE_THIRDPARTY) && $action != 'editthirdparty' && $object->brouillon && $user->rights->facture->creer)
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editthirdparty&facid=' . $object->id . '">' . img_edit($langs->trans('SetLinkToAnotherThirdParty'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="5">';
- if ($action == 'editthirdparty') {
- $form->form_thirdparty($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, 'socid','client>0');
- } else {
- print ' ' . $soc->getNomUrl(1, 'compta');
- print ' ';
- print '(<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?socid=' . $object->socid . '">' . $langs->trans('OtherBills') . '</a>';
- // Outstanding Bill
- $outstandingBills = $soc->get_OutstandingBill();
- print ' - ' . $langs->trans('CurrentOutstandingBill') . ': ';
- print price($outstandingBills, '', $langs, 0, 0, - 1, $conf->currency);
- if ($soc->outstanding_limit != '')
- {
- if ($outstandingBills > $soc->outstanding_limit)
- print img_warning($langs->trans("OutstandingBillReached"));
- print ' / ' . price($soc->outstanding_limit);
- }
- print ')';
- }
- print '</tr>';
- // Type
- print '<tr><td>' . $langs->trans('Type') . '</td><td colspan="5">';
- print $object->getLibType();
- if ($object->type == Facture::TYPE_REPLACEMENT) {
- $facreplaced = new Facture($db);
- $facreplaced->fetch($object->fk_facture_source);
- print ' (' . $langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)) . ')';
- }
- if ($object->type == Facture::TYPE_CREDIT_NOTE && !empty($object->fk_facture_source)) {
- $facusing = new Facture($db);
- $facusing->fetch($object->fk_facture_source);
- print ' (' . $langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)) . ')';
- }
- $facidavoir = $object->getListIdAvoirFromInvoice();
- if (count($facidavoir) > 0) {
- print ' (' . $langs->transnoentities("InvoiceHasAvoir");
- $i = 0;
- foreach ($facidavoir as $id) {
- if ($i == 0)
- print ' ';
- else
- print ',';
- $facavoir = new Facture($db);
- $facavoir->fetch($id);
- print $facavoir->getNomUrl(1);
- }
- print ')';
- }
- if ($objectidnext > 0) {
- $facthatreplace = new Facture($db);
- $facthatreplace->fetch($objectidnext);
- print ' (' . $langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)) . ')';
- }
- print '</td></tr>';
- // Relative and absolute discounts
- $addrelativediscount = '<a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("EditRelativeDiscounts") . '</a>';
- $addabsolutediscount = '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("EditGlobalDiscounts") . '</a>';
- $addcreditnote = '<a href="' . DOL_URL_ROOT . '/compta/facture.php?action=create&socid=' . $soc->id . '&type=2&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("AddCreditNote") . '</a>';
- print '<tr><td>' . $langs->trans('Discounts');
- print '</td><td colspan="5">';
- if ($soc->remise_percent)
- print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
- else
- print $langs->trans("CompanyHasNoRelativeDiscount");
- // print ' ('.$addrelativediscount.')';
- if ($absolute_discount > 0) {
- print '. ';
- if ($object->statut > 0 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
- if ($object->statut == 0) {
- print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
- print '. ';
- } else {
- if ($object->statut < 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
- $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
- print '<br>' . $text . '.<br>';
- } else {
- $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
- $text2 = $langs->trans("AbsoluteDiscountUse");
- print $form->textwithpicto($text, $text2);
- }
- }
- } else {
- // Remise dispo de type remise fixe (not credit note)
- print '<br>';
- $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')');
- }
- } else {
- if ($absolute_creditnote > 0) // If not, link will be added later
- {
- if ($object->statut == 0 && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT)
- print ' (' . $addabsolutediscount . ')<br>';
- else
- print '. ';
- } else
- print '. ';
- }
- if ($absolute_creditnote > 0)
- {
- // If validated, we show link "add credit note to payment"
- if ($object->statut != 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
- if ($object->statut == 0 && $object->type != Facture::TYPE_DEPOSIT) {
- $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency));
- print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse"));
- } else {
- print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.';
- }
- } else {
- // Remise dispo de type avoir
- if (! $absolute_discount)
- print '<br>';
- // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer
- $more=' ('.$addcreditnote.')';
- $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
- }
- }
- if (! $absolute_discount && ! $absolute_creditnote) {
- print $langs->trans("CompanyHasNoAbsoluteDiscount");
- if ($object->statut == 0 && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT)
- print ' (' . $addabsolutediscount . ')<br>';
- else
- print '. ';
- }
- // if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
- // {
- // if (! $absolute_discount && ! $absolute_creditnote) print '<br>';
- // print ' - ';
- // print $addabsolutediscount;
- // print ' - '.$addcreditnote; // We disbale link to credit note
- // }
- print '</td></tr>';
- // Date invoice
- print '<tr><td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print $langs->trans('DateInvoice');
- print '</td>';
- if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editinvoicedate' && ! empty($object->brouillon) && $user->rights->facture->creer && empty($conf->global->FAC_FORCE_DATE_VALIDATION))
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editinvoicedate&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($object->type != Facture::TYPE_CREDIT_NOTE) {
- if ($action == 'editinvoicedate') {
- $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date, 'invoicedate');
- } else {
- print dol_print_date($object->date, 'day');
- }
- } else {
- print dol_print_date($object->date, 'day');
- }
- print '</td>';
- // List of payments
- $sign = 1;
- if ($object->type == Facture::TYPE_CREDIT_NOTE)
- $sign = - 1;
- $nbrows = 8;
- $nbcols = 3;
- if (! empty($conf->projet->enabled))
- $nbrows ++;
- if (! empty($conf->banque->enabled)) {
- $nbrows ++; $nbcols++;
- }
- if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0)
- $nbrows ++;
- if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0)
- $nbrows ++;
- if ($selleruserevenustamp)
- $nbrows ++;
- if (! empty($conf->multicurrency->enabled)) $nbrows+=5;
- if (! empty($conf->incoterm->enabled)) $nbrows+=1;
- print '<td rowspan="' . $nbrows . '" colspan="2" valign="top">';
- if ($object->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
- {
- if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) print '<table class="nobordernopadding paymenttable" width="100%">';
- if (count($object->tab_previous_situation_invoice) > 0)
- {
- //List of previous invoices
- print '<tr class="liste_titre">';
- print '<td>' . $langs->trans('ListOfPreviousSituationInvoices') . '</td>';
- print '<td></td>';
- if (! empty($conf->banque->enabled))
- print '<td align="right"></td>';
- print '<td align="right">' . $langs->trans('AmountHT') . '</td>';
- print '<td align="right">' . $langs->trans('AmountTTC') . '</td>';
- print '<td width="18"> </td>';
- print '</tr>';
- $total_prev_ht = $total_prev_ttc = 0;
- $var = true;
- foreach ($object->tab_previous_situation_invoice as $prev_invoice)
- {
- $totalpaye = $prev_invoice->getSommePaiement();
- $total_prev_ht += $prev_invoice->total_ht;
- $total_prev_ttc += $prev_invoice->total_ttc;
- print '<tr '.$bc [$var].'>';
- print '<td>'.$prev_invoice->getNomUrl(1).'</td>';
- print '<td></td>';
- if (! empty($conf->banque->enabled))
- print '<td align="right"></td>';
- print '<td align="right">' . price($prev_invoice->total_ht) . '</td>';
- print '<td align="right">' . price($prev_invoice->total_ttc) . '</td>';
- print '<td align="right">'.$prev_invoice->getLibStatut(3, $totalpaye).'</td>';
- print '</tr>';
- $var = !$var;
- }
- print '<tr '.$bc [$var].'>';
- print '<td colspan="2" align="right"></td>';
- print '<td align="right"><b>' . price($total_prev_ht) . '</b></td>';
- print '<td align="right"><b>' . price($total_prev_ttc) . '</b></td>';
- print '<td width="18"> </td>';
- print '</tr>';
- }
- if (count($object->tab_next_situation_invoice) > 0)
- {
- //List of next invoices
- print '<tr class="liste_titre">';
- print '<td>' . $langs->trans('ListOfNextSituationInvoices') . '</td>';
- print '<td></td>';
- if (! empty($conf->banque->enabled))
- print '<td align="right"></td>';
- print '<td align="right">' . $langs->trans('AmountHT') . '</td>';
- print '<td align="right">' . $langs->trans('AmountTTC') . '</td>';
- print '<td width="18"> </td>';
- print '</tr>';
- $total_next_ht = $total_next_ttc = 0;
- $var = true;
- foreach ($object->tab_next_situation_invoice as $next_invoice)
- {
- $totalpaye = $next_invoice->getSommePaiement();
- $total_next_ht += $next_invoice->total_ht;
- $total_next_ttc += $next_invoice->total_ttc;
- print '<tr '.$bc [$var].'>';
- print '<td>'.$next_invoice->getNomUrl(1).'</td>';
- print '<td></td>';
- if (! empty($conf->banque->enabled))
- print '<td align="right"></td>';
- print '<td align="right">' . price($next_invoice->total_ht) . '</td>';
- print '<td align="right">' . price($next_invoice->total_ttc) . '</td>';
- print '<td align="right">'.$next_invoice->getLibStatut(3, $totalpaye).'</td>';
- print '</tr>';
- $var = !$var;
- }
- print '<tr '.$bc [$var].'>';
- print '<td colspan="2" align="right"></td>';
- print '<td align="right"><b>' . price($total_next_ht) . '</b></td>';
- print '<td align="right"><b>' . price($total_next_ttc) . '</b></td>';
- print '<td width="18"> </td>';
- print '</tr>';
- }
- if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) print '</table>';
- }
- print '<table class="nobordernopadding paymenttable" width="100%">';
- // List of payments already done
- print '<tr class="liste_titre">';
- print '<td class="liste_titre">' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '</td>';
- print '<td class="liste_titre">' . $langs->trans('Date') . '</td>';
- print '<td class="liste_titre">' . $langs->trans('Type') . '</td>';
- if (! empty($conf->banque->enabled))
- print '<td class="liste_titre" align="right">' . $langs->trans('BankAccount') . '</td>';
- print '<td class="liste_titre" align="right">' . $langs->trans('Amount') . '</td>';
- print '<td class="liste_titre" width="18"> </td>';
- print '</tr>';
- $var = true;
- // Payments already done (from payment on this invoice)
- $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,';
- $sql .= ' c.code as payment_code, c.libelle as payment_label,';
- $sql .= ' pf.amount,';
- $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label';
- $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p';
- $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid';
- $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid';
- $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid';
- $sql .= ' ORDER BY p.datep, p.tms';
- $result = $db->query($sql);
- if ($result)
- {
- $num = $db->num_rows($result);
- $i = 0;
- // if ($object->type != 2)
- // {
- if ($num > 0)
- {
- while ($i < $num)
- {
- $objp = $db->fetch_object($result);
- $var = ! $var;
- print '<tr ' . $bc [$var] . '><td>';
- $paymentstatic->id=$objp->rowid;
- $paymentstatic->datepaye=$db->jdate($objp->dp);
- $paymentstatic->ref=$objp->ref;
- $paymentstatic->num_paiement=$objp->num_paiement;
- $paymentstatic->payment_code=$objp->payment_code;
- print $paymentstatic->getNomUrl(1);
- print '</td>';
- print '<td>'.dol_print_date($db->jdate($objp->dp), 'day') . '</td>';
- $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label;
- print '<td>' . $label . ' ' . $objp->num_paiement . '</td>';
- if (! empty($conf->banque->enabled))
- {
- $bankaccountstatic->id = $objp->baid;
- $bankaccountstatic->ref = $objp->baref;
- $bankaccountstatic->label = $objp->baref;
- print '<td align="right">';
- if ($bankaccountstatic->id)
- print $bankaccountstatic->getNomUrl(1, 'transactions');
- print '</td>';
- }
- print '<td align="right">' . price($sign * $objp->amount) . '</td>';
- print '<td> </td>';
- print '</tr>';
- $i ++;
- }
- } else {
- print '<tr ' . $bc[false] . '><td colspan="' . $nbcols . '" class="opacitymedium">' . $langs->trans("None") . '</td><td></td><td></td></tr>';
- }
- // }
- $db->free($result);
- } else {
- dol_print_error($db);
- }
- if ($object->type != Facture::TYPE_CREDIT_NOTE)
- {
- // Total already paid
- print '<tr><td colspan="' . $nbcols . '" align="right">';
- if ($object->type != Facture::TYPE_DEPOSIT)
- print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
- else
- print $langs->trans('AlreadyPaid');
- print ' :</td><td align="right">' . price($totalpaye) . '</td><td> </td></tr>';
- $resteapayeraffiche = $resteapayer;
- // Loop on each credit note or deposit amount applied
- $creditnoteamount = 0;
- $depositamount = 0;
- $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
- $sql .= " re.description, re.fk_facture_source";
- $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re";
- $sql .= " WHERE fk_facture = " . $object->id;
- $resql = $db->query($sql);
- if ($resql)
- {
- $num = $db->num_rows($resql);
- $i = 0;
- $invoice = new Facture($db);
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
- $invoice->fetch($obj->fk_facture_source);
- print '<tr><td colspan="' . $nbcols . '" align="right">';
- if ($invoice->type == Facture::TYPE_CREDIT_NOTE)
- print $langs->trans("CreditNote") . ' ';
- if ($invoice->type == Facture::TYPE_DEPOSIT)
- print $langs->trans("Deposit") . ' ';
- print $invoice->getNomUrl(0);
- print ' :</td>';
- print '<td align="right">' . price($obj->amount_ttc) . '</td>';
- print '<td align="right">';
- print '<a href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=unlinkdiscount&discountid=' . $obj->rowid . '">' . img_delete() . '</a>';
- print '</td></tr>';
- $i ++;
- if ($invoice->type == Facture::TYPE_CREDIT_NOTE)
- $creditnoteamount += $obj->amount_ttc;
- if ($invoice->type == Facture::TYPE_DEPOSIT)
- $depositamount += $obj->amount_ttc;
- }
- } else {
- dol_print_error($db);
- }
- // Paye partiellement 'escompte'
- if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'discount_vat') {
- print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
- print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1);
- print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td> </td></tr>';
- $resteapayeraffiche = 0;
- }
- // Paye partiellement ou Abandon 'badcustomer'
- if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'badcustomer') {
- print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
- print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1);
- print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td> </td></tr>';
- // $resteapayeraffiche=0;
- }
- // Paye partiellement ou Abandon 'product_returned'
- if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'product_returned') {
- print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
- print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1);
- print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td> </td></tr>';
- $resteapayeraffiche = 0;
- }
- // Paye partiellement ou Abandon 'abandon'
- if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'abandon') {
- print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
- $text = $langs->trans("HelpAbandonOther");
- if ($object->close_note)
- $text .= '<br><br><b>' . $langs->trans("Reason") . '</b>:' . $object->close_note;
- print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1);
- print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td> </td></tr>';
- $resteapayeraffiche = 0;
- }
- // Billed
- print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("Billed") . ' :</td><td align="right" style="border: 1px solid;">' . price($object->total_ttc) . '</td><td> </td></tr>';
- // Remainder to pay
- print '<tr><td colspan="' . $nbcols . '" align="right">';
- if ($resteapayeraffiche >= 0)
- print $langs->trans('RemainderToPay');
- else
- print $langs->trans('ExcessReceived');
- print ' :</td>';
- print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>' . price($resteapayeraffiche) . '</b></td>';
- print '<td class="nowrap"> </td></tr>';
- }
- else // Credit note
- {
- // Total already paid back
- print '<tr><td colspan="' . $nbcols . '" align="right">';
- print $langs->trans('AlreadyPaidBack');
- print ' :</td><td align="right">' . price($sign * $totalpaye) . '</td><td> </td></tr>';
- // Billed
- print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("Billed") . ' :</td><td align="right" style="border: 1px solid;">' . price($sign * $object->total_ttc) . '</td><td> </td></tr>';
- // Remainder to pay back
- print '<tr><td colspan="' . $nbcols . '" align="right">';
- if ($resteapayeraffiche <= 0)
- print $langs->trans('RemainderToPayBack');
- else
- print $langs->trans('ExcessPaydBack');
- print ' :</td>';
- print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>' . price($sign * $resteapayeraffiche) . '</b></td>';
- print '<td class="nowrap"> </td></tr>';
- // Sold credit note
- // print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('TotalTTC').' :</td>';
- // print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
- // $object->total_ttc).'</b></td><td> </td></tr>';
- }
- print '</table>';
- // Margin Infos
- if (! empty($conf->margin->enabled))
- {
- print '<br>';
- $formmargin->displayMarginInfos($object, $object->statut > 0);
- }
- print '</td></tr>';
- if (! empty($conf->global->INVOICE_POINTOFTAX_DATE))
- {
- // Date invoice
- print '<tr><td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print $langs->trans('DatePointOfTax');
- print '</td>';
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editdate_pointoftax&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($action == 'editdate_pointoftax') {
- $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_pointoftax, 'date_pointoftax');
- } else {
- print dol_print_date($object->date_pointoftax, 'day');
- }
- print '</td></tr>';
- }
- // Conditions de reglement
- print '<tr><td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print $langs->trans('PaymentConditionsShort');
- print '</td>';
- if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer)
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editconditions&facid=' . $object->id . '">' . img_edit($langs->trans('SetConditions'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($object->type != Facture::TYPE_CREDIT_NOTE)
- {
- if ($action == 'editconditions') {
- $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id');
- } else {
- $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none');
- }
- } else {
- print ' ';
- }
- print '</td></tr>';
- // Date payment term
- print '<tr><td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print $langs->trans('DateMaxPayment');
- print '</td>';
- if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && ! empty($object->brouillon) && $user->rights->facture->creer)
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editpaymentterm&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($object->type != Facture::TYPE_CREDIT_NOTE)
- {
- if ($action == 'editpaymentterm') {
- $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_lim_reglement, 'paymentterm');
- } else {
- print dol_print_date($object->date_lim_reglement, 'day');
- if ($object->hasDelay()) {
- print img_warning($langs->trans('Late'));
- }
- }
- } else {
- print ' ';
- }
- print '</td></tr>';
- // Payment mode
- print '<tr><td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print $langs->trans('PaymentMode');
- print '</td>';
- if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer)
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmode&facid=' . $object->id . '">' . img_edit($langs->trans('SetMode'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($action == 'editmode')
- {
- $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT');
- }
- else
- {
- $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none', 'CRDT');
- }
- print '</td></tr>';
- // Multicurrency
- if (! empty($conf->multicurrency->enabled))
- {
- // Multicurrency code
- print '<tr>';
- print '<td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print fieldLabel('Currency','multicurrency_code');
- print '</td>';
- if ($action != 'editmulticurrencycode' && ! empty($object->brouillon))
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencycode&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($action == 'editmulticurrencycode') {
- $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code');
- } else {
- $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none');
- }
- print '</td></tr>';
- // Multicurrency rate
- print '<tr>';
- print '<td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print fieldLabel('CurrencyRate','multicurrency_tx');
- print '</td>';
- if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon))
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencyrate&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($action == 'editmulticurrencyrate') {
- $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
- } else {
- $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
- }
- print '</td></tr>';
- }
- // Bank Account
- print '<tr><td class="nowrap">';
- print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
- print $langs->trans('BankAccount');
- print '<td>';
- if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon))
- print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'),1).'</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($action == 'editbankaccount')
- {
- $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
- }
- else
- {
- $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
- }
- print "</td>";
- print '</tr>';
- // Situations
- if (! empty($conf->global->INVOICE_US_SITUATION))
- {
- if ($object->type == 5 && ($object->situation_counter > 1))
- {
- $prevsits = $object->get_prev_sits();
- print '<tr><td>';
- print $langs->trans('SituationAmount');
- print ' ';
- print $prevsits[0]->situation_counter;
- $cprevsits = count($prevsits);
- for ($i = 1; $i < $cprevsits; $i++) {
- print ' + ';
- print $prevsits[$i]->situation_counter;
- }
- print ' + ';
- print $object->situation_counter;
- print '</td>';
- print '<td align="right" colspan="2" class="nowrap">';
- $prevsits_total_amount = 0;
- foreach ($prevsits as $situation) {
- $prevsits_total_amount += $situation->total_ht;
- }
- $prevsits_total_amount += $object->total_ht;
- print price($prevsits_total_amount);
- print '</td>';
- print '<td>' . $langs->trans('Currency' . $conf->currency) . '</td></tr>';
- // Previous situation(s) deduction(s)
- for ($i = 0; $i < $cprevsits; $i++) {
- print '<tr><td>';
- print '<a href="' . $_SERVER['PHP_SELF'] . '?facid=' . $prevsits[$i]->id . '">';
- print $langs->trans('SituationDeduction');
- print ' ';
- print $prevsits[$i]->situation_counter;
- print '</a></td>';
- print '<td align="right" colspan="2" class="nowrap">';
- print '- ' . price($prevsits[$i]->total_ht);
- print '</td>';
- print '<td>' . $langs->trans('Currency' . $conf->currency) . '</td></tr>';
- }
- }
- }
- // Amount
- print '<tr><td>' . $langs->trans('AmountHT') . '</td>';
- print '<td colspan="3" class="nowrap">' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
- print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td colspan="3" class="nowrap">' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
- print '</tr>';
- // Amount Local Taxes
- if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1
- {
- print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
- print '<td colspan="3" class="nowrap">' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
- }
- if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2
- {
- print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
- print '<td colspan="3" class=nowrap">' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
- }
- // Revenue stamp
- if ($selleruserevenustamp) // Test company use revenue stamp
- {
- print '<tr><td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print $langs->trans('RevenueStamp');
- print '</td>';
- if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer)
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editrevenuestamp&facid=' . $object->id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '</a></td>';
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($action == 'editrevenuestamp') {
- print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
- print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
- print '<input type="hidden" name="action" value="setrevenuestamp">';
- print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code);
- // print '<input type="text" class="flat" size="4" name="revenuestamp" value="'.price2num($object->revenuestamp).'">';
- print ' <input type="submit" class="button" value="' . $langs->trans('Modify') . '">';
- print '</form>';
- } else {
- print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency);
- }
- print '</td></tr>';
- }
- // Total with tax
- print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td colspan="3" class="nowrap">' . price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
- if (!empty($conf->multicurrency->enabled))
- {
- // Multicurrency Amount HT
- print '<tr><td height="10">' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '</td>';
- print '<td class="nowrap" colspan="2">' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
- print '</tr>';
- // Multicurrency Amount VAT
- print '<tr><td height="10">' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '</td>';
- print '<td class="nowrap" colspan="2">' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
- print '</tr>';
- // Multicurrency Amount TTC
- print '<tr><td height="10">' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '</td>';
- print '<td class="nowrap" colspan="2">' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
- print '</tr>';
- }
- // Statut
- print '<tr><td>' . $langs->trans('Status') . '</td>';
- print '<td colspan="3">' . ($object->getLibStatut(4, $totalpaye)) . '</td></tr>';
- // Project
- if (! empty($conf->projet->enabled)) {
- $langs->load('projects');
- print '<tr>';
- print '<td>';
- print '<table class="nobordernopadding" width="100%"><tr><td>';
- print $langs->trans('Project');
- print '</td>';
- if ($action != 'classify') {
- print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=classify&facid=' . $object->id . '">';
- print img_edit($langs->trans('SetProject'), 1);
- print '</a></td>';
- }
- print '</tr></table>';
- print '</td><td colspan="3">';
- if ($action == 'classify') {
- $form->form_project($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1);
- } else {
- $form->form_project($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0);
- }
- print '</td>';
- print '</tr>';
- }
- // Incoterms
- if (!empty($conf->incoterm->enabled))
- {
- print '<tr><td>';
- print '<table width="100%" class="nobordernopadding"><tr><td>';
- print $langs->trans('IncotermLabel');
- print '<td><td align="right">';
- if ($user->rights->facture->creer) print '<a href="'.DOL_URL_ROOT.'/compta/facture.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>';
- else print ' ';
- print '</td></tr></table>';
- print '</td>';
- print '<td colspan="3">';
- if ($action != 'editincoterm')
- {
- print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1);
- }
- else
- {
- print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id);
- }
- print '</td></tr>';
- }
- // Other attributes
- $cols = 5;
- include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
- print '</table><br>';
- if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
- $blocname = 'contacts';
- $title = $langs->trans('ContactsAddresses');
- include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
- }
- if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
- $blocname = 'notes';
- $title = $langs->trans('Notes');
- include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
- }
- // Lines
- $result = $object->getLinesArray();
- print ' <form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (($action != 'editline') ? '#add' : '#line_' . GETPOST('lineid')) . '" method="POST">
- <input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">
- <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateligne') . '">
- <input type="hidden" name="mode" value="">
- <input type="hidden" name="id" value="' . $object->id . '">
- ';
- if (! empty($conf->use_javascript_ajax) && $object->statut == 0) {
- include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
- }
- print '<table id="tablelines" class="noborder noshadow" width="100%">';
- // Show global modifiers
- if (! empty($conf->global->INVOICE_US_SITUATION))
- {
- if ($object->situation_cycle_ref && $object->statut == 0) {
- print '<tr class="liste_titre nodrag nodrop">';
- print '<form name="updatealllines" id="updatealllines" action="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '"#updatealllines" method="POST">';
- print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '" />';
- print '<input type="hidden" name="action" value="updatealllines" />';
- print '<input type="hidden" name="id" value="' . $object->id . '" />';
- if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
- print '<td align="center" width="5"> </td>';
- }
- print '<td>' . $langs->trans('ModifyAllLines') . '</td>';
- print '<td align="right" width="50"> </td>';
- print '<td align="right" width="80"> </td>';
- if ($inputalsopricewithtax) print '<td align="right" width="80"> </td>';
- print '<td align="right" width="50"> </td>';
- print '<td align="right" width="50"> </td>';
- print '<td align="right" width="50">' . $langs->trans('Progress') . '</td>';
- if (! empty($conf->margin->enabled) && empty($user->societe_id))
- {
- print '<td align="right" class="margininfos" width="80"> </td>';
- if ((! empty($conf->global->DISPLAY_MARGIN_RATES) || ! empty($conf->global->DISPLAY_MARK_RATES)) && $user->rights->margins->liretous) {
- print '<td align="right" class="margininfos" width="50"> </td>';
- }
- }
- print '<td align="right" width="50"> </td>';
- print '<td> </td>';
- print '<td width="10"> </td>';
- print '<td width="10"> </td>';
- print "</tr>\n";
- if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
- print '<td align="center" width="5"> </td>';
- }
- print '<tr width="100%" class="nodrag nodrop">';
- print '<td> </td>';
- print '<td width="50"> </td>';
- print '<td width="80"> </td>';
- print '<td width="50"> </td>';
- print '<td width="50"> </td>';
- print '<td align="right" class="nowrap"><input type="text" size="1" value="" name="all_progress">%</td>';
- print '<td colspan="4" align="right"><input class="button" type="submit" name="all_percent" value="Modifier" /></td>';
- print '</tr>';
- print '</form>';
- }
- }
- // Show object lines
- if (! empty($object->lines))
- $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
- // Form to add new line
- if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline' && ($object->is_first() || !$object->situation_cycle_ref))
- {
- if ($action != 'editline')
- {
- $var = true;
- // Add free products/services
- $object->formAddObjectLine(1, $mysoc, $soc);
- $parameters = array();
- $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
- }
- }
- print "</table>\n";
- print "</form>\n";
- dol_fiche_end();
- // Actions buttons
- if ($action != 'prerelance' && $action != 'presend' && $action != 'valid' && $action != 'editline')
- {
- print '<div class="tabsAction">';
- $parameters = array();
- $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
- // modified by hook
- if (empty($reshook)) {
- // Editer une facture deja validee, sans paiement effectue et pas exporte en compta
- if ($object->statut == 1)
- {
- // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
- $ventilExportCompta = $object->getVentilExportCompta();
- if ($resteapayer == $object->total_ttc && empty($object->paye) && $ventilExportCompta == 0)
- {
- if (! $objectidnext && $object->is_last_in_cycle())
- {
- if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
- || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate)))
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=modif">' . $langs->trans('Modify') . '</a></div>';
- } else {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("NotEnoughPermissions") . '">' . $langs->trans('Modify') . '</span></div>';
- }
- } else if (!$object->is_last_in_cycle()) {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("NotLastInCycle") . '">' . $langs->trans('Modify') . '</span></div>';
- } else {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('Modify') . '</span></div>';
- }
- }
- }
- // Reopen a standard paid invoice
- if ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)
- || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id))
- || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id)))
- && ($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
- && $user->rights->facture->creer) // A paid invoice (partially or completely)
- {
- if (! $objectidnext && $object->close_code != 'replaced') // Not replaced by another invoice
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=reopen">' . $langs->trans('ReOpen') . '</a></div>';
- } else {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('ReOpen') . '</span></div>';
- }
- }
- // Validate
- 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))) {
- if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer))
- || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate)))
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=valid">' . $langs->trans('Validate') . '</a></div>';
- }
- }
- // Send by mail
- if (($object->statut == 1 || $object->statut == 2) || ! empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) {
- if ($objectidnext) {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('SendByMail') . '</span></div>';
- } else {
- if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send) {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=presend&mode=init">' . $langs->trans('SendByMail') . '</a></div>';
- } else
- print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">' . $langs->trans('SendByMail') . '</a></div>';
- }
- }
- // deprecated. Useless because now we can use templates
- if (! empty($conf->global->FACTURE_SHOW_SEND_REMINDER)) // For backward compatibility
- {
- if (($object->statut == 1 || $object->statut == 2) && $resteapayer > 0) {
- if ($objectidnext) {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('SendRemindByMail') . '</span></div>';
- } else {
- if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send) {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=prerelance&mode=init">' . $langs->trans('SendRemindByMail') . '</a></div>';
- } else
- print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">' . $langs->trans('SendRemindByMail') . '</a></div>';
- }
- }
- }
- // Create payment
- if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement) {
- if ($objectidnext) {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('DoPayment') . '</span></div>';
- } else {
- if ($resteapayer == 0) {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseRemainderToPayIsZero") . '">' . $langs->trans('DoPayment') . '</span></div>';
- } else {
- print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid=' . $object->id . '&action=create&accountid='.$object->fk_account.'">' . $langs->trans('DoPayment') . '</a></div>';
- }
- }
- }
- // Reverse back money or convert to reduction
- if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
- // For credit note only
- if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->paiement)
- {
- if ($resteapayer == 0)
- {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span></div>';
- }
- else
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&action=create&accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a></div>';
- }
- }
- // For credit note
- if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0) {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=converttoreduc">' . $langs->trans('ConvertToReduc') . '</a></div>';
- }
- // For deposit invoice
- if ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $user->rights->facture->creer && empty($discount->id))
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>';
- }
- }
- // Classify paid
- 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))
- || ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 0 && $object->total_ttc > 0 && $resteapayer == 0 && $user->rights->facture->paiement && empty($discount->id))
- )
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=paid">'.$langs->trans('ClassifyPaid').'</a></div>';
- }
- // Classify 'closed not completely paid' (possible si validee et pas encore classee payee)
- if ($object->statut == 1 && $object->paye == 0 && $resteapayer > 0 && $user->rights->facture->paiement)
- {
- if ($totalpaye > 0 || $totalcreditnotes > 0)
- {
- // If one payment or one credit note was linked to this invoice
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=paid">' . $langs->trans('ClassifyPaidPartially') . '</a></div>';
- }
- else
- {
- if ( empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED))
- {
- if ($objectidnext)
- {
- print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('ClassifyCanceled') . '</span></div>';
- }
- else
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=canceled">' . $langs->trans('ClassifyCanceled') . '</a></div>';
- }
- }
- }
- }
- // Clone
- if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $user->rights->facture->creer)
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=clone&object=invoice">' . $langs->trans("ToClone") . '</a></div>';
- }
- // Clone as predefined / Create template
- if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut == 0 && $user->rights->facture->creer)
- {
- if (! $objectidnext && count($object->lines) > 0)
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="facture/fiche-rec.php?facid=' . $object->id . '&action=create">' . $langs->trans("ChangeIntoRepeatableInvoice") . '</a></div>';
- }
- }
- // Create a credit note
- if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $user->rights->facture->creer)
- {
- if (! $objectidnext)
- {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?socid=' . $object->socid .'&fac_avoir=' . $object->id . '&action=create&type=2'.($object->fk_project > 0 ? '&projectid='.$object->fk_project : '').'">' . $langs->trans("CreateCreditNote") . '</a></div>';
- }
- }
- // Create next situation invoice
- if ($user->rights->facture->creer && ($object->type == 5) && ($object->statut == 1 || $object->statut == 2)) {
- if ($object->is_last_in_cycle() && $object->situation_final != 1) {
- print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=create&type=5&origin=facture&originid=' . $object->id . '&socid=' . $object->socid . '" >' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
- } else if (!$object->is_last_in_cycle()) {
- print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotLastInCycle") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
- } else {
- print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseFinal") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a></div>';
- }
- }
- // Delete
- if ($user->rights->facture->supprimer)
- {
- if (! $object->is_erasable()) {
- print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotErasable") . '">' . $langs->trans('Delete') . '</a></div>';
- } else if ($objectidnext) {
- print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('Delete') . '</a></div>';
- } elseif ($object->getSommePaiement()) {
- print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecausePayments") . '">' . $langs->trans('Delete') . '</a></div>';
- } else {
- print '<div class="inline-block divButAction"><a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=delete">' . $langs->trans('Delete') . '</a></div>';
- }
- } else {
- print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("NotAllowed") . '">' . $langs->trans('Delete') . '</a></div>';
- }
- print '</div>';
- }
- }
- print '<br>';
- // Select mail models is same action as presend
- if (GETPOST('modelselected')) {
- $action = 'presend';
- }
- if ($action != 'prerelance' && $action != 'presend')
- {
- print '<div class="fichecenter"><div class="fichehalfleft">';
- print '<a name="builddoc"></a>'; // ancre
- // Documents generes
- $filename = dol_sanitizeFileName($object->ref);
- $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
- $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id;
- $genallowed = $user->rights->facture->creer;
- $delallowed = $user->rights->facture->supprimer;
- print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
- $somethingshown = $formfile->numoffiles;
- // Show links to link elements
- $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
- $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
-
- // Link for paypal payment
- if (! empty($conf->paypal->enabled) && $object->statut != 0) {
- include_once DOL_DOCUMENT_ROOT . '/paypal/lib/paypal.lib.php';
- print showPaypalPaymentUrl('invoice', $object->ref);
- }
- print '</div><div class="fichehalfright"><div class="ficheaddleft">';
- // List of actions on element
- include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
- $formactions = new FormActions($db);
- $somethingshown = $formactions->showactions($object, 'invoice', $socid);
- print '</div></div></div>';
- }
- else
- {
- /*
- * Action presend (or prerelance)
- */
- $object->fetch_projet();
- // By default if $action=='presend'
- $titreform = 'SendBillByMail';
- $topicmail = 'SendBillRef';
- $modelmail = 'facture_send';
- if ($action == 'prerelance') // For backward compatibility
- {
- $titrefrom = 'SendReminderBillByMail';
- $topicmail = 'SendReminderBillRef';
- $modelmail = 'facture_relance';
- $action = 'relance';
- } else
- $action = 'send';
- $ref = dol_sanitizeFileName($object->ref);
- include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
- $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+');
- $file = $fileparams['fullname'];
- // Define output language
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id']))
- $newlang = $_REQUEST['lang_id'];
- if ($conf->global->MAIN_MULTILANGS && empty($newlang))
- $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang))
- {
- $outputlangs = new Translate('', $conf);
- $outputlangs->setDefaultLang($newlang);
- $outputlangs->load('bills');
- }
- // Build document if it not exists
- if (! $file || ! is_readable($file)) {
- $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
- if ($result <= 0) {
- dol_print_error($db, $object->error, $object->errors);
- exit();
- }
- $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/').'[^\-]+');
- $file = $fileparams['fullname'];
- }
- print '<div class="clearboth"></div>';
- print '<br>';
- print load_fiche_titre($langs->trans($titreform));
- // Cree l'objet formulaire mail
- dol_fiche_head();
- include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
- $formmail = new FormMail($db);
- $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang);
- $formmail->fromtype = 'user';
- $formmail->fromid = $user->id;
- $formmail->fromname = $user->getFullName($langs);
- $formmail->frommail = $user->email;
- $formmail->trackid='inv'.$object->id;
- if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set
- {
- include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
- $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'inv'.$object->id);
- }
- $formmail->withfrom = 1;
- $liste = array();
- foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) {
- $liste [$key] = $value;
- }
- $formmail->withto = GETPOST('sendto') ? GETPOST('sendto') : $liste; // List suggested for send to
- $formmail->withtocc = $liste; // List suggested for CC
- $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC;
- if (empty($object->ref_client)) {
- $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__REF__');
- } else if (! empty($object->ref_client)) {
- $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__REF__ (__REFCLIENT__)');
- }
- $formmail->withfile = 2;
- $formmail->withbody = 1;
- $formmail->withdeliveryreceipt = 1;
- $formmail->withcancel = 1;
- // Tableau des substitutions
- $formmail->setSubstitFromObject($object, $outputlangs);
- $formmail->substit['__INVREF__'] = $object->ref;
- // Find the good contact adress
- $custcontact = '';
- $contactarr = array();
- $contactarr = $object->liste_contact(- 1, 'external');
- if (is_array($contactarr) && count($contactarr) > 0) {
- foreach ($contactarr as $contact) {
- if ($contact['libelle'] == $langs->trans('TypeContact_facture_external_BILLING')) { // TODO Use code and not label
- require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
- $contactstatic = new Contact($db);
- $contactstatic->fetch($contact ['id']);
- $custcontact = $contactstatic->getFullName($langs, 1);
- }
- }
- if (! empty($custcontact)) {
- $formmail->substit['__CONTACTCIVNAME__'] = $custcontact;
- }
- }
- // Tableau des parametres complementaires du post
- $formmail->param['action'] = $action;
- $formmail->param['models'] = $modelmail;
- $formmail->param['models_id']=GETPOST('modelmailselected','int');
- $formmail->param['facid'] = $object->id;
- $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id;
- // Init list of files
- if (GETPOST("mode") == 'init') {
- $formmail->clear_attached_files();
- $formmail->add_attached_files($file, basename($file), dol_mimetype($file));
- }
- print $formmail->get_form();
- dol_fiche_end();
- }
- }
- llxFooter();
- $db->close();
|