card.php 319 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123
  1. <?php
  2. /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  4. * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  6. * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  8. * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
  9. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  10. * Copyright (C) 2012-2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  11. * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  12. * Copyright (C) 2013 Jean-Francois FERRY <jfefe@aternatik.fr>
  13. * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
  14. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  15. * Copyright (C) 2014-2019 Ferran Marcet <fmarcet@2byte.es>
  16. * Copyright (C) 2015-2016 Marcos García <marcosgdf@gmail.com>
  17. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  18. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/compta/facture/card.php
  35. * \ingroup facture
  36. * \brief Page to create/see an invoice
  37. */
  38. // Libraries
  39. require '../../main.inc.php';
  40. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  41. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php';
  42. require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
  43. require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  44. require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
  45. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  46. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
  47. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
  48. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
  49. require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
  50. require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
  51. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  52. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  53. require_once DOL_DOCUMENT_ROOT . '/custom/financialreport/class/userinvoice.class.php';
  54. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/commissionhandler.class.php';
  55. require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketcounter.class.php';
  56. if (isModEnabled('commande')) {
  57. require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
  58. }
  59. if (isModEnabled('project')) {
  60. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  61. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  62. }
  63. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  64. if (isModEnabled('variants')) {
  65. require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination.class.php';
  66. }
  67. if (isModEnabled('accounting')) {
  68. require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
  69. }
  70. // Load translation files required by the page
  71. $langs->loadLangs(array('bills', 'companies', 'compta', 'products', 'banks', 'main', 'withdrawals'));
  72. if (isModEnabled('incoterm')) {
  73. $langs->load('incoterm');
  74. }
  75. if (isModEnabled('margin')) {
  76. $langs->load('margins');
  77. }
  78. // General $Variables
  79. $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
  80. $ref = GETPOST('ref', 'alpha');
  81. $socid = GETPOST('socid', 'int');
  82. $action = GETPOST('action', 'aZ09');
  83. $confirm = GETPOST('confirm', 'alpha');
  84. $cancel = GETPOST('cancel', 'alpha');
  85. $lineid = GETPOST('lineid', 'int');
  86. $userid = GETPOST('userid', 'int');
  87. $search_ref = GETPOST('sf_ref', 'alpha') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
  88. $search_societe = GETPOST('search_societe', 'alpha');
  89. $search_montant_ht = GETPOST('search_montant_ht', 'alpha');
  90. $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
  91. $origin = GETPOST('origin', 'alpha');
  92. $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
  93. $fac_rec = GETPOST('fac_rec', 'int');
  94. $facid = GETPOST('facid', 'int');
  95. $ref_client = GETPOST('ref_client', 'int');
  96. $rank = (GETPOST('rank', 'int') > 0) ? GETPOST('rank', 'int') : -1;
  97. $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0);
  98. // Customer Change button
  99. $customerchange = GETPOST('customerchange', 'int');
  100. // PDF
  101. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  102. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  103. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  104. // Number of lines for predefined product/service choices
  105. $NBLINES = 4;
  106. $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
  107. $object = new Facture($db);
  108. $extrafields = new ExtraFields($db);
  109. // Fetch optionals attributes and labels
  110. $extrafields->fetch_name_optionals_label($object->table_element);
  111. // Load object
  112. if ($id > 0 || !empty($ref)) {
  113. if ($action != 'add') {
  114. if (empty($conf->global->INVOICE_USE_SITUATION)) {
  115. $fetch_situation = false;
  116. } else {
  117. $fetch_situation = true;
  118. }
  119. $ret = $object->fetch($id, $ref, '', '', $fetch_situation);
  120. }
  121. }
  122. if ($object->statut == 2) {
  123. $Bbticketcounter = new Bbticketcounter();
  124. }
  125. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  126. $hookmanager->initHooks(array('invoicecard', 'globalcard'));
  127. // Permissions
  128. $usercanread = $user->hasRight("facture", "lire");
  129. $usercancreate = $user->hasRight("facture", "creer");
  130. $usercanissuepayment = $user->hasRight("facture", "paiement");
  131. $usercandelete = $user->hasRight("facture", "supprimer");
  132. $usercancreatecontract = $user->hasRight("contrat", "creer");
  133. // Advanced Permissions
  134. $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->validate)));
  135. $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->send)));
  136. $usercanreopen = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->reopen)));
  137. if (!empty($conf->global->INVOICE_DISALLOW_REOPEN)) {
  138. $usercanreopen = false;
  139. }
  140. $usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->unvalidate)));
  141. $usermustrespectpricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS));
  142. $usercancreatemargin = (!empty($user->rights->margins->creer) ? $user->rights->margins->creer : 0);
  143. $usercanreadallmargin = (!empty($user->rights->margins->liretous) ? $user->rights->margins->liretous : 0);
  144. $usercancreatewithdrarequest = (!empty($user->rights->prelevement->bons->creer) ? $user->rights->prelevement->bons->creer : 0);
  145. $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
  146. $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
  147. $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdonw.inc.php
  148. $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php
  149. // retained warranty invoice available type
  150. $retainedWarrantyInvoiceAvailableType = array();
  151. if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  152. $retainedWarrantyInvoiceAvailableType = explode('+', $conf->global->INVOICE_USE_RETAINED_WARRANTY);
  153. }
  154. // Security check
  155. if ($user->socid) {
  156. $socid = $user->socid;
  157. }
  158. $isdraft = (($object->statut == Facture::STATUS_DRAFT) ? 1 : 0);
  159. $result = restrictedArea($user, 'facture', $object->id, '', '', 'fk_soc', 'rowid', $isdraft);
  160. /*
  161. * Actions
  162. */
  163. $parameters = array('socid' => $socid);
  164. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  165. if ($reshook < 0) {
  166. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  167. }
  168. if (empty($reshook)) {
  169. // send invoice to ntak
  170. if ($conf->ntak->enabled) {
  171. require_once DOL_DOCUMENT_ROOT . '/custom/ntak/class/ntaksender.class.php';
  172. require_once DOL_DOCUMENT_ROOT . '/custom/ntak/class/ntaksendresult.class.php';
  173. require_once DOL_DOCUMENT_ROOT . '/custom/ntak/class/ntakconnector/ntak_const.class.php';
  174. if ($action == 'sendntak') {
  175. $ntakSendResult = (new NtakSender)->sendByInvoice($object);
  176. if (empty($ntakSendResult->error) && !empty($ntakSendResult->ntakId)) {
  177. $object->array_options['options_ntak_id'] = $ntakSendResult->ntakId;
  178. $object->array_options['options_ntak_status'] = $ntakSendResult->ntakStatus;
  179. $object->updateExtraField('ntak_id');
  180. $object->updateExtraField('ntak_status');
  181. setEventMessages($langs->trans('NtakSuccessSend', $ntakSendResult->ntakId), null, 'mesgs');
  182. } else {
  183. setEventMessages($langs->trans('NtakSendFailure'), null, 'errors');
  184. }
  185. header('Location: ' . DOL_URL_ROOT . '/compta/facture/card.php?id=' . $id);
  186. exit;
  187. }
  188. if ($action == 'getntakstatus') {
  189. $ntakResult = (new NtakSender)->checkSentInvoice($object->array_options['options_ntak_id'], $object->id);
  190. if (!empty($ntakResult['uzenetValaszok'][0]['statusz'])) {
  191. $object->array_options['options_ntak_status'] = $ntakResult['uzenetValaszok'][0]['statusz'];
  192. $object->updateExtraField('ntak_status');
  193. setEventMessages($langs->trans('NtakStatusChecked', $ntakResult['uzenetValaszok'][0]['statusz']), null, 'mesgs');
  194. } else {
  195. setEventMessages($langs->trans('NtakStatusCheckFailure'), null, 'errors');
  196. }
  197. header('Location: ' . DOL_URL_ROOT . '/compta/facture/card.php?id=' . $id);
  198. exit;
  199. }
  200. }
  201. $backurlforlist = DOL_URL_ROOT . '/compta/facture/list.php';
  202. if (empty($backtopage) || ($cancel && empty($id))) {
  203. if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
  204. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  205. $backtopage = $backurlforlist;
  206. } else {
  207. $backtopage = DOL_URL_ROOT . '/compta/facture/card.php?id=' . ((!empty($id) && $id > 0) ? $id : '__ID__');
  208. }
  209. }
  210. }
  211. if ($cancel) {
  212. if (!empty($backtopageforcancel)) {
  213. header("Location: " . $backtopageforcancel);
  214. exit;
  215. } elseif (!empty($backtopage)) {
  216. header("Location: " . $backtopage);
  217. exit;
  218. }
  219. $action = '';
  220. }
  221. include DOL_DOCUMENT_ROOT . '/core/actions_setnotes.inc.php'; // Must be include, not include_once
  222. include DOL_DOCUMENT_ROOT . '/core/actions_dellink.inc.php'; // Must be include, not include_once
  223. include DOL_DOCUMENT_ROOT . '/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  224. // Action clone object
  225. if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
  226. $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
  227. $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
  228. $objectutil->socid = $socid;
  229. $result = $objectutil->createFromClone($user, $id);
  230. if ($result > 0) {
  231. header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $result);
  232. exit();
  233. } else {
  234. $langs->load("errors");
  235. setEventMessages($objectutil->error, $objectutil->errors, 'errors');
  236. $action = '';
  237. }
  238. } elseif ($action == 'reopen' && $usercanreopen) {
  239. $result = $object->fetch($id);
  240. if ($object->statut == Facture::STATUS_CLOSED || ($object->statut == Facture::STATUS_ABANDONED && ($object->close_code != 'replaced' || $object->getIdReplacingInvoice() == 0)) || ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 1)) { // ($object->statut == 1 && $object->paye == 1) should not happened but can be found when data are corrupted
  241. $result = $object->setUnpaid($user);
  242. if ($result > 0) {
  243. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  244. exit();
  245. } else {
  246. setEventMessages($object->error, $object->errors, 'errors');
  247. }
  248. }
  249. } elseif ($action == 'confirm_delete' && $confirm == 'yes') {
  250. // Delete invoice
  251. $result = $object->fetch($id);
  252. $object->fetch_thirdparty();
  253. $idwarehouse = GETPOST('idwarehouse');
  254. $qualified_for_stock_change = 0;
  255. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  256. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  257. } else {
  258. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  259. }
  260. $isErasable = $object->is_erasable();
  261. if (
  262. ($usercandelete && $isErasable > 0)
  263. || ($usercancreate && $isErasable == 1)
  264. ) {
  265. $result = $object->delete($user, 0, $idwarehouse);
  266. if ($result > 0) {
  267. header('Location: ' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1');
  268. exit();
  269. } else {
  270. setEventMessages($object->error, $object->errors, 'errors');
  271. $action = '';
  272. }
  273. }
  274. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
  275. // Delete line
  276. $object->fetch($id);
  277. $object->fetch_thirdparty();
  278. $result = $object->deleteline(GETPOST('lineid', 'int'));
  279. if ($result > 0) {
  280. // reorder lines
  281. $object->line_order(true);
  282. // Define output language
  283. $outputlangs = $langs;
  284. $newlang = '';
  285. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id')) {
  286. $newlang = GETPOST('lang_id');
  287. }
  288. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  289. $newlang = $object->thirdparty->default_lang;
  290. }
  291. if (!empty($newlang)) {
  292. $outputlangs = new Translate("", $conf);
  293. $outputlangs->setDefaultLang($newlang);
  294. $outputlangs->load('products');
  295. }
  296. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  297. $ret = $object->fetch($id); // Reload to get new records
  298. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  299. }
  300. if ($result >= 0) {
  301. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  302. exit();
  303. }
  304. } else {
  305. setEventMessages($object->error, $object->errors, 'errors');
  306. $action = '';
  307. }
  308. } elseif ($action == 'unlinkdiscount' && $usercancreate) {
  309. // Delete link of credit note to invoice
  310. $discount = new DiscountAbsolute($db);
  311. $result = $discount->fetch(GETPOST("discountid"));
  312. $discount->unlink_invoice();
  313. } elseif ($action == 'valid' && $usercancreate) {
  314. // Validation
  315. $object->fetch($id);
  316. if (!empty($conf->global->INVOICE_CHECK_POSTERIOR_DATE)) {
  317. $last_of_type = $object->willBeLastOfSameType(true);
  318. if (empty($object->date_validation) && !$last_of_type[0]) {
  319. setEventMessages($langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $object->ref, dol_print_date($object->date, 'day'), dol_print_date($last_of_type[1], 'day')), null, 'errors');
  320. $action = '';
  321. }
  322. }
  323. // On verifie signe facture
  324. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  325. // Si avoir, le signe doit etre negatif
  326. if ($object->total_ht >= 0) {
  327. setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
  328. $action = '';
  329. }
  330. } elseif ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  331. // Si avoir, le signe doit etre negatif
  332. if ($object->total_ht >= 0) {
  333. setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
  334. $action = '';
  335. }
  336. } else {
  337. // If not a credit note, amount with tax must be positive or nul.
  338. // Note that amount excluding tax can be negative because you can have a invoice of 100 with vat of 20 that
  339. // consumes a credit note of 100 with vat 0 (total with tax is 0 but without tax is -20).
  340. // For some cases, credit notes can have a vat of 0 (for example when selling goods in France).
  341. if (empty($conf->global->FACTURE_ENABLE_NEGATIVE) && $object->total_ttc < 0) {
  342. setEventMessages($langs->trans("ErrorInvoiceOfThisTypeMustBePositive"), null, 'errors');
  343. $action = '';
  344. }
  345. // Also negative lines should not be allowed on 'non Credit notes' invoices. A test is done when adding or updating lines but we must
  346. // do it again in validation to avoid cases where invoice is created from another object that allow negative lines.
  347. // Note that we can accept the negative line if sum with other lines with same vat makes total positive: Because all the lines will be merged together
  348. // when converted into 'available credit' and we will get a positive available credit line.
  349. // Note: Other solution if you want to add a negative line on invoice, is to create a discount for customer and consumme it (but this is possible on standard invoice only).
  350. $array_of_total_ht_per_vat_rate = array();
  351. $array_of_total_ht_devise_per_vat_rate = array();
  352. foreach ($object->lines as $line) {
  353. //$vat_src_code_for_line = $line->vat_src_code; // TODO We chek sign of total per vat without taking into account the vat code because for the moment the vat code is lost/unknown when we add a down payment.
  354. $vat_src_code_for_line = '';
  355. if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line])) {
  356. $array_of_total_ht_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line] = 0;
  357. }
  358. if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line])) {
  359. $array_of_total_ht_devise_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line] = 0;
  360. }
  361. $array_of_total_ht_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line] += $line->total_ht;
  362. $array_of_total_ht_devise_per_vat_rate[$line->tva_tx . '_' . $vat_src_code_for_line] += $line->multicurrency_total_ht;
  363. }
  364. //var_dump($array_of_total_ht_per_vat_rate);exit;
  365. foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) {
  366. $tmp_total_ht = price2num($array_of_total_ht_per_vat_rate[$vatrate]);
  367. $tmp_total_ht_devise = price2num($array_of_total_ht_devise_per_vat_rate[$vatrate]);
  368. if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  369. if ($object->type == $object::TYPE_DEPOSIT) {
  370. $langs->load("errors");
  371. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  372. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  373. $error++;
  374. $action = '';
  375. } else {
  376. $tmpvatratetoshow = explode('_', $vatrate);
  377. $tmpvatratetoshow[0] = round($tmpvatratetoshow[0], 2);
  378. if ($tmpvatratetoshow[0] != 0) {
  379. $langs->load("errors");
  380. setEventMessages($langs->trans("ErrorLinesCantBeNegativeForOneVATRate", $tmpvatratetoshow[0]), null, 'errors');
  381. $error++;
  382. $action = '';
  383. }
  384. }
  385. }
  386. }
  387. }
  388. } elseif ($action == 'classin' && $usercancreate) {
  389. $object->fetch($id);
  390. $object->setProject(GETPOST('projectid', 'int'));
  391. } elseif ($action == 'setmode' && $usercancreate) {
  392. $object->fetch($id);
  393. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  394. if ($result < 0) {
  395. dol_print_error($db, $object->error);
  396. }
  397. } elseif ($action == 'setretainedwarrantyconditions' && $user->rights->facture->creer) {
  398. $object->fetch($id);
  399. $object->retained_warranty_fk_cond_reglement = 0; // To clean property
  400. $result = $object->setRetainedWarrantyPaymentTerms(GETPOST('retained_warranty_fk_cond_reglement', 'int'));
  401. if ($result < 0) {
  402. dol_print_error($db, $object->error);
  403. }
  404. $old_rw_date_lim_reglement = $object->retained_warranty_date_limit;
  405. $new_rw_date_lim_reglement = $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  406. if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) {
  407. $object->retained_warranty_date_limit = $new_rw_date_lim_reglement;
  408. }
  409. if ($object->retained_warranty_date_limit < $object->date) {
  410. $object->retained_warranty_date_limit = $object->date;
  411. }
  412. $result = $object->update($user);
  413. if ($result < 0) {
  414. dol_print_error($db, $object->error);
  415. }
  416. } elseif ($action == 'setretainedwarranty' && $user->rights->facture->creer) {
  417. $object->fetch($id);
  418. $result = $object->setRetainedWarranty(GETPOST('retained_warranty', 'float'));
  419. if ($result < 0) {
  420. dol_print_error($db, $object->error);
  421. }
  422. } elseif ($action == 'setretainedwarrantydatelimit' && $user->rights->facture->creer) {
  423. $object->fetch($id);
  424. $result = $object->setRetainedWarrantyDateLimit(GETPOST('retained_warranty_date_limit', 'float'));
  425. if ($result < 0) {
  426. dol_print_error($db, $object->error);
  427. }
  428. } elseif ($action == 'setmulticurrencycode' && $usercancreate) { // Multicurrency Code
  429. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  430. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { // Multicurrency rate
  431. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
  432. } elseif ($action == 'setinvoicedate' && $usercancreate) {
  433. $object->fetch($id);
  434. $old_date_lim_reglement = $object->date_lim_reglement;
  435. $newdate = dol_mktime(0, 0, 0, GETPOST('invoicedatemonth', 'int'), GETPOST('invoicedateday', 'int'), GETPOST('invoicedateyear', 'int'), 'tzserver');
  436. if (empty($newdate)) {
  437. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  438. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id . '&action=editinvoicedate&token=' . newToken());
  439. exit;
  440. }
  441. if ($newdate > (dol_now('tzuserrel') + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  442. if (empty($conf->global->INVOICE_MAX_FUTURE_DELAY)) {
  443. setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
  444. } else {
  445. setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
  446. }
  447. }
  448. $object->date = $newdate;
  449. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  450. if ($new_date_lim_reglement > $old_date_lim_reglement) {
  451. $object->date_lim_reglement = $new_date_lim_reglement;
  452. }
  453. if ($object->date_lim_reglement < $object->date) {
  454. $object->date_lim_reglement = $object->date;
  455. }
  456. $result = $object->update($user);
  457. if ($result < 0) {
  458. dol_print_error($db, $object->error);
  459. }
  460. } elseif ($action == 'setdate_pointoftax' && $usercancreate) {
  461. $object->fetch($id);
  462. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  463. $object->date_pointoftax = $date_pointoftax;
  464. $result = $object->update($user);
  465. if ($result < 0) {
  466. dol_print_error($db, $object->error);
  467. }
  468. } elseif ($action == 'setconditions' && $usercancreate) {
  469. $object->fetch($id);
  470. $object->cond_reglement_code = 0; // To clean property
  471. $object->cond_reglement_id = 0; // To clean property
  472. $error = 0;
  473. $db->begin();
  474. if (!$error) {
  475. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  476. if ($result < 0) {
  477. $error++;
  478. setEventMessages($object->error, $object->errors, 'errors');
  479. }
  480. }
  481. if (!$error) {
  482. $old_date_lim_reglement = $object->date_lim_reglement;
  483. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  484. if ($new_date_lim_reglement > $old_date_lim_reglement) {
  485. $object->date_lim_reglement = $new_date_lim_reglement;
  486. }
  487. if ($object->date_lim_reglement < $object->date) {
  488. $object->date_lim_reglement = $object->date;
  489. }
  490. $result = $object->update($user);
  491. if ($result < 0) {
  492. $error++;
  493. setEventMessages($object->error, $object->errors, 'errors');
  494. }
  495. }
  496. if ($error) {
  497. $db->rollback();
  498. } else {
  499. $db->commit();
  500. }
  501. } elseif ($action == 'setpaymentterm' && $usercancreate) {
  502. $object->fetch($id);
  503. $object->date_lim_reglement = dol_mktime(12, 0, 0, GETPOST('paymenttermmonth', 'int'), GETPOST('paymenttermday', 'int'), GETPOST('paymenttermyear', 'int'));
  504. if ($object->date_lim_reglement < $object->date) {
  505. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  506. setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
  507. }
  508. $result = $object->update($user);
  509. if ($result < 0) {
  510. dol_print_error($db, $object->error);
  511. }
  512. } elseif ($action == 'setrevenuestamp' && $usercancreate) {
  513. $object->fetch($id);
  514. $object->revenuestamp = GETPOST('revenuestamp');
  515. $result = $object->update($user);
  516. $object->update_price(1);
  517. if ($result < 0) {
  518. dol_print_error($db, $object->error);
  519. } else {
  520. // Define output language
  521. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  522. $outputlangs = $langs;
  523. $newlang = '';
  524. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  525. $newlang = GETPOST('lang_id', 'aZ09');
  526. }
  527. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  528. $newlang = $object->thirdparty->default_lang;
  529. }
  530. if (!empty($newlang)) {
  531. $outputlangs = new Translate("", $conf);
  532. $outputlangs->setDefaultLang($newlang);
  533. $outputlangs->load('products');
  534. }
  535. $model = $object->model_pdf;
  536. $ret = $object->fetch($id); // Reload to get new records
  537. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  538. if ($result < 0) {
  539. setEventMessages($object->error, $object->errors, 'errors');
  540. }
  541. }
  542. }
  543. } elseif ($action == 'set_incoterms' && isModEnabled('incoterm')) { // Set incoterm
  544. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  545. } elseif ($action == 'setbankaccount' && $usercancreate) { // bank account
  546. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  547. } elseif ($action == 'setremisepercent' && $usercancreate) {
  548. $object->fetch($id);
  549. $result = $object->setDiscount($user, price2num(GETPOST('remise_percent'), '', 2));
  550. } elseif ($action == "setabsolutediscount" && $usercancreate) {
  551. // We have POST[remise_id] or POST[remise_id_for_payment]
  552. $db->begin();
  553. // We use the credit to reduce amount of invoice
  554. if (GETPOST("remise_id", 'int') > 0) {
  555. $ret = $object->fetch($id);
  556. if ($ret > 0) {
  557. $result = $object->insert_discount(GETPOST("remise_id", 'int'));
  558. if ($result < 0) {
  559. setEventMessages($object->error, $object->errors, 'errors');
  560. }
  561. } else {
  562. $error++;
  563. setEventMessages($object->error, $object->errors, 'errors');
  564. }
  565. }
  566. // We use the credit to reduce remain to pay
  567. if (GETPOST("remise_id_for_payment", 'int') > 0) {
  568. require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
  569. $discount = new DiscountAbsolute($db);
  570. $discount->fetch(GETPOST("remise_id_for_payment", 'int'));
  571. //var_dump($object->getRemainToPay(0));
  572. //var_dump($discount->amount_ttc);exit;
  573. $remaintopay = $object->getRemainToPay(0);
  574. if (price2num($discount->amount_ttc) > price2num($remaintopay)) {
  575. // TODO Split the discount in 2 automatically
  576. $error++;
  577. setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
  578. }
  579. if (!$error) {
  580. $result = $discount->link_to_invoice(0, $id);
  581. if ($result < 0) {
  582. $error++;
  583. setEventMessages($discount->error, $discount->errors, 'errors');
  584. }
  585. }
  586. if (!$error) {
  587. $newremaintopay = $object->getRemainToPay(0);
  588. if ($newremaintopay == 0) {
  589. $object->setPaid($user);
  590. }
  591. }
  592. }
  593. if (!$error) {
  594. $db->commit();
  595. } else {
  596. $db->rollback();
  597. }
  598. if (empty($error) && empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  599. $outputlangs = $langs;
  600. $newlang = '';
  601. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  602. $newlang = GETPOST('lang_id', 'aZ09');
  603. }
  604. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  605. $newlang = $object->thirdparty->default_lang;
  606. }
  607. if (!empty($newlang)) {
  608. $outputlangs = new Translate("", $conf);
  609. $outputlangs->setDefaultLang($newlang);
  610. }
  611. $ret = $object->fetch($id); // Reload to get new records
  612. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  613. if ($result < 0) {
  614. setEventMessages($object->error, $object->errors, 'errors');
  615. }
  616. }
  617. } elseif ($action == 'setref' && $usercancreate) {
  618. $object->fetch($id);
  619. $object->setValueFrom('ref', GETPOST('ref'), '', null, '', '', $user, 'BILL_MODIFY');
  620. } elseif ($action == 'setref_client' && $usercancreate) {
  621. $object->fetch($id);
  622. $object->set_ref_client(GETPOST('ref_client'));
  623. } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
  624. // Classify to validated
  625. $idwarehouse = GETPOST('idwarehouse', 'int');
  626. $object->fetch($id);
  627. $object->fetch_thirdparty();
  628. // Check for warehouse
  629. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  630. $qualified_for_stock_change = 0;
  631. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  632. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  633. } else {
  634. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  635. }
  636. if ($qualified_for_stock_change) {
  637. if (!$idwarehouse || $idwarehouse == -1) {
  638. $error++;
  639. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  640. $action = '';
  641. }
  642. }
  643. }
  644. if (!$error) {
  645. $result = $object->validate($user, '', $idwarehouse);
  646. if ($result >= 0) {
  647. // Define output language
  648. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  649. $outputlangs = $langs;
  650. $newlang = '';
  651. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  652. $newlang = GETPOST('lang_id', 'aZ09');
  653. }
  654. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  655. $newlang = $object->thirdparty->default_lang;
  656. }
  657. if (!empty($newlang)) {
  658. $outputlangs = new Translate("", $conf);
  659. $outputlangs->setDefaultLang($newlang);
  660. $outputlangs->load('products');
  661. }
  662. $model = $object->model_pdf;
  663. $ret = $object->fetch($id); // Reload to get new records
  664. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  665. if ($result < 0) {
  666. setEventMessages($object->error, $object->errors, 'errors');
  667. }
  668. }
  669. } else {
  670. if (count($object->errors)) {
  671. setEventMessages(null, $object->errors, 'errors');
  672. } else {
  673. setEventMessages($object->error, $object->errors, 'errors');
  674. }
  675. }
  676. }
  677. } elseif ($action == 'confirm_modif' && $usercanunvalidate) {
  678. // Go back to draft status (unvalidate)
  679. $idwarehouse = GETPOST('idwarehouse', 'int');
  680. $object->fetch($id);
  681. $object->fetch_thirdparty();
  682. // Check parameters
  683. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  684. $qualified_for_stock_change = 0;
  685. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  686. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  687. } else {
  688. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  689. }
  690. if ($qualified_for_stock_change) {
  691. if (!$idwarehouse || $idwarehouse == -1) {
  692. $error++;
  693. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  694. $action = '';
  695. }
  696. }
  697. }
  698. if (!$error) {
  699. // We check if invoice has payments
  700. $sql = 'SELECT pf.amount';
  701. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf';
  702. $sql .= ' WHERE pf.fk_facture = ' . ((int) $object->id);
  703. $result = $db->query($sql);
  704. if ($result) {
  705. $i = 0;
  706. $num = $db->num_rows($result);
  707. while ($i < $num) {
  708. $objp = $db->fetch_object($result);
  709. $totalpaid += $objp->amount;
  710. $i++;
  711. }
  712. } else {
  713. dol_print_error($db, '');
  714. }
  715. $resteapayer = $object->total_ttc - $totalpaid;
  716. // We check that invlice lines are transferred into accountancy
  717. $ventilExportCompta = $object->getVentilExportCompta();
  718. // On verifie si aucun paiement n'a ete effectue
  719. if ($ventilExportCompta == 0) {
  720. if (!empty($conf->global->INVOICE_CAN_BE_EDITED_EVEN_IF_PAYMENT_DONE) || ($resteapayer == $object->total_ttc && empty($object->paye))) {
  721. $result = $object->setDraft($user, $idwarehouse);
  722. if ($result < 0) {
  723. setEventMessages($object->error, $object->errors, 'errors');
  724. }
  725. // Define output language
  726. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  727. $outputlangs = $langs;
  728. $newlang = '';
  729. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  730. $newlang = GETPOST('lang_id', 'aZ09');
  731. }
  732. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  733. $newlang = $object->thirdparty->default_lang;
  734. }
  735. if (!empty($newlang)) {
  736. $outputlangs = new Translate("", $conf);
  737. $outputlangs->setDefaultLang($newlang);
  738. $outputlangs->load('products');
  739. }
  740. $model = $object->model_pdf;
  741. $ret = $object->fetch($id); // Reload to get new records
  742. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  743. }
  744. }
  745. }
  746. }
  747. } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercanissuepayment) {
  748. // Classify "paid"
  749. $object->fetch($id);
  750. $result = $object->setPaid($user);
  751. if ($result < 0) {
  752. setEventMessages($object->error, $object->errors, 'errors');
  753. }
  754. } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) {
  755. // Classif "paid partialy"
  756. $object->fetch($id);
  757. $close_code = GETPOST("close_code", 'restricthtml');
  758. $close_note = GETPOST("close_note", 'restricthtml');
  759. if ($close_code) {
  760. $result = $object->setPaid($user, $close_code, $close_note);
  761. if ($result < 0) {
  762. setEventMessages($object->error, $object->errors, 'errors');
  763. }
  764. } else {
  765. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  766. }
  767. } elseif ($action == 'confirm_canceled' && $confirm == 'yes') {
  768. // Classify "abandoned"
  769. $object->fetch($id);
  770. $close_code = GETPOST("close_code", 'restricthtml');
  771. $close_note = GETPOST("close_note", 'restricthtml');
  772. if ($close_code) {
  773. $result = $object->setCanceled($user, $close_code, $close_note);
  774. if ($result < 0) {
  775. setEventMessages($object->error, $object->errors, 'errors');
  776. }
  777. } else {
  778. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  779. }
  780. } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
  781. // Convertir en reduc
  782. $object->fetch($id);
  783. $object->fetch_thirdparty();
  784. //$object->fetch_lines(); // Already done into fetch
  785. // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
  786. $discountcheck = new DiscountAbsolute($db);
  787. $result = $discountcheck->fetch(0, $object->id);
  788. $canconvert = 0;
  789. if ($object->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
  790. $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
  791. }
  792. if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_RECEIPT || $object->type == Facture::TYPE_SITUATION) && $object->paye == 0 && empty($discountcheck->id)) {
  793. $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)
  794. }
  795. if ($canconvert) {
  796. $db->begin();
  797. $amount_ht = $amount_tva = $amount_ttc = array();
  798. $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
  799. // Loop on each vat rate
  800. $i = 0;
  801. foreach ($object->lines as $line) {
  802. if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null
  803. $keyforvatrate = $line->tva_tx . ($line->vat_src_code ? ' (' . $line->vat_src_code . ')' : '');
  804. $amount_ht[$keyforvatrate] += $line->total_ht;
  805. $amount_tva[$keyforvatrate] += $line->total_tva;
  806. $amount_ttc[$keyforvatrate] += $line->total_ttc;
  807. $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
  808. $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
  809. $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
  810. $i++;
  811. }
  812. }
  813. // If some payments were already done, we change the amount to pay using same prorate
  814. if (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) && $object->type == Facture::TYPE_CREDIT_NOTE && $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  815. $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
  816. if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
  817. $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
  818. foreach ($amount_ht as $vatrate => $val) {
  819. $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
  820. $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
  821. $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
  822. $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
  823. $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
  824. $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
  825. }
  826. }
  827. }
  828. //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
  829. // Insert one discount by VAT rate category
  830. $discount = new DiscountAbsolute($db);
  831. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  832. $discount->description = '(CREDIT_NOTE)';
  833. } elseif ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  834. $discount->description = '(CREDIT_NOTE_RECEIPT)';
  835. } elseif ($object->type == Facture::TYPE_DEPOSIT) {
  836. $discount->description = '(DEPOSIT)';
  837. } elseif ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION || $object->type == Facture::TYPE_RECEIPT) {
  838. $discount->description = '(EXCESS RECEIVED)';
  839. } else {
  840. setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
  841. }
  842. $discount->fk_soc = $object->socid;
  843. $discount->fk_facture_source = $object->id;
  844. $error = 0;
  845. if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION || $object->type == Facture::TYPE_RECEIPT) {
  846. // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
  847. // Total payments
  848. $sql = 'SELECT SUM(pf.amount) as total_paiements';
  849. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p';
  850. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_paiement as c ON p.fk_paiement = c.id';
  851. $sql .= ' WHERE pf.fk_facture = ' . ((int) $object->id);
  852. $sql .= ' AND pf.fk_paiement = p.rowid';
  853. $sql .= ' AND p.entity IN (' . getEntity('invoice') . ')';
  854. $resql = $db->query($sql);
  855. if (!$resql) {
  856. dol_print_error($db);
  857. }
  858. $res = $db->fetch_object($resql);
  859. $total_paiements = $res->total_paiements;
  860. // Total credit note and deposit
  861. $total_creditnote_and_deposit = 0;
  862. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  863. $sql .= " re.description, re.fk_facture_source";
  864. $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re";
  865. $sql .= " WHERE fk_facture = " . ((int) $object->id);
  866. $resql = $db->query($sql);
  867. if (!empty($resql)) {
  868. while ($obj = $db->fetch_object($resql)) {
  869. $total_creditnote_and_deposit += $obj->amount_ttc;
  870. }
  871. } else {
  872. dol_print_error($db);
  873. }
  874. $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
  875. $discount->amount_tva = 0;
  876. $discount->tva_tx = 0;
  877. $discount->vat_src_code = '';
  878. $result = $discount->create($user);
  879. if ($result < 0) {
  880. $error++;
  881. }
  882. }
  883. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  884. foreach ($amount_ht as $tva_tx => $xxx) {
  885. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  886. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  887. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  888. $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
  889. $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
  890. $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
  891. // Clean vat code
  892. $reg = array();
  893. $vat_src_code = '';
  894. if (preg_match('/\((.*)\)/', $tva_tx, $reg)) {
  895. $vat_src_code = $reg[1];
  896. $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx); // Remove code into vatrate.
  897. }
  898. $discount->tva_tx = abs($tva_tx);
  899. $discount->vat_src_code = $vat_src_code;
  900. $result = $discount->create($user);
  901. if ($result < 0) {
  902. $error++;
  903. break;
  904. }
  905. }
  906. }
  907. if (empty($error)) {
  908. if ($object->type != Facture::TYPE_DEPOSIT) {
  909. // Classe facture
  910. $result = $object->setPaid($user);
  911. if ($result >= 0) {
  912. $db->commit();
  913. } else {
  914. setEventMessages($object->error, $object->errors, 'errors');
  915. $db->rollback();
  916. }
  917. } else {
  918. $db->commit();
  919. }
  920. } else {
  921. setEventMessages($discount->error, $discount->errors, 'errors');
  922. $db->rollback();
  923. }
  924. }
  925. } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercanissuepayment) {
  926. // Delete payment
  927. $object->fetch($id);
  928. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0) {
  929. $paiement = new Paiement($db);
  930. $result = $paiement->fetch(GETPOST('paiement_id', 'int'));
  931. if ($result > 0) {
  932. $result = $paiement->delete(); // If fetch ok and found
  933. if ($result >= 0) {
  934. header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
  935. exit;
  936. }
  937. }
  938. if ($result < 0) {
  939. setEventMessages($paiement->error, $paiement->errors, 'errors');
  940. }
  941. }
  942. } elseif ($action == 'add' && $usercancreate) {
  943. // Insert new invoice in database
  944. if ($socid > 0) {
  945. $object->socid = GETPOST('socid', 'int');
  946. }
  947. $selectedLines = GETPOST('toselect', 'array');
  948. if (GETPOST('type', 'int') === '') {
  949. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  950. }
  951. $db->begin();
  952. $error = 0;
  953. $originentity = GETPOST('originentity');
  954. // Fill array 'array_options' with data from add form
  955. $ret = $extrafields->setOptionalsFromPost(null, $object);
  956. if ($ret < 0) {
  957. $error++;
  958. }
  959. $dateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver'); // If we enter the 02 january, we need to save the 02 january for server
  960. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  961. // Replacement invoice
  962. if (GETPOST('type') == Facture::TYPE_REPLACEMENT) {
  963. if (empty($dateinvoice)) {
  964. $error++;
  965. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  966. $action = 'create';
  967. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  968. $error++;
  969. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  970. $action = 'create';
  971. }
  972. if (!(GETPOST('fac_replacement', 'int') > 0)) {
  973. $error++;
  974. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
  975. $action = 'create';
  976. }
  977. if (!$error) {
  978. // This is a replacement invoice
  979. $result = $object->fetch(GETPOST('fac_replacement', 'int'));
  980. $object->fetch_thirdparty();
  981. $object->date = $dateinvoice;
  982. $object->date_pointoftax = $date_pointoftax;
  983. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  984. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  985. $object->ref_client = GETPOST('ref_client', 'alphanohtml');
  986. $object->model_pdf = GETPOST('model', 'alphanohtml');
  987. $object->fk_project = GETPOST('projectid', 'int');
  988. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  989. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  990. $object->fk_account = GETPOST('fk_account', 'int');
  991. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU', 2);
  992. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  993. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  994. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  995. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  996. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  997. // Proprietes particulieres a facture de remplacement
  998. $object->fk_facture_source = GETPOST('fac_replacement', 'int');
  999. $object->type = Facture::TYPE_REPLACEMENT;
  1000. $id = $object->createFromCurrent($user);
  1001. if ($id <= 0) {
  1002. setEventMessages($object->error, $object->errors, 'errors');
  1003. }
  1004. }
  1005. }
  1006. // Credit note invoice
  1007. if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) {
  1008. if ($object->array_options['options_commission_deduction']) {
  1009. $factureObj = new Facture($db);
  1010. $userinvoiceObj = new UserInvoice($db);
  1011. $commmissionhandler = new CommissionHandler();
  1012. $productObj = new Product($db);
  1013. $productObjHUF = new Product($db);
  1014. $fk_facture_resource = GETPOST('fac_avoir', 'int');
  1015. $result_source_facture = $factureObj->fetch($fk_facture_resource);
  1016. if ($factureObj->fk_multicurrency == 2) {
  1017. $fk_product = $factureObj->lines[0]->fk_product;
  1018. $assignedProduct = $productObj->fetch($fk_product);
  1019. $relatedService = $productObj->array_options['options_related_service'];
  1020. $productToCount = $productObjHUF->fetch($relatedService);
  1021. $price_ttc = $productObjHUF->price_ttc;
  1022. $commissionValue = $productObjHUF->array_options['options_commission_value'];
  1023. $type = $productObjHUF->array_options['options_commission_type'] == 1 ? '%' : 'Forint';
  1024. $row['total_ttc'] = $price_ttc;
  1025. $row['commission'] = $commissionValue . '_' . $type;
  1026. ;
  1027. $amount = $commmissionhandler->getAmountOfCommission($row);
  1028. } else {
  1029. $row['total_ttc'] = $factureObj->total_ttc;
  1030. $row['commission'] = $factureObj->array_options['options_commission'];
  1031. $amount = $commmissionhandler->getAmountOfCommission($row);
  1032. }
  1033. $resultUserinvoiceObj = $userinvoiceObj->fetchAll('', '', 0, 0, ["customsql" => "invoices LIKE '%{$factureObj->id}%'"]);
  1034. $usersArray = [];
  1035. foreach ($resultUserinvoiceObj as $userObj) {
  1036. $usersArray[] = $userObj->user_id;
  1037. }
  1038. $numberOfUsers = count($usersArray);
  1039. if ($numberOfUsers > 0) {
  1040. $amountOfOneUser = $amount / $numberOfUsers;
  1041. foreach ($usersArray as $userid) {
  1042. if ($amountOfOneUser > 0) {
  1043. $userinvoiceObj2 = new UserInvoice($db);
  1044. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  1045. ;
  1046. $userinvoiceObj2->label = 'Visszatartás / Withholding ' . date('Y-m-d');
  1047. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amountOfOneUser . ' HUF. Commission deduction. (CREDIT NOTE)';
  1048. $userinvoiceObj2->user_id = $userid;
  1049. $userinvoiceObj2->payment_type = 1;
  1050. $userinvoiceObj2->amount = $amountOfOneUser;
  1051. $userinvoiceObj2->currency = 0;
  1052. $userinvoiceObj2->individual = 1;
  1053. $userinvoiceObj2->invoices = $factureObj->id;
  1054. $result = $userinvoiceObj2->create($user);
  1055. if ($result < 0) {
  1056. $error++;
  1057. }
  1058. }
  1059. }
  1060. } else {
  1061. if ($amount > 0) {
  1062. $userinvoiceObj2 = new UserInvoice($db);
  1063. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  1064. ;
  1065. $userinvoiceObj2->label = 'Visszatartás / Withholding ' . date('Y-m-d');
  1066. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amount . ' HUF. Commission deduction. (CREDIT NOTE)';
  1067. $userinvoiceObj2->user_id = $factureObj->fk_user_valid;
  1068. $userinvoiceObj2->payment_type = 1;
  1069. $userinvoiceObj2->amount = $amount;
  1070. $userinvoiceObj2->currency = 0;
  1071. $userinvoiceObj2->individual = 1;
  1072. $userinvoiceObj2->invoices = $factureObj->id;
  1073. $result = $userinvoiceObj2->create($user);
  1074. if ($result < 0) {
  1075. $error++;
  1076. }
  1077. }
  1078. }
  1079. }
  1080. $sourceinvoice = GETPOST('fac_avoir', 'int');
  1081. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  1082. $error++;
  1083. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  1084. $action = 'create';
  1085. }
  1086. if (empty($dateinvoice)) {
  1087. $error++;
  1088. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1089. $action = 'create';
  1090. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1091. $error++;
  1092. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1093. $action = 'create';
  1094. }
  1095. if (!$error) {
  1096. if (!empty($originentity)) {
  1097. $object->entity = $originentity;
  1098. }
  1099. $object->socid = GETPOST('socid', 'int');
  1100. $object->ref = GETPOST('ref');
  1101. $object->date = $dateinvoice;
  1102. $object->date_pointoftax = $date_pointoftax;
  1103. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1104. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1105. $object->ref_client = GETPOST('ref_client');
  1106. $object->model_pdf = GETPOST('model');
  1107. $object->fk_project = GETPOST('projectid', 'int');
  1108. $object->cond_reglement_id = 0; // No payment term for a credit note
  1109. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1110. $object->fk_account = GETPOST('fk_account', 'int');
  1111. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1112. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1113. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1114. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1115. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1116. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1117. // Proprietes particulieres a facture avoir
  1118. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  1119. $object->type = Facture::TYPE_CREDIT_NOTE;
  1120. $facture_source = new Facture($db); // fetch origin object
  1121. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1122. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1123. $object->situation_counter = $facture_source->situation_counter;
  1124. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  1125. $facture_source->fetchPreviousNextSituationInvoice();
  1126. }
  1127. }
  1128. $id = $object->create($user);
  1129. if ($id < 0) {
  1130. $error++;
  1131. } else {
  1132. // copy internal contacts
  1133. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  1134. $error++;
  1135. } elseif ($facture_source->socid == $object->socid) {
  1136. // copy external contacts if same company
  1137. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  1138. $error++;
  1139. }
  1140. }
  1141. }
  1142. // NOTE: Pb with situation invoice
  1143. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  1144. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  1145. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  1146. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  1147. if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
  1148. if (!empty($facture_source->lines)) {
  1149. $fk_parent_line = 0;
  1150. foreach ($facture_source->lines as $line) {
  1151. // Extrafields
  1152. if (method_exists($line, 'fetch_optionals')) {
  1153. // load extrafields
  1154. $line->fetch_optionals();
  1155. }
  1156. // Reset fk_parent_line for no child products and special product
  1157. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  1158. $fk_parent_line = 0;
  1159. }
  1160. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1161. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  1162. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  1163. if (!empty($facture_source->tab_previous_situation_invoice)) {
  1164. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  1165. // TODO Move this out of loop of $facture_source->lines
  1166. $tab_jumped_credit_notes = array();
  1167. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  1168. $searchPreviousInvoice = true;
  1169. while ($searchPreviousInvoice) {
  1170. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  1171. $searchPreviousInvoice = false; // find, exit;
  1172. break;
  1173. } else {
  1174. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
  1175. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  1176. }
  1177. $lineIndex--; // go to previous invoice in cycle
  1178. }
  1179. }
  1180. $maxPrevSituationPercent = 0;
  1181. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  1182. if ($prevLine->id == $source_fk_prev_id) {
  1183. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  1184. //$line->subprice = $line->subprice - $prevLine->subprice;
  1185. $line->total_ht = $line->total_ht - $prevLine->total_ht;
  1186. $line->total_tva = $line->total_tva - $prevLine->total_tva;
  1187. $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
  1188. $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
  1189. $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
  1190. $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
  1191. $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
  1192. $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
  1193. $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
  1194. }
  1195. }
  1196. // prorata
  1197. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  1198. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1199. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  1200. $maxPrevSituationPercent = 0;
  1201. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  1202. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  1203. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  1204. $maxPrevSituationPercent = $prevLine->situation_percent;
  1205. $line->total_ht -= $prevLine->total_ht;
  1206. $line->total_tva -= $prevLine->total_tva;
  1207. $line->total_ttc -= $prevLine->total_ttc;
  1208. $line->total_localtax1 -= $prevLine->total_localtax1;
  1209. $line->total_localtax2 -= $prevLine->total_localtax2;
  1210. $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
  1211. $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
  1212. $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
  1213. $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
  1214. }
  1215. }
  1216. }
  1217. // prorata
  1218. $line->situation_percent += $maxPrevSituationPercent;
  1219. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1220. }
  1221. }
  1222. $line->fk_facture = $object->id;
  1223. $line->fk_parent_line = $fk_parent_line;
  1224. $line->subprice = -$line->subprice; // invert price for object
  1225. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  1226. $line->total_ht = -$line->total_ht;
  1227. $line->total_tva = -$line->total_tva;
  1228. $line->total_ttc = -$line->total_ttc;
  1229. $line->total_localtax1 = -$line->total_localtax1;
  1230. $line->total_localtax2 = -$line->total_localtax2;
  1231. $line->multicurrency_subprice = -$line->multicurrency_subprice;
  1232. $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
  1233. $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
  1234. $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
  1235. $line->context['createcreditnotefrominvoice'] = 1;
  1236. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  1237. $object->lines[] = $line; // insert new line in current object
  1238. // Defined the new fk_parent_line
  1239. if ($result > 0 && $line->product_type == 9) {
  1240. $fk_parent_line = $result;
  1241. }
  1242. }
  1243. $object->update_price(1);
  1244. }
  1245. }
  1246. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  1247. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1248. $totalpaid = $facture_source->getSommePaiement();
  1249. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  1250. $totaldeposits = $facture_source->getSumDepositsUsed();
  1251. $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
  1252. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
  1253. }
  1254. }
  1255. // Add link between credit note and origin
  1256. if (!empty($object->fk_facture_source) && $id > 0) {
  1257. $facture_source->fetch($object->fk_facture_source);
  1258. $facture_source->fetchObjectLinked();
  1259. if (!empty($facture_source->linkedObjectsIds)) {
  1260. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  1261. $object->add_object_linked($sourcetype, current($TIds));
  1262. }
  1263. }
  1264. }
  1265. }
  1266. }
  1267. // Receipt Credit note invoice
  1268. if (GETPOST('type') == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  1269. if ($object->array_options['options_commission_deduction']) {
  1270. $factureObj = new Facture($db);
  1271. $userinvoiceObj = new UserInvoice($db);
  1272. $commmissionhandler = new CommissionHandler();
  1273. $productObj = new Product($db);
  1274. $productObjHUF = new Product($db);
  1275. $fk_facture_resource = GETPOST('fac_avoir', 'int');
  1276. $result_source_facture = $factureObj->fetch($fk_facture_resource);
  1277. if ($factureObj->fk_multicurrency == 2) {
  1278. $fk_product = $factureObj->lines[0]->fk_product;
  1279. $assignedProduct = $productObj->fetch($fk_product);
  1280. $relatedService = $productObj->array_options['options_related_service'];
  1281. $productToCount = $productObjHUF->fetch($relatedService);
  1282. $price_ttc = $productObjHUF->price_ttc;
  1283. $commissionValue = $productObjHUF->array_options['options_commission_value'];
  1284. $type = $productObjHUF->array_options['options_commission_type'] == 1 ? '%' : 'Forint';
  1285. $row['total_ttc'] = $price_ttc;
  1286. $row['commission'] = $commissionValue . '_' . $type;
  1287. ;
  1288. $amount = $commmissionhandler->getAmountOfCommission($row);
  1289. } else {
  1290. $row['total_ttc'] = $factureObj->total_ttc;
  1291. $row['commission'] = $factureObj->array_options['options_commission'];
  1292. $amount = $commmissionhandler->getAmountOfCommission($row);
  1293. }
  1294. $resultUserinvoiceObj = $userinvoiceObj->fetchAll('', '', 0, 0, ["customsql" => "invoices LIKE '%{$factureObj->id}%'"]);
  1295. $usersArray = [];
  1296. foreach ($resultUserinvoiceObj as $userObj) {
  1297. $usersArray[] = $userObj->user_id;
  1298. }
  1299. $numberOfUsers = count($usersArray);
  1300. if ($numberOfUsers > 0) {
  1301. $amountOfOneUser = $amount / $numberOfUsers;
  1302. foreach ($usersArray as $userid) {
  1303. if ($amountOfOneUser > 0) {
  1304. $userinvoiceObj2 = new UserInvoice($db);
  1305. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  1306. ;
  1307. $userinvoiceObj2->label = 'Visszatartás / Withholding ' . date('Y-m-d');
  1308. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amountOfOneUser . ' HUF. Commission deduction. (CREDIT NOTE)';
  1309. $userinvoiceObj2->user_id = $userid;
  1310. $userinvoiceObj2->payment_type = 1;
  1311. $userinvoiceObj2->amount = $amountOfOneUser;
  1312. $userinvoiceObj2->currency = 0;
  1313. $userinvoiceObj2->individual = 1;
  1314. $userinvoiceObj2->invoices = $factureObj->id;
  1315. $result = $userinvoiceObj2->create($user);
  1316. if ($result < 0) {
  1317. $error++;
  1318. }
  1319. }
  1320. }
  1321. } else {
  1322. if ($amount > 0) {
  1323. $userinvoiceObj2 = new UserInvoice($db);
  1324. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  1325. ;
  1326. $userinvoiceObj2->label = 'Visszatartás / Withholding ' . date('Y-m-d');
  1327. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amount . ' HUF. Commission deduction. (CREDIT NOTE)';
  1328. $userinvoiceObj2->user_id = $factureObj->fk_user_valid;
  1329. $userinvoiceObj2->payment_type = 1;
  1330. $userinvoiceObj2->amount = $amount;
  1331. $userinvoiceObj2->currency = 0;
  1332. $userinvoiceObj2->individual = 1;
  1333. $userinvoiceObj2->invoices = $factureObj->id;
  1334. $result = $userinvoiceObj2->create($user);
  1335. if ($result < 0) {
  1336. $error++;
  1337. }
  1338. }
  1339. }
  1340. }
  1341. $sourceinvoice = GETPOST('fac_avoir', 'int');
  1342. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  1343. $error++;
  1344. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  1345. $action = 'create';
  1346. }
  1347. if (empty($dateinvoice)) {
  1348. $error++;
  1349. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1350. $action = 'create';
  1351. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1352. $error++;
  1353. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1354. $action = 'create';
  1355. }
  1356. if (!$error) {
  1357. if (!empty($originentity)) {
  1358. $object->entity = $originentity;
  1359. }
  1360. $object->socid = GETPOST('socid', 'int');
  1361. $object->ref = GETPOST('ref');
  1362. $object->date = $dateinvoice;
  1363. $object->date_pointoftax = $date_pointoftax;
  1364. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1365. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1366. $object->ref_client = GETPOST('ref_client');
  1367. $object->model_pdf = GETPOST('model');
  1368. $object->fk_project = GETPOST('projectid', 'int');
  1369. $object->cond_reglement_id = 0; // No payment term for a credit note
  1370. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1371. $object->fk_account = GETPOST('fk_account', 'int');
  1372. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1373. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1374. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1375. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1376. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1377. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1378. // Proprietes particulieres a facture avoir
  1379. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  1380. $object->type = Facture::TYPE_RECEIPT_CREDIT_NOTE;
  1381. $facture_source = new Facture($db); // fetch origin object
  1382. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1383. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1384. $object->situation_counter = $facture_source->situation_counter;
  1385. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  1386. $facture_source->fetchPreviousNextSituationInvoice();
  1387. }
  1388. }
  1389. $id = $object->create($user);
  1390. if ($id < 0) {
  1391. $error++;
  1392. } else {
  1393. // copy internal contacts
  1394. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  1395. $error++;
  1396. } elseif ($facture_source->socid == $object->socid) {
  1397. // copy external contacts if same company
  1398. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  1399. $error++;
  1400. }
  1401. }
  1402. }
  1403. // NOTE: Pb with situation invoice
  1404. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  1405. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  1406. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  1407. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  1408. if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
  1409. if (!empty($facture_source->lines)) {
  1410. $fk_parent_line = 0;
  1411. foreach ($facture_source->lines as $line) {
  1412. // Extrafields
  1413. if (method_exists($line, 'fetch_optionals')) {
  1414. // load extrafields
  1415. $line->fetch_optionals();
  1416. }
  1417. // Reset fk_parent_line for no child products and special product
  1418. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  1419. $fk_parent_line = 0;
  1420. }
  1421. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1422. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  1423. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  1424. if (!empty($facture_source->tab_previous_situation_invoice)) {
  1425. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  1426. // TODO Move this out of loop of $facture_source->lines
  1427. $tab_jumped_credit_notes = array();
  1428. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  1429. $searchPreviousInvoice = true;
  1430. while ($searchPreviousInvoice) {
  1431. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  1432. $searchPreviousInvoice = false; // find, exit;
  1433. break;
  1434. } else {
  1435. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  1436. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  1437. }
  1438. $lineIndex--; // go to previous invoice in cycle
  1439. }
  1440. }
  1441. $maxPrevSituationPercent = 0;
  1442. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  1443. if ($prevLine->id == $source_fk_prev_id) {
  1444. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  1445. //$line->subprice = $line->subprice - $prevLine->subprice;
  1446. $line->total_ht = $line->total_ht - $prevLine->total_ht;
  1447. $line->total_tva = $line->total_tva - $prevLine->total_tva;
  1448. $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
  1449. $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
  1450. $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
  1451. $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
  1452. $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
  1453. $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
  1454. $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
  1455. }
  1456. }
  1457. // prorata
  1458. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  1459. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1460. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  1461. $maxPrevSituationPercent = 0;
  1462. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  1463. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  1464. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  1465. $maxPrevSituationPercent = $prevLine->situation_percent;
  1466. $line->total_ht -= $prevLine->total_ht;
  1467. $line->total_tva -= $prevLine->total_tva;
  1468. $line->total_ttc -= $prevLine->total_ttc;
  1469. $line->total_localtax1 -= $prevLine->total_localtax1;
  1470. $line->total_localtax2 -= $prevLine->total_localtax2;
  1471. $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
  1472. $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
  1473. $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
  1474. $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
  1475. }
  1476. }
  1477. }
  1478. // prorata
  1479. $line->situation_percent += $maxPrevSituationPercent;
  1480. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1481. }
  1482. }
  1483. $line->fk_facture = $object->id;
  1484. $line->fk_parent_line = $fk_parent_line;
  1485. $line->subprice = -$line->subprice; // invert price for object
  1486. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  1487. $line->total_ht = -$line->total_ht;
  1488. $line->total_tva = -$line->total_tva;
  1489. $line->total_ttc = -$line->total_ttc;
  1490. $line->total_localtax1 = -$line->total_localtax1;
  1491. $line->total_localtax2 = -$line->total_localtax2;
  1492. $line->multicurrency_subprice = -$line->multicurrency_subprice;
  1493. $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
  1494. $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
  1495. $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
  1496. $line->context['createcreditnotefrominvoice'] = 1;
  1497. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  1498. $object->lines[] = $line; // insert new line in current object
  1499. // Defined the new fk_parent_line
  1500. if ($result > 0 && $line->product_type == 9) {
  1501. $fk_parent_line = $result;
  1502. }
  1503. }
  1504. $object->update_price(1);
  1505. }
  1506. }
  1507. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  1508. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1509. $totalpaid = $facture_source->getSommePaiement();
  1510. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  1511. $totaldeposits = $facture_source->getSumDepositsUsed();
  1512. $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
  1513. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
  1514. }
  1515. }
  1516. // Add link between credit note and origin
  1517. if (!empty($object->fk_facture_source) && $id > 0) {
  1518. $facture_source->fetch($object->fk_facture_source);
  1519. $facture_source->fetchObjectLinked();
  1520. if (!empty($facture_source->linkedObjectsIds)) {
  1521. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  1522. $object->add_object_linked($sourcetype, current($TIds));
  1523. }
  1524. }
  1525. }
  1526. }
  1527. }
  1528. // Standard invoice or Deposit invoice, created from a Predefined template invoice
  1529. if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT || GETPOST('type') == Facture::TYPE_RECEIPT) && GETPOST('fac_rec', 'int') > 0) {
  1530. if (empty($dateinvoice)) {
  1531. $error++;
  1532. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1533. $action = 'create';
  1534. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1535. $error++;
  1536. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1537. $action = 'create';
  1538. }
  1539. if (!$error) {
  1540. $object->socid = GETPOST('socid', 'int');
  1541. $object->type = GETPOST('type');
  1542. $object->ref = GETPOST('ref');
  1543. $object->date = $dateinvoice;
  1544. $object->date_pointoftax = $date_pointoftax;
  1545. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1546. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1547. $object->ref_customer = GETPOST('ref_client');
  1548. $object->ref_client = $object->ref_customer;
  1549. $object->model_pdf = GETPOST('model');
  1550. $object->fk_project = GETPOST('projectid', 'int');
  1551. $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  1552. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1553. $object->fk_account = GETPOST('fk_account', 'int');
  1554. $object->amount = price2num(GETPOST('amount'));
  1555. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1556. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1557. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1558. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1559. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1560. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1561. // Source facture
  1562. $object->fac_rec = GETPOST('fac_rec', 'int');
  1563. $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines
  1564. }
  1565. }
  1566. // Standard or deposit invoice, not from a Predefined template invoice
  1567. if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT || GETPOST('type') == Facture::TYPE_PROFORMA || (GETPOST('type') == Facture::TYPE_SITUATION || GETPOST('type') == Facture::TYPE_RECEIPT && !GETPOST('situations'))) && GETPOST('fac_rec') <= 0) {
  1568. $typeamount = GETPOST('typedeposit', 'aZ09');
  1569. $valuestandardinvoice = price2num(str_replace('%', '', GETPOST('valuestandardinvoice', 'alpha')), 'MU');
  1570. $valuepeceipt = price2num(str_replace('%', '', GETPOST('valuepeceipt', 'alpha')), 'MU');
  1571. $valuedeposit = price2num(str_replace('%', '', GETPOST('valuedeposit', 'alpha')), 'MU');
  1572. if (GETPOST('socid', 'int') < 1) {
  1573. $error++;
  1574. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
  1575. $action = 'create';
  1576. }
  1577. if (empty($dateinvoice)) {
  1578. $error++;
  1579. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1580. $action = 'create';
  1581. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1582. $error++;
  1583. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1584. $action = 'create';
  1585. }
  1586. if (GETPOST('type') == Facture::TYPE_STANDARD) {
  1587. if ($valuestandardinvoice < 0 || $valuestandardinvoice > 100) {
  1588. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1589. $error++;
  1590. $action = 'create';
  1591. }
  1592. } elseif (GETPOST('type') == Facture::TYPE_RECEIPT) {
  1593. if ($valuepeceipt < 0 || $valuepeceipt > 100) {
  1594. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1595. $error++;
  1596. $action = 'create';
  1597. }
  1598. } elseif (GETPOST('type') == Facture::TYPE_DEPOSIT) {
  1599. if ($typeamount && !empty($origin) && !empty($originid)) {
  1600. if ($typeamount == 'amount' && $valuedeposit <= 0) {
  1601. setEventMessages($langs->trans("ErrorAnAmountWithoutTaxIsRequired"), null, 'errors');
  1602. $error++;
  1603. $action = 'create';
  1604. }
  1605. if ($typeamount == 'variable' && $valuedeposit <= 0) {
  1606. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1607. $error++;
  1608. $action = 'create';
  1609. }
  1610. if ($typeamount == 'variablealllines' && $valuedeposit <= 0) {
  1611. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1612. $error++;
  1613. $action = 'create';
  1614. }
  1615. }
  1616. }
  1617. if (!$error) {
  1618. // Si facture standard
  1619. $object->socid = GETPOST('socid', 'int');
  1620. $object->type = GETPOST('type');
  1621. $object->ref = GETPOST('ref');
  1622. $object->date = $dateinvoice;
  1623. $object->date_pointoftax = $date_pointoftax;
  1624. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1625. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1626. $object->ref_client = GETPOST('ref_client');
  1627. $object->ref_customer = GETPOST('ref_client');
  1628. $object->model_pdf = GETPOST('model');
  1629. $object->fk_project = GETPOST('projectid', 'int');
  1630. $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  1631. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  1632. $object->fk_account = GETPOST('fk_account', 'int');
  1633. $object->amount = price2num(GETPOST('amount'));
  1634. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1635. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1636. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1637. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1638. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1639. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1640. if (GETPOST('type') == Facture::TYPE_SITUATION) {
  1641. $object->situation_counter = 1;
  1642. $object->situation_final = 0;
  1643. $object->situation_cycle_ref = $object->newCycle();
  1644. }
  1645. if (in_array($object->type, $retainedWarrantyInvoiceAvailableType)) {
  1646. $object->retained_warranty = GETPOST('retained_warranty', 'int');
  1647. $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  1648. } else {
  1649. $object->retained_warranty = 0;
  1650. $object->retained_warranty_fk_cond_reglement = 0;
  1651. }
  1652. $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
  1653. if (!empty($retained_warranty_date_limit) && dol_stringtotime($retained_warranty_date_limit)) {
  1654. $object->retained_warranty_date_limit = dol_stringtotime($retained_warranty_date_limit);
  1655. }
  1656. $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  1657. $object->fetch_thirdparty();
  1658. // If creation from another object of another module (Example: origin=propal, originid=1)
  1659. if (!empty($origin) && !empty($originid)) {
  1660. $regs = array();
  1661. // Parse element/subelement (ex: project_task)
  1662. $element = $subelement = $origin;
  1663. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  1664. $element = $regs[1];
  1665. $subelement = $regs[2];
  1666. }
  1667. // For compatibility
  1668. if ($element == 'order') {
  1669. $element = $subelement = 'commande';
  1670. }
  1671. if ($element == 'propal') {
  1672. $element = 'comm/propal';
  1673. $subelement = 'propal';
  1674. }
  1675. if ($element == 'contract') {
  1676. $element = $subelement = 'contrat';
  1677. }
  1678. if ($element == 'inter') {
  1679. $element = $subelement = 'ficheinter';
  1680. }
  1681. if ($element == 'shipping') {
  1682. $element = $subelement = 'expedition';
  1683. }
  1684. $object->origin = $origin;
  1685. $object->origin_id = $originid;
  1686. // Possibility to add external linked objects with hooks
  1687. $object->linked_objects[$object->origin] = $object->origin_id;
  1688. // link with order if it is a shipping invoice
  1689. if ($object->origin == 'shipping') {
  1690. require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
  1691. $exp = new Expedition($db);
  1692. $exp->fetch($object->origin_id);
  1693. $exp->fetchObjectLinked();
  1694. if (is_array($exp->linkedObjectsIds['commande']) && count($exp->linkedObjectsIds['commande']) > 0) {
  1695. foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
  1696. $object->linked_objects['commande'] = $value;
  1697. }
  1698. }
  1699. }
  1700. if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
  1701. $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
  1702. }
  1703. $id = $object->create($user); // This include class to add_object_linked() and add add_contact()
  1704. if ($id > 0) {
  1705. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  1706. $classname = ucfirst($subelement);
  1707. $srcobject = new $classname($db);
  1708. dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines");
  1709. $result = $srcobject->fetch($object->origin_id);
  1710. // If deposit invoice - down payment with 1 line (fixed amount or percent)
  1711. if (GETPOST('type') == Facture::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
  1712. // Define the array $amountdeposit
  1713. $amountdeposit = array();
  1714. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
  1715. if ($typeamount == 'amount') {
  1716. $amount = $valuedeposit;
  1717. } else {
  1718. $amount = $srcobject->total_ttc * ($valuedeposit / 100);
  1719. }
  1720. $TTotalByTva = array();
  1721. foreach ($srcobject->lines as &$line) {
  1722. if (!empty($line->special_code)) {
  1723. continue;
  1724. }
  1725. $TTotalByTva[$line->tva_tx] += $line->total_ttc;
  1726. }
  1727. foreach ($TTotalByTva as $tva => &$total) {
  1728. $coef = $total / $srcobject->total_ttc; // Calc coef
  1729. $am = $amount * $coef;
  1730. $amount_ttc_diff += $am;
  1731. $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
  1732. }
  1733. } else {
  1734. if ($typeamount == 'amount') {
  1735. $amountdeposit[0] = $valuedeposit;
  1736. } elseif ($typeamount == 'variable') {
  1737. if ($result > 0) {
  1738. $totalamount = 0;
  1739. $lines = $srcobject->lines;
  1740. $numlines = count($lines);
  1741. for ($i = 0; $i < $numlines; $i++) {
  1742. $qualified = 1;
  1743. if (empty($lines[$i]->qty)) {
  1744. $qualified = 0; // We discard qty=0, it is an option
  1745. }
  1746. if (!empty($lines[$i]->special_code)) {
  1747. $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
  1748. }
  1749. if ($qualified) {
  1750. $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
  1751. $tva_tx = $lines[$i]->tva_tx;
  1752. $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100;
  1753. }
  1754. }
  1755. if ($totalamount == 0) {
  1756. $amountdeposit[0] = 0;
  1757. }
  1758. } else {
  1759. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1760. $error++;
  1761. }
  1762. }
  1763. $amount_ttc_diff = $amountdeposit[0];
  1764. }
  1765. foreach ($amountdeposit as $tva => $amount) {
  1766. if (empty($amount)) {
  1767. continue;
  1768. }
  1769. $arraylist = array(
  1770. 'amount' => 'FixAmount',
  1771. 'variable' => 'VarAmount'
  1772. );
  1773. $descline = '(DEPOSIT)';
  1774. //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
  1775. if ($typeamount == 'amount') {
  1776. $descline .= ' (' . price($valuedeposit, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ')';
  1777. } elseif ($typeamount == 'variable') {
  1778. $descline .= ' (' . $valuedeposit . '%)';
  1779. }
  1780. $descline .= ' - ' . $srcobject->ref;
  1781. $result = $object->addline(
  1782. $descline,
  1783. $amount, // subprice
  1784. 1, // quantity
  1785. $tva, // vat rate
  1786. 0, // localtax1_tx
  1787. 0, // localtax2_tx
  1788. (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
  1789. 0, // remise_percent
  1790. 0, // date_start
  1791. 0, // date_end
  1792. 0,
  1793. $lines[$i]->info_bits, // info_bits
  1794. 0,
  1795. 'HT',
  1796. 0,
  1797. 0, // product_type
  1798. 1,
  1799. $lines[$i]->special_code,
  1800. $object->origin,
  1801. 0,
  1802. 0,
  1803. 0,
  1804. 0,
  1805. '',
  1806. 0,
  1807. 100,
  1808. 0,
  1809. null,
  1810. 0,
  1811. '',
  1812. 1
  1813. );
  1814. }
  1815. $diff = $object->total_ttc - $amount_ttc_diff;
  1816. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
  1817. $object->fetch_lines();
  1818. $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
  1819. $object->updateline($object->lines[0]->id, $object->lines[0]->desc, $subprice_diff, $object->lines[0]->qty, $object->lines[0]->remise_percent, $object->lines[0]->date_start, $object->lines[0]->date_end, $object->lines[0]->tva_tx, 0, 0, 'HT', $object->lines[0]->info_bits, $object->lines[0]->product_type, 0, 0, 0, $object->lines[0]->pa_ht, $object->lines[0]->label, 0, array(), 100);
  1820. }
  1821. }
  1822. // standard invoice, credit note, or down payment from a percent of all lines
  1823. if (GETPOST('type') != Facture::TYPE_DEPOSIT || (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines')) {
  1824. if ($result > 0) {
  1825. $lines = $srcobject->lines;
  1826. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1827. $srcobject->fetch_lines();
  1828. $lines = $srcobject->lines;
  1829. }
  1830. // If we create a standard invoice with a percent, we change amount by changing the qty
  1831. if (GETPOST('type') == Facture::TYPE_STANDARD && $valuestandardinvoice > 0 && $valuestandardinvoice < 100) {
  1832. if (is_array($lines)) {
  1833. foreach ($lines as $line) {
  1834. // We keep ->subprice and ->pa_ht, but we change the qty
  1835. $line->qty = price2num($line->qty * $valuestandardinvoice / 100, 'MS');
  1836. }
  1837. }
  1838. }
  1839. // If we create a receipt with a percent, we change amount by changing the qty
  1840. if (GETPOST('type') == Facture::TYPE_RECEIPT && $valuepeceipt > 0 && $valuepeceipt < 100) {
  1841. if (is_array($lines)) {
  1842. foreach ($lines as $line) {
  1843. // We keep ->subprice and ->pa_ht, but we change the qty
  1844. $line->qty = price2num($line->qty * $valuepeceipt / 100, 'MS');
  1845. }
  1846. }
  1847. }
  1848. // If we create a down payment with a percent on all lines, we change amount by changing the qty
  1849. if (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines') {
  1850. if (is_array($lines)) {
  1851. foreach ($lines as $line) {
  1852. // We keep ->subprice and ->pa_ht, but we change the qty
  1853. $line->qty = price2num($line->qty * $valuedeposit / 100, 'MS');
  1854. }
  1855. }
  1856. }
  1857. $fk_parent_line = 0;
  1858. $num = count($lines);
  1859. for ($i = 0; $i < $num; $i++) {
  1860. if (!in_array($lines[$i]->id, $selectedLines)) {
  1861. continue; // Skip unselected lines
  1862. }
  1863. // Don't add lines with qty 0 when coming from a shipment including all order lines
  1864. if ($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) {
  1865. continue;
  1866. }
  1867. // Don't add closed lines when coming from a contract (Set constant to '0,5' to exclude also inactive lines)
  1868. if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) {
  1869. $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5';
  1870. }
  1871. if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE))) {
  1872. continue;
  1873. }
  1874. $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
  1875. $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle);
  1876. if ($object->situation_counter == 1) {
  1877. $lines[$i]->situation_percent = 0;
  1878. }
  1879. if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) {
  1880. // Negative line, we create a discount line
  1881. $discount = new DiscountAbsolute($db);
  1882. $discount->fk_soc = $object->socid;
  1883. $discount->amount_ht = abs($lines[$i]->total_ht);
  1884. $discount->amount_tva = abs($lines[$i]->total_tva);
  1885. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  1886. $discount->tva_tx = $lines[$i]->tva_tx;
  1887. $discount->fk_user = $user->id;
  1888. $discount->description = $desc;
  1889. $discount->multicurrency_subprice = abs($lines[$i]->multicurrency_subprice);
  1890. $discount->multicurrency_amount_ht = abs($lines[$i]->multicurrency_total_ht);
  1891. $discount->multicurrency_amount_tva = abs($lines[$i]->multicurrency_total_tva);
  1892. $discount->multicurrency_amount_ttc = abs($lines[$i]->multicurrency_total_ttc);
  1893. $discountid = $discount->create($user);
  1894. if ($discountid > 0) {
  1895. $result = $object->insert_discount($discountid); // This include link_to_invoice
  1896. } else {
  1897. setEventMessages($discount->error, $discount->errors, 'errors');
  1898. $error++;
  1899. break;
  1900. }
  1901. } else {
  1902. // Positive line
  1903. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  1904. // Date start
  1905. $date_start = false;
  1906. if ($lines[$i]->date_debut_prevue) {
  1907. $date_start = $lines[$i]->date_debut_prevue;
  1908. }
  1909. if ($lines[$i]->date_debut_reel) {
  1910. $date_start = $lines[$i]->date_debut_reel;
  1911. }
  1912. if ($lines[$i]->date_start) {
  1913. $date_start = $lines[$i]->date_start;
  1914. }
  1915. // Date end
  1916. $date_end = false;
  1917. if ($lines[$i]->date_fin_prevue) {
  1918. $date_end = $lines[$i]->date_fin_prevue;
  1919. }
  1920. if ($lines[$i]->date_fin_reel) {
  1921. $date_end = $lines[$i]->date_fin_reel;
  1922. }
  1923. if ($lines[$i]->date_end) {
  1924. $date_end = $lines[$i]->date_end;
  1925. }
  1926. // Reset fk_parent_line for no child products and special product
  1927. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  1928. $fk_parent_line = 0;
  1929. }
  1930. // Extrafields
  1931. if (method_exists($lines[$i], 'fetch_optionals')) {
  1932. $lines[$i]->fetch_optionals();
  1933. $array_options = $lines[$i]->array_options;
  1934. }
  1935. $tva_tx = $lines[$i]->tva_tx;
  1936. if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
  1937. $tva_tx .= ' (' . $lines[$i]->vat_src_code . ')';
  1938. }
  1939. // View third's localtaxes for NOW and do not use value from origin.
  1940. // TODO Is this really what we want ? Yes if source is template invoice but what if proposal or order ?
  1941. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
  1942. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
  1943. $result = $object->addline(
  1944. $desc,
  1945. $lines[$i]->subprice,
  1946. $lines[$i]->qty,
  1947. $tva_tx,
  1948. $localtax1_tx,
  1949. $localtax2_tx,
  1950. $lines[$i]->fk_product,
  1951. $lines[$i]->remise_percent,
  1952. $date_start,
  1953. $date_end,
  1954. 0,
  1955. $lines[$i]->info_bits,
  1956. $lines[$i]->fk_remise_except,
  1957. 'HT',
  1958. 0,
  1959. $product_type,
  1960. $lines[$i]->rang,
  1961. $lines[$i]->special_code,
  1962. $object->origin,
  1963. $lines[$i]->rowid,
  1964. $fk_parent_line,
  1965. $lines[$i]->fk_fournprice,
  1966. $lines[$i]->pa_ht,
  1967. $label,
  1968. $array_options,
  1969. $lines[$i]->situation_percent,
  1970. $lines[$i]->fk_prev_id,
  1971. $lines[$i]->fk_unit,
  1972. 0,
  1973. '',
  1974. 1
  1975. );
  1976. if ($result > 0) {
  1977. $lineid = $result;
  1978. } else {
  1979. $lineid = 0;
  1980. $error++;
  1981. break;
  1982. }
  1983. // Defined the new fk_parent_line
  1984. if ($result > 0 && $lines[$i]->product_type == 9) {
  1985. $fk_parent_line = $result;
  1986. }
  1987. }
  1988. }
  1989. } else {
  1990. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1991. $error++;
  1992. }
  1993. }
  1994. $object->update_price(1, 'auto', 0, $mysoc);
  1995. // Now we create same links to contact than the ones found on origin object
  1996. /* Useless, already into the create
  1997. if (!empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
  1998. {
  1999. $originforcontact = $object->origin;
  2000. $originidforcontact = $object->origin_id;
  2001. if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
  2002. {
  2003. $originforcontact=$srcobject->origin;
  2004. $originidforcontact=$srcobject->origin_id;
  2005. }
  2006. $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  2007. $sqlcontact.= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'";
  2008. $resqlcontact = $db->query($sqlcontact);
  2009. if ($resqlcontact)
  2010. {
  2011. while($objcontact = $db->fetch_object($resqlcontact))
  2012. {
  2013. //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
  2014. $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
  2015. }
  2016. }
  2017. else dol_print_error($resqlcontact);
  2018. }*/
  2019. // Hooks
  2020. $parameters = array('objFrom' => $srcobject);
  2021. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
  2022. // modified by hook
  2023. if ($reshook < 0) {
  2024. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2025. $error++;
  2026. }
  2027. } else {
  2028. setEventMessages($object->error, $object->errors, 'errors');
  2029. $error++;
  2030. }
  2031. } else { // If some invoice's lines coming from page
  2032. $id = $object->create($user);
  2033. for ($i = 1; $i <= $NBLINES; $i++) {
  2034. if (GETPOST('idprod' . $i, 'int')) {
  2035. $product = new Product($db);
  2036. $product->fetch(GETPOST('idprod' . $i, 'int'));
  2037. $startday = dol_mktime(12, 0, 0, GETPOST('date_start' . $i . 'month'), GETPOST('date_start' . $i . 'day'), GETPOST('date_start' . $i . 'year'));
  2038. $endday = dol_mktime(12, 0, 0, GETPOST('date_end' . $i . 'month'), GETPOST('date_end' . $i . 'day'), GETPOST('date_end' . $i . 'year'));
  2039. $result = $object->addline($product->description, $product->price, price2num(GETPOST('qty' . $i), 'MS'), $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, GETPOST('idprod' . $i, 'int'), price2num(GETPOST('remise_percent' . $i), '', 2), $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, null, 0, '', 0, 100, '', $product->fk_unit, 0, '', 1);
  2040. }
  2041. }
  2042. $object->update_price(1, 'auto', 0, $mysoc);
  2043. }
  2044. }
  2045. }
  2046. // Situation invoices
  2047. if (GETPOST('type') == Facture::TYPE_SITUATION && GETPOST('situations')) {
  2048. if (empty($dateinvoice)) {
  2049. $error++;
  2050. $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date"));
  2051. setEventMessages($mesg, null, 'errors');
  2052. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  2053. $error++;
  2054. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  2055. $action = 'create';
  2056. }
  2057. if (!(GETPOST('situations', 'int') > 0)) {
  2058. $error++;
  2059. $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSituation"));
  2060. setEventMessages($mesg, null, 'errors');
  2061. $action = 'create';
  2062. }
  2063. if (!$error) {
  2064. $result = $object->fetch(GETPOST('situations', 'int'));
  2065. $object->fk_facture_source = GETPOST('situations', 'int');
  2066. $object->type = Facture::TYPE_SITUATION;
  2067. if (!empty($origin) && !empty($originid)) {
  2068. include_once DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php';
  2069. $object->origin = $origin;
  2070. $object->origin_id = $originid;
  2071. // retained warranty
  2072. if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  2073. $retained_warranty = GETPOST('retained_warranty', 'int');
  2074. if (price2num($retained_warranty) > 0) {
  2075. $object->retained_warranty = price2num($retained_warranty);
  2076. }
  2077. if (GETPOST('retained_warranty_fk_cond_reglement', 'int') > 0) {
  2078. $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  2079. }
  2080. $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
  2081. if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) {
  2082. $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit);
  2083. }
  2084. $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  2085. }
  2086. foreach ($object->lines as $i => &$line) {
  2087. $line->origin = $object->origin;
  2088. $line->origin_id = $line->id;
  2089. $line->fk_prev_id = $line->id;
  2090. $line->fetch_optionals();
  2091. $line->situation_percent = $line->get_prev_progress($object->id); // get good progress including credit note
  2092. // The $line->situation_percent has been modified, so we must recalculate all amounts
  2093. $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, '', $line->situation_percent);
  2094. $line->total_ht = $tabprice[0];
  2095. $line->total_tva = $tabprice[1];
  2096. $line->total_ttc = $tabprice[2];
  2097. $line->total_localtax1 = $tabprice[9];
  2098. $line->total_localtax2 = $tabprice[10];
  2099. $line->multicurrency_total_ht = $tabprice[16];
  2100. $line->multicurrency_total_tva = $tabprice[17];
  2101. $line->multicurrency_total_ttc = $tabprice[18];
  2102. // Si fk_remise_except defini on vérifie si la réduction à déjà été appliquée
  2103. if ($line->fk_remise_except) {
  2104. $discount = new DiscountAbsolute($line->db);
  2105. $result = $discount->fetch($line->fk_remise_except);
  2106. if ($result > 0) {
  2107. // Check if discount not already affected to another invoice
  2108. if ($discount->fk_facture_line > 0) {
  2109. $line->fk_remise_except = 0;
  2110. }
  2111. }
  2112. }
  2113. }
  2114. }
  2115. $object->fetch_thirdparty();
  2116. $object->date = $dateinvoice;
  2117. $object->date_pointoftax = $date_pointoftax;
  2118. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  2119. $object->note = trim(GETPOST('note', 'restricthtml'));
  2120. $object->note_private = trim(GETPOST('note', 'restricthtml'));
  2121. $object->ref_client = GETPOST('ref_client', 'alpha');
  2122. $object->model_pdf = GETPOST('model', 'alpha');
  2123. $object->fk_project = GETPOST('projectid', 'int');
  2124. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  2125. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  2126. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU', 2);
  2127. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  2128. // Proprietes particulieres a facture de remplacement
  2129. $object->situation_counter = $object->situation_counter + 1;
  2130. $id = $object->createFromCurrent($user);
  2131. if ($id <= 0) {
  2132. $mesg = $object->error;
  2133. } else {
  2134. $nextSituationInvoice = new Facture($db);
  2135. $nextSituationInvoice->fetch($id);
  2136. // create extrafields with data from create form
  2137. $extrafields->fetch_name_optionals_label($nextSituationInvoice->table_element);
  2138. $ret = $extrafields->setOptionalsFromPost(null, $nextSituationInvoice);
  2139. if ($ret > 0) {
  2140. $nextSituationInvoice->insertExtraFields();
  2141. }
  2142. }
  2143. }
  2144. }
  2145. #-------------------------------------------------------------------
  2146. # CUSTOMER CHANGE
  2147. #-------------------------------------------------------------------*/
  2148. if (GETPOST('type') == Facture::TYPE_CUSTOMERCHANGE) {
  2149. if ($object->array_options['options_commission_deduction']) {
  2150. $factureObj = new Facture($db);
  2151. $userinvoiceObj = new UserInvoice($db);
  2152. $commmissionhandler = new CommissionHandler();
  2153. $productObj = new Product($db);
  2154. $productObjHUF = new Product($db);
  2155. $fk_facture_resource = GETPOST('fac_avoir', 'int');
  2156. $result_source_facture = $factureObj->fetch($fk_facture_resource);
  2157. if ($factureObj->fk_multicurrency == 2) {
  2158. $fk_product = $factureObj->lines[0]->fk_product;
  2159. $assignedProduct = $productObj->fetch($fk_product);
  2160. $relatedService = $productObj->array_options['options_related_service'];
  2161. $productToCount = $productObjHUF->fetch($relatedService);
  2162. $price_ttc = $productObjHUF->price_ttc;
  2163. $commissionValue = $productObjHUF->array_options['options_commission_value'];
  2164. $type = $productObjHUF->array_options['options_commission_type'] == 1 ? '%' : 'Forint';
  2165. $row['total_ttc'] = $price_ttc;
  2166. $row['commission'] = $commissionValue . '_' . $type;
  2167. ;
  2168. $amount = $commmissionhandler->getAmountOfCommission($row);
  2169. } else {
  2170. $row['total_ttc'] = $factureObj->total_ttc;
  2171. $row['commission'] = $factureObj->array_options['options_commission'];
  2172. $amount = $commmissionhandler->getAmountOfCommission($row);
  2173. }
  2174. $resultUserinvoiceObj = $userinvoiceObj->fetchAll('', '', 0, 0, ["customsql" => "invoices LIKE '%{$factureObj->id}%'"]);
  2175. $usersArray = [];
  2176. foreach ($resultUserinvoiceObj as $userObj) {
  2177. $usersArray[] = $userObj->user_id;
  2178. }
  2179. $numberOfUsers = count($usersArray);
  2180. if ($numberOfUsers > 0) {
  2181. $amountOfOneUser = $amount / $numberOfUsers;
  2182. foreach ($usersArray as $userid) {
  2183. if ($amountOfOneUser > 0) {
  2184. $userinvoiceObj2 = new UserInvoice($db);
  2185. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  2186. ;
  2187. $userinvoiceObj2->label = 'Visszatartás/Withholding ' . date('Y.m.d');
  2188. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amountOfOneUser . ' HUF. Commission deduction.(Customer Change)';
  2189. $userinvoiceObj2->user_id = $userid;
  2190. $userinvoiceObj2->payment_type = 1;
  2191. $userinvoiceObj2->amount = $amountOfOneUser;
  2192. $userinvoiceObj2->currency = 0;
  2193. $userinvoiceObj2->individual = 1;
  2194. $userinvoiceObj2->invoices = $factureObj->id;
  2195. $result = $userinvoiceObj2->create($user);
  2196. if ($result < 0) {
  2197. $error++;
  2198. }
  2199. }
  2200. }
  2201. } else {
  2202. if ($amount > 0) {
  2203. $userinvoiceObj2 = new UserInvoice($db);
  2204. $userinvoiceObj2->ref = 'Withhold_' . dol_now() . '_' . rand(1000000, 9999999);
  2205. ;
  2206. $userinvoiceObj2->label = 'Visszatartás/Withholding ' . date('Y.m.d');
  2207. $userinvoiceObj2->description = 'Összeg / Amount: ' . $amount . ' HUF. Commission deduction.(Customer Change)';
  2208. $userinvoiceObj2->user_id = $factureObj->fk_user_valid;
  2209. $userinvoiceObj2->payment_type = 1;
  2210. $userinvoiceObj2->amount = $amount;
  2211. $userinvoiceObj2->currency = 0;
  2212. $userinvoiceObj2->individual = 1;
  2213. $userinvoiceObj2->invoices = $factureObj->id;
  2214. $result = $userinvoiceObj2->create($user);
  2215. if ($result < 0) {
  2216. $error++;
  2217. }
  2218. }
  2219. }
  2220. }
  2221. $sourceinvoice = GETPOST('fac_avoir', 'int');
  2222. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  2223. $error++;
  2224. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  2225. $action = 'create';
  2226. }
  2227. if (empty($dateinvoice)) {
  2228. $error++;
  2229. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  2230. $action = 'create';
  2231. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  2232. $error++;
  2233. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  2234. $action = 'create';
  2235. }
  2236. #-------------------------------------------------------------------
  2237. # CREATE CREDIT NOTE INVOICE BEFORE NEW CUSTOMER'S STANDARD INVOICE
  2238. #-------------------------------------------------------------------
  2239. $factureObj = new Facture($db);
  2240. $factureObj->fetch(GETPOST('fac_avoir'));
  2241. if ($factureObj->type == 0) {
  2242. $CreditNoteType = Facture::TYPE_CREDIT_NOTE;
  2243. }
  2244. if ($factureObj->type == 7) {
  2245. $CreditNoteType = Facture::TYPE_RECEIPT_CREDIT_NOTE;
  2246. }
  2247. //print_r($object);
  2248. if (!$error) {
  2249. if (!empty($originentity)) {
  2250. $object->entity = $originentity;
  2251. }
  2252. //$object->socid = GETPOST('socid', 'int');
  2253. $object->ref = GETPOST('ref');
  2254. $object->date = $dateinvoice;
  2255. $object->date_pointoftax = $date_pointoftax;
  2256. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  2257. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  2258. $object->ref_client = GETPOST('ref_client');
  2259. $object->model_pdf = GETPOST('model');
  2260. $object->fk_project = GETPOST('projectid', 'int');
  2261. $object->cond_reglement_id = 0; // No payment term for a credit note
  2262. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  2263. $object->fk_account = GETPOST('fk_account', 'int');
  2264. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  2265. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  2266. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  2267. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  2268. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  2269. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  2270. // Proprietes particulieres a facture avoir
  2271. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  2272. $object->type = $CreditNoteType;
  2273. $facture_source = new Facture($db); // fetch origin object
  2274. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  2275. if ($facture_source->type == Facture::TYPE_SITUATION) {
  2276. $object->situation_counter = $facture_source->situation_counter;
  2277. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  2278. $facture_source->fetchPreviousNextSituationInvoice();
  2279. }
  2280. }
  2281. // We have to add the facture_source socid to the credit note invoice fk_socid
  2282. $object->socid = $facture_source->socid;
  2283. $id = $object->create($user);
  2284. if ($id < 0) {
  2285. $error++;
  2286. } else {
  2287. // copy internal contacts
  2288. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  2289. $error++;
  2290. } elseif ($facture_source->socid == $object->socid) {
  2291. // copy external contacts if same company
  2292. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  2293. $error++;
  2294. }
  2295. }
  2296. }
  2297. // NOTE: Pb with situation invoice
  2298. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  2299. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  2300. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  2301. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  2302. if (($factureObj->type == 0 || $factureObj->type == 7) && $id > 0) {
  2303. if (!empty($facture_source->lines)) {
  2304. $fk_parent_line = 0;
  2305. foreach ($facture_source->lines as $line) {
  2306. // Extrafields
  2307. if (method_exists($line, 'fetch_optionals')) {
  2308. // load extrafields
  2309. $line->fetch_optionals();
  2310. }
  2311. // Reset fk_parent_line for no child products and special product
  2312. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  2313. $fk_parent_line = 0;
  2314. }
  2315. if ($facture_source->type == Facture::TYPE_SITUATION) {
  2316. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  2317. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  2318. if (!empty($facture_source->tab_previous_situation_invoice)) {
  2319. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  2320. // TODO Move this out of loop of $facture_source->lines
  2321. $tab_jumped_credit_notes = array();
  2322. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  2323. $searchPreviousInvoice = true;
  2324. while ($searchPreviousInvoice) {
  2325. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  2326. $searchPreviousInvoice = false; // find, exit;
  2327. break;
  2328. } else {
  2329. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
  2330. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  2331. }
  2332. $lineIndex--; // go to previous invoice in cycle
  2333. }
  2334. }
  2335. $maxPrevSituationPercent = 0;
  2336. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  2337. if ($prevLine->id == $source_fk_prev_id) {
  2338. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  2339. //$line->subprice = $line->subprice - $prevLine->subprice;
  2340. $line->total_ht = $line->total_ht - $prevLine->total_ht;
  2341. $line->total_tva = $line->total_tva - $prevLine->total_tva;
  2342. $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
  2343. $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
  2344. $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
  2345. $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
  2346. $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
  2347. $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
  2348. $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
  2349. }
  2350. }
  2351. // prorata
  2352. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  2353. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  2354. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  2355. $maxPrevSituationPercent = 0;
  2356. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  2357. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  2358. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  2359. $maxPrevSituationPercent = $prevLine->situation_percent;
  2360. $line->total_ht -= $prevLine->total_ht;
  2361. $line->total_tva -= $prevLine->total_tva;
  2362. $line->total_ttc -= $prevLine->total_ttc;
  2363. $line->total_localtax1 -= $prevLine->total_localtax1;
  2364. $line->total_localtax2 -= $prevLine->total_localtax2;
  2365. $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
  2366. $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
  2367. $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
  2368. $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
  2369. }
  2370. }
  2371. }
  2372. // prorata
  2373. $line->situation_percent += $maxPrevSituationPercent;
  2374. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  2375. }
  2376. }
  2377. $line->fk_facture = $object->id;
  2378. $line->fk_parent_line = $fk_parent_line;
  2379. $line->subprice = -$line->subprice; // invert price for object
  2380. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  2381. $line->total_ht = -$line->total_ht;
  2382. $line->total_tva = -$line->total_tva;
  2383. $line->total_ttc = -$line->total_ttc;
  2384. $line->total_localtax1 = -$line->total_localtax1;
  2385. $line->total_localtax2 = -$line->total_localtax2;
  2386. $line->multicurrency_subprice = -$line->multicurrency_subprice;
  2387. $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
  2388. $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
  2389. $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
  2390. $line->context['createcustomernamefrominvoice'] = 1;
  2391. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  2392. $object->lines[] = $line; // insert new line in current object
  2393. // Defined the new fk_parent_line
  2394. if ($result > 0 && $line->product_type == 9) {
  2395. $fk_parent_line = $result;
  2396. }
  2397. }
  2398. $object->update_price(1);
  2399. }
  2400. }
  2401. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  2402. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  2403. $totalpaid = $facture_source->getSommePaiement();
  2404. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  2405. $totaldeposits = $facture_source->getSumDepositsUsed();
  2406. $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
  2407. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
  2408. }
  2409. }
  2410. // Add link between credit note and origin
  2411. if (!empty($object->fk_facture_source) && $id > 0) {
  2412. $facture_source->fetch($object->fk_facture_source);
  2413. $facture_source->fetchObjectLinked();
  2414. if (!empty($facture_source->linkedObjectsIds)) {
  2415. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  2416. $object->add_object_linked($sourcetype, current($TIds));
  2417. }
  2418. }
  2419. }
  2420. }
  2421. #-------------------------------------------------------------------
  2422. # VALIDATE CREDITNOTE
  2423. #-------------------------------------------------------------------
  2424. $object->fetch($id);
  2425. $object->fetch_thirdparty();
  2426. $result = $object->validate($user, '', $idwarehouse);
  2427. #-------------------------------------------------------------------
  2428. # CREATE NEW CUSTOMER'S INVOICE AFTER CREDIT NOTE INVOICE
  2429. #-------------------------------------------------------------------
  2430. // Need to set empty the lines, because the array containes the minus lines from the credit note invoice
  2431. $object->lines = [];
  2432. if (!$error) {
  2433. if (GETPOST('invoiceAvoirWithLinesCustomerChange') == 0) {
  2434. $FactureType = Facture::TYPE_STANDARD;
  2435. }
  2436. if (GETPOST('invoiceAvoirWithLinesReceiptCustomerChange') == 7) {
  2437. $FactureType = Facture::TYPE_RECEIPT;
  2438. }
  2439. if (!empty($originentity)) {
  2440. $object->entity = $originentity;
  2441. }
  2442. $object->socid = GETPOST('socid', 'int');
  2443. $object->ref = GETPOST('ref');
  2444. $object->date = $dateinvoice;
  2445. $object->date_pointoftax = $date_pointoftax;
  2446. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  2447. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  2448. $object->ref_client = GETPOST('ref_client');
  2449. $object->model_pdf = GETPOST('model');
  2450. $object->fk_project = GETPOST('projectid', 'int');
  2451. $object->cond_reglement_id = 0; // No payment term for a credit note
  2452. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  2453. $object->fk_account = GETPOST('fk_account', 'int');
  2454. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  2455. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  2456. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  2457. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  2458. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  2459. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  2460. // Proprietes particulieres a facture avoir
  2461. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  2462. $object->type = $FactureType;
  2463. $facture_source = new Facture($db); // fetch origin object
  2464. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  2465. if ($facture_source->type == Facture::TYPE_SITUATION) {
  2466. $object->situation_counter = $facture_source->situation_counter;
  2467. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  2468. $facture_source->fetchPreviousNextSituationInvoice();
  2469. }
  2470. }
  2471. $id = $object->create($user);
  2472. if ($id < 0) {
  2473. $error++;
  2474. } else {
  2475. // copy internal contacts
  2476. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  2477. $error++;
  2478. } elseif ($facture_source->socid == $object->socid) {
  2479. // copy external contacts if same company
  2480. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  2481. $error++;
  2482. }
  2483. }
  2484. }
  2485. //print GETPOST('invoiceAvoirWithLinesCustomerChange', 'int');exit;
  2486. // NOTE: Pb with situation invoice
  2487. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  2488. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  2489. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  2490. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  2491. if (($factureObj->type == 0 || $factureObj->type == 7) && $id > 0) {
  2492. if (!empty($facture_source->lines)) {
  2493. $fk_parent_line = 0;
  2494. foreach ($facture_source->lines as $line) {
  2495. // Extrafields
  2496. if (method_exists($line, 'fetch_optionals')) {
  2497. // load extrafields
  2498. $line->fetch_optionals();
  2499. }
  2500. // Reset fk_parent_line for no child products and special product
  2501. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  2502. $fk_parent_line = 0;
  2503. }
  2504. if ($facture_source->type == Facture::TYPE_SITUATION) {
  2505. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  2506. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  2507. if (!empty($facture_source->tab_previous_situation_invoice)) {
  2508. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  2509. // TODO Move this out of loop of $facture_source->lines
  2510. $tab_jumped_credit_notes = array();
  2511. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  2512. $searchPreviousInvoice = true;
  2513. while ($searchPreviousInvoice) {
  2514. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  2515. $searchPreviousInvoice = false; // find, exit;
  2516. break;
  2517. } else {
  2518. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
  2519. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  2520. }
  2521. $lineIndex--; // go to previous invoice in cycle
  2522. }
  2523. }
  2524. $maxPrevSituationPercent = 0;
  2525. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  2526. if ($prevLine->id == $source_fk_prev_id) {
  2527. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  2528. }
  2529. }
  2530. // prorata
  2531. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  2532. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  2533. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  2534. $maxPrevSituationPercent = 0;
  2535. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  2536. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  2537. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  2538. $maxPrevSituationPercent = $prevLine->situation_percent;
  2539. }
  2540. }
  2541. }
  2542. // prorata
  2543. $line->situation_percent += $maxPrevSituationPercent;
  2544. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  2545. }
  2546. }
  2547. $line->fk_facture = $object->id;
  2548. $line->fk_parent_line = $fk_parent_line;
  2549. //$line->subprice = -$line->subprice; // invert price for object
  2550. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  2551. $line->context['createcreditnotefrominvoice'] = 1;
  2552. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  2553. $object->lines[] = $line; // insert new line in current object
  2554. // Defined the new fk_parent_line
  2555. if ($result > 0 && $line->product_type == 9) {
  2556. $fk_parent_line = $result;
  2557. }
  2558. }
  2559. $object->update_price(1);
  2560. }
  2561. }
  2562. // Add link between credit note and origin
  2563. if (!empty($object->fk_facture_source) && $id > 0) {
  2564. $facture_source->fetch($object->fk_facture_source);
  2565. $facture_source->fetchObjectLinked();
  2566. if (!empty($facture_source->linkedObjectsIds)) {
  2567. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  2568. $object->add_object_linked($sourcetype, current($TIds));
  2569. }
  2570. }
  2571. }
  2572. }
  2573. }
  2574. #-------------------------------------------------------------------
  2575. # Commission deduction (add Withholding)
  2576. #-------------------------------------------------------------------
  2577. // End of object creation, we show it
  2578. if ($id > 0 && !$error) {
  2579. $db->commit();
  2580. // Define output language
  2581. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($object->lines)) {
  2582. $outputlangs = $langs;
  2583. $newlang = '';
  2584. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  2585. $newlang = GETPOST('lang_id', 'aZ09');
  2586. }
  2587. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  2588. $newlang = $object->thirdparty->default_lang;
  2589. }
  2590. if (!empty($newlang)) {
  2591. $outputlangs = new Translate("", $conf);
  2592. $outputlangs->setDefaultLang($newlang);
  2593. $outputlangs->load('products');
  2594. }
  2595. $model = $object->model_pdf;
  2596. $ret = $object->fetch($id); // Reload to get new records
  2597. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  2598. if ($result < 0) {
  2599. setEventMessages($object->error, $object->errors, 'errors');
  2600. }
  2601. }
  2602. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id);
  2603. exit();
  2604. } else {
  2605. $db->rollback();
  2606. $action = 'create';
  2607. $_GET["origin"] = $_POST["origin"];
  2608. $_GET["originid"] = $_POST["originid"];
  2609. setEventMessages($object->error, $object->errors, 'errors');
  2610. }
  2611. } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '') {
  2612. // Define vat_rate
  2613. $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
  2614. $vat_rate = str_replace('*', '', $vat_rate);
  2615. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
  2616. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
  2617. foreach ($object->lines as $line) {
  2618. $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
  2619. }
  2620. } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('remiseforalllines', 'alpha') !== '' && $usercancreate) {
  2621. // Define vat_rate
  2622. $remise_percent = (GETPOST('remiseforalllines') ? GETPOST('remiseforalllines') : 0);
  2623. $remise_percent = str_replace('*', '', $remise_percent);
  2624. foreach ($object->lines as $line) {
  2625. $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
  2626. }
  2627. } elseif ($action == 'addline' && $usercancreate) { // Add a new line
  2628. $langs->load('errors');
  2629. $error = 0;
  2630. // Set if we used free entry or predefined product
  2631. $predef = '';
  2632. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  2633. $price_ht = '';
  2634. $price_ht_devise = '';
  2635. $price_ttc = '';
  2636. $price_ttc_devise = '';
  2637. if (GETPOST('price_ht') !== '') {
  2638. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  2639. }
  2640. if (GETPOST('multicurrency_price_ht') !== '') {
  2641. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  2642. }
  2643. if (GETPOST('price_ttc') !== '') {
  2644. $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
  2645. }
  2646. if (GETPOST('multicurrency_price_ttc') !== '') {
  2647. $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
  2648. }
  2649. $prod_entry_mode = GETPOST('prod_entry_mode', 'aZ09');
  2650. if ($prod_entry_mode == 'free') {
  2651. $idprod = 0;
  2652. $tva_tx = (GETPOSTISSET('tva_tx') ? GETPOST('tva_tx', 'alpha') : 0);
  2653. } else {
  2654. $idprod = GETPOST('idprod', 'int');
  2655. $tva_tx = '';
  2656. }
  2657. $qty = price2num(GETPOST('qty' . $predef, 'alpha'), 'MS', 2);
  2658. $remise_percent = (GETPOSTISSET('remise_percent' . $predef) ? price2num(GETPOST('remise_percent' . $predef, 'alpha'), '', 2) : 0);
  2659. if (empty($remise_percent)) {
  2660. $remise_percent = 0;
  2661. }
  2662. // Extrafields
  2663. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  2664. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  2665. // Unset extrafield
  2666. if (is_array($extralabelsline)) {
  2667. // Get extra fields
  2668. foreach ($extralabelsline as $key => $value) {
  2669. unset($_POST["options_" . $key . $predef]);
  2670. }
  2671. }
  2672. if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
  2673. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  2674. $error++;
  2675. }
  2676. if (!$prod_entry_mode) {
  2677. if (GETPOST('type') < 0 && !GETPOST('search_idprod')) {
  2678. setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors');
  2679. $error++;
  2680. }
  2681. }
  2682. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
  2683. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  2684. $error++;
  2685. }
  2686. if (($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && (($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $price_ht == '') && $price_ht_devise == '') && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) { // Unit price can be 0 but not ''
  2687. if (($price_ht < 0 || $price_ttc < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  2688. $langs->load("errors");
  2689. if ($object->type == $object::TYPE_DEPOSIT) {
  2690. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  2691. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  2692. } else {
  2693. setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
  2694. }
  2695. $error++;
  2696. } else {
  2697. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  2698. $error++;
  2699. }
  2700. }
  2701. if ($qty == '') {
  2702. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  2703. $error++;
  2704. }
  2705. if ($prod_entry_mode == 'free' && empty($idprod) && empty($product_desc)) {
  2706. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  2707. $error++;
  2708. }
  2709. if ($qty < 0) {
  2710. $langs->load("errors");
  2711. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  2712. $error++;
  2713. }
  2714. if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
  2715. if ($combinations = GETPOST('combinations', 'array')) {
  2716. //Check if there is a product with the given combination
  2717. $prodcomb = new ProductCombination($db);
  2718. if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
  2719. $idprod = $res->fk_product_child;
  2720. } else {
  2721. setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
  2722. $error++;
  2723. }
  2724. }
  2725. }
  2726. if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
  2727. $ret = $object->fetch($id);
  2728. if ($ret < 0) {
  2729. dol_print_error($db, $object->error);
  2730. exit();
  2731. }
  2732. $ret = $object->fetch_thirdparty();
  2733. // Clean parameters
  2734. $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'));
  2735. $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'));
  2736. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  2737. // Define special_code for special lines
  2738. $special_code = 0;
  2739. // if (!GETPOST(qty)) $special_code=3; // Options should not exists on invoices
  2740. // Ecrase $pu par celui du produit
  2741. // Ecrase $desc par celui du produit
  2742. // Ecrase $tva_tx par celui du produit
  2743. // Ecrase $base_price_type par celui du produit
  2744. // Replaces $fk_unit with the product's
  2745. if (!empty($idprod) && $idprod > 0) {
  2746. $prod = new Product($db);
  2747. $prod->fetch($idprod);
  2748. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  2749. // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
  2750. $pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0);
  2751. $datapriceofproduct = $prod->getSellPrice($mysoc, $object->thirdparty, $pqp);
  2752. $pu_ht = $datapriceofproduct['pu_ht'];
  2753. $pu_ttc = $datapriceofproduct['pu_ttc'];
  2754. $price_min = $datapriceofproduct['price_min'];
  2755. $price_min_ttc = (isset($datapriceofproduct['price_min_ttc'])) ? $datapriceofproduct['price_min_ttc'] : null;
  2756. $price_base_type = $datapriceofproduct['price_base_type'];
  2757. $tva_tx = $datapriceofproduct['tva_tx'];
  2758. $tva_npr = $datapriceofproduct['tva_npr'];
  2759. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  2760. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  2761. // Set unit price to use
  2762. if (!empty($price_ht) || $price_ht === '0') {
  2763. $pu_ht = price2num($price_ht, 'MU');
  2764. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  2765. } elseif (!empty($price_ttc) || $price_ttc === '0') {
  2766. $pu_ttc = price2num($price_ttc, 'MU');
  2767. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  2768. } elseif ($tmpvat != $tmpprodvat) {
  2769. // Is this still used ?
  2770. if ($price_base_type != 'HT') {
  2771. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  2772. } else {
  2773. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  2774. }
  2775. }
  2776. $desc = '';
  2777. // Define output language
  2778. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2779. $outputlangs = $langs;
  2780. $newlang = '';
  2781. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  2782. $newlang = GETPOST('lang_id', 'aZ09');
  2783. }
  2784. if (empty($newlang)) {
  2785. $newlang = $object->thirdparty->default_lang;
  2786. }
  2787. if (!empty($newlang)) {
  2788. $outputlangs = new Translate("", $conf);
  2789. $outputlangs->setDefaultLang($newlang);
  2790. $outputlangs->load('products');
  2791. }
  2792. $desc = (!empty($prod->multilangs[$outputlangs->defaultlang]["description"])) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description;
  2793. } else {
  2794. $desc = $prod->description;
  2795. }
  2796. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  2797. if ($product_desc == $desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  2798. $product_desc = '';
  2799. }
  2800. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  2801. $desc = $product_desc;
  2802. } else {
  2803. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  2804. }
  2805. // Add custom code and origin country into description
  2806. if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
  2807. $tmptxt = '(';
  2808. // Define output language
  2809. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2810. $outputlangs = $langs;
  2811. $newlang = '';
  2812. if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
  2813. $newlang = GETPOST('lang_id', 'alpha');
  2814. }
  2815. if (empty($newlang)) {
  2816. $newlang = $object->thirdparty->default_lang;
  2817. }
  2818. if (!empty($newlang)) {
  2819. $outputlangs = new Translate("", $conf);
  2820. $outputlangs->setDefaultLang($newlang);
  2821. $outputlangs->load('products');
  2822. }
  2823. if (!empty($prod->customcode)) {
  2824. $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
  2825. }
  2826. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  2827. $tmptxt .= ' - ';
  2828. }
  2829. if (!empty($prod->country_code)) {
  2830. $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $outputlangs, 0);
  2831. }
  2832. } else {
  2833. if (!empty($prod->customcode)) {
  2834. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
  2835. }
  2836. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  2837. $tmptxt .= ' - ';
  2838. }
  2839. if (!empty($prod->country_code)) {
  2840. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0);
  2841. }
  2842. }
  2843. $tmptxt .= ')';
  2844. $desc = dol_concatdesc($desc, $tmptxt);
  2845. }
  2846. $type = $prod->type;
  2847. $fk_unit = $prod->fk_unit;
  2848. } else {
  2849. $pu_ht = price2num($price_ht, 'MU');
  2850. $pu_ttc = price2num($price_ttc, 'MU');
  2851. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  2852. $tva_tx = str_replace('*', '', $tva_tx);
  2853. if (empty($tva_tx)) {
  2854. $tva_npr = 0;
  2855. }
  2856. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  2857. $desc = $product_desc;
  2858. $type = GETPOST('type');
  2859. $fk_unit = GETPOST('units', 'alpha');
  2860. $pu_ht_devise = price2num($price_ht_devise, 'MU');
  2861. $pu_ttc_devise = price2num($price_ttc_devise, 'MU');
  2862. if ($pu_ttc && !$pu_ht) {
  2863. $price_base_type = 'TTC';
  2864. }
  2865. }
  2866. $pu_ht_devise = price2num($price_ht_devise, 'MU');
  2867. // Margin
  2868. $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : '');
  2869. $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value
  2870. // Local Taxes
  2871. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  2872. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  2873. $info_bits = 0;
  2874. if ($tva_npr) {
  2875. $info_bits |= 0x01;
  2876. }
  2877. $price2num_pu_ht = price2num($pu_ht);
  2878. $price2num_remise_percent = price2num($remise_percent);
  2879. $price2num_price_min = price2num($price_min);
  2880. $price2num_price_min_ttc = price2num($price_min_ttc);
  2881. if (empty($price2num_pu_ht)) {
  2882. $price2num_pu_ht = 0;
  2883. }
  2884. if (empty($price2num_remise_percent)) {
  2885. $price2num_remise_percent = 0;
  2886. }
  2887. if (empty($price2num_price_min)) {
  2888. $price2num_price_min = 0;
  2889. }
  2890. if (empty($price2num_price_min_ttc)) {
  2891. $price2num_price_min_ttc = 0;
  2892. }
  2893. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  2894. if ($usermustrespectpricemin && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)) {
  2895. if ($pu_ht && $price_min && ((price2num($pu_ht) * (1 - $remise_percent / 100)) < price2num($price_min))) {
  2896. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  2897. setEventMessages($mesg, null, 'errors');
  2898. $error++;
  2899. } elseif ($pu_ttc && $price_min_ttc && ((price2num($pu_ttc) * (1 - $remise_percent / 100)) < price2num($price_min_ttc))) {
  2900. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  2901. setEventMessages($mesg, null, 'errors');
  2902. $error++;
  2903. }
  2904. }
  2905. if (!$error) {
  2906. // Add batchinfo if the detail_batch array is defined
  2907. if (isModEnabled('productbatch') && !empty($lines[$i]->detail_batch) && is_array($lines[$i]->detail_batch) && !empty($conf->global->INVOICE_INCUDE_DETAILS_OF_LOTS_SERIALS)) {
  2908. $langs->load('productbatch');
  2909. foreach ($lines[$i]->detail_batch as $batchline) {
  2910. $desc .= ' ' . $langs->trans('Batch') . ' ' . $batchline->batch . ' ' . $langs->trans('printQty', $batchline->qty) . ' ';
  2911. }
  2912. }
  2913. // Insert line
  2914. $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, min($rank, count($object->lines) + 1), $special_code, '', 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, GETPOST('progress'), '', $fk_unit, $pu_ht_devise);
  2915. if ($result > 0) {
  2916. // Define output language and generate document
  2917. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  2918. $outputlangs = $langs;
  2919. $newlang = '';
  2920. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  2921. $newlang = GETPOST('lang_id', 'aZ09');
  2922. }
  2923. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  2924. $newlang = $object->thirdparty->default_lang;
  2925. }
  2926. if (!empty($newlang)) {
  2927. $outputlangs = new Translate("", $conf);
  2928. $outputlangs->setDefaultLang($newlang);
  2929. $outputlangs->load('products');
  2930. }
  2931. $model = $object->model_pdf;
  2932. $ret = $object->fetch($id); // Reload to get new records
  2933. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  2934. if ($result < 0) {
  2935. setEventMessages($object->error, $object->errors, 'errors');
  2936. }
  2937. }
  2938. unset($_POST['prod_entry_mode']);
  2939. unset($_POST['qty']);
  2940. unset($_POST['type']);
  2941. unset($_POST['remise_percent']);
  2942. unset($_POST['price_ht']);
  2943. unset($_POST['multicurrency_price_ht']);
  2944. unset($_POST['price_ttc']);
  2945. unset($_POST['tva_tx']);
  2946. unset($_POST['product_ref']);
  2947. unset($_POST['product_label']);
  2948. unset($_POST['product_desc']);
  2949. unset($_POST['fournprice']);
  2950. unset($_POST['buying_price']);
  2951. unset($_POST['np_marginRate']);
  2952. unset($_POST['np_markRate']);
  2953. unset($_POST['dp_desc']);
  2954. unset($_POST['idprod']);
  2955. unset($_POST['units']);
  2956. unset($_POST['date_starthour']);
  2957. unset($_POST['date_startmin']);
  2958. unset($_POST['date_startsec']);
  2959. unset($_POST['date_startday']);
  2960. unset($_POST['date_startmonth']);
  2961. unset($_POST['date_startyear']);
  2962. unset($_POST['date_endhour']);
  2963. unset($_POST['date_endmin']);
  2964. unset($_POST['date_endsec']);
  2965. unset($_POST['date_endday']);
  2966. unset($_POST['date_endmonth']);
  2967. unset($_POST['date_endyear']);
  2968. unset($_POST['situations']);
  2969. unset($_POST['progress']);
  2970. } else {
  2971. setEventMessages($object->error, $object->errors, 'errors');
  2972. }
  2973. $action = '';
  2974. }
  2975. }
  2976. } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) {
  2977. if (!$object->fetch($id) > 0) {
  2978. dol_print_error($db);
  2979. }
  2980. $object->fetch_thirdparty();
  2981. // Clean parameters
  2982. $date_start = '';
  2983. $date_end = '';
  2984. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  2985. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  2986. $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml'));
  2987. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  2988. $vat_rate = str_replace('*', '', $vat_rate);
  2989. $pu_ht = price2num(GETPOST('price_ht'), '', 2);
  2990. $pu_ttc = price2num(GETPOST('price_ttc'), '', 2);
  2991. $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
  2992. $pu_ttc_devise = price2num(GETPOST('multicurrency_subprice_ttc'), '', 2);
  2993. $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
  2994. // Define info_bits
  2995. $info_bits = 0;
  2996. if (preg_match('/\*/', $vat_rate)) {
  2997. $info_bits |= 0x01;
  2998. }
  2999. // Define vat_rate
  3000. $vat_rate = str_replace('*', '', $vat_rate);
  3001. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
  3002. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
  3003. // Add buying price
  3004. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  3005. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  3006. // Extrafields
  3007. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  3008. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  3009. // Unset extrafield
  3010. if (is_array($extralabelsline)) {
  3011. // Get extra fields
  3012. foreach ($extralabelsline as $key => $value) {
  3013. unset($_POST["options_" . $key]);
  3014. }
  3015. }
  3016. // Define special_code for special lines
  3017. $special_code = GETPOST('special_code', 'int');
  3018. if ($special_code == 3) {
  3019. $special_code = 0; // Options should not exists on invoices
  3020. }
  3021. $line = new FactureLigne($db);
  3022. $line->fetch(GETPOST('lineid', 'int'));
  3023. $percent = $line->get_prev_progress($object->id);
  3024. $progress = price2num(GETPOST('progress', 'alpha'));
  3025. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref > 0) {
  3026. // in case of situation credit note
  3027. if ($progress >= 0) {
  3028. $mesg = $langs->trans("CantBeNullOrPositive");
  3029. setEventMessages($mesg, null, 'warnings');
  3030. $error++;
  3031. $result = -1;
  3032. } elseif ($progress < $line->situation_percent) { // TODO : use a modified $line->get_prev_progress($object->id) result
  3033. $mesg = $langs->trans("CantBeLessThanMinPercent");
  3034. setEventMessages($mesg, null, 'warnings');
  3035. $error++;
  3036. $result = -1;
  3037. } elseif ($progress < $percent) {
  3038. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  3039. setEventMessages($mesg, null, 'warnings');
  3040. $error++;
  3041. $result = -1;
  3042. }
  3043. }
  3044. if ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->situation_cycle_ref > 0) {
  3045. // in case of situation credit note
  3046. if ($progress >= 0) {
  3047. $mesg = $langs->trans("CantBeNullOrPositive");
  3048. setEventMessages($mesg, null, 'warnings');
  3049. $error++;
  3050. $result = -1;
  3051. } elseif ($progress < $line->situation_percent) { // TODO : use a modified $line->get_prev_progress($object->id) result
  3052. $mesg = $langs->trans("CantBeLessThanMinPercent");
  3053. setEventMessages($mesg, null, 'warnings');
  3054. $error++;
  3055. $result = -1;
  3056. } elseif ($progress < $percent) {
  3057. $mesg = '<div class="warning">' . $langs->trans("CantBeLessThanMinPercent") . '</div>';
  3058. setEventMessages($mesg, null, 'warnings');
  3059. $error++;
  3060. $result = -1;
  3061. }
  3062. }
  3063. $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  3064. // Check minimum price
  3065. $productid = GETPOST('productid', 'int');
  3066. if (!empty($productid)) {
  3067. $product = new Product($db);
  3068. $product->fetch($productid);
  3069. $type = $product->type;
  3070. $price_min = $product->price_min;
  3071. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
  3072. $price_min = $product->multiprices_min[$object->thirdparty->price_level];
  3073. }
  3074. $price_min_ttc = $product->price_min_ttc;
  3075. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
  3076. $price_min_ttc = $product->multiprices_min_ttc[$object->thirdparty->price_level];
  3077. }
  3078. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  3079. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  3080. if ($usermustrespectpricemin && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_RECEIPT)) {
  3081. if ($pu_ht && $price_min && (((float) price2num($pu_ht) * (1 - (float) $remise_percent / 100)) < (float) price2num($price_min))) {
  3082. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  3083. setEventMessages($mesg, null, 'errors');
  3084. $error++;
  3085. $action = 'editline';
  3086. } elseif ($pu_ttc && $price_min_ttc && ((price2num($pu_ttc) * (1 - (float) $remise_percent / 100)) < price2num($price_min_ttc))) {
  3087. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  3088. setEventMessages($mesg, null, 'errors');
  3089. $error++;
  3090. $action = 'editline';
  3091. }
  3092. }
  3093. } else {
  3094. $type = GETPOST('type');
  3095. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  3096. // Check parameters
  3097. if (GETPOST('type') < 0) {
  3098. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  3099. $error++;
  3100. }
  3101. }
  3102. if ($qty < 0) {
  3103. $langs->load("errors");
  3104. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  3105. $error++;
  3106. }
  3107. if (empty($productid) && (($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht == '') && (($pu_ht_devise < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht_devise == '') && $pu_ttc === '' && $pu_ttc_devise === '' && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) { // Unit price can be 0 but not ''
  3108. if (($pu_ht < 0 || $pu_ttc < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  3109. $langs->load("errors");
  3110. if ($object->type == $object::TYPE_DEPOSIT) {
  3111. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  3112. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  3113. } else {
  3114. setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
  3115. }
  3116. $error++;
  3117. } else {
  3118. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  3119. $error++;
  3120. }
  3121. }
  3122. // Update line
  3123. if (!$error) {
  3124. if (empty($usercancreatemargin)) {
  3125. foreach ($object->lines as &$line) {
  3126. if ($line->id == GETPOST('lineid', 'int')) {
  3127. $fournprice = $line->fk_fournprice;
  3128. $buyingprice = $line->pa_ht;
  3129. break;
  3130. }
  3131. }
  3132. }
  3133. $price_base_type = 'HT';
  3134. $pu = $pu_ht;
  3135. if (empty($pu) && !empty($pu_ttc)) {
  3136. $pu = $pu_ttc;
  3137. $price_base_type = 'TTC';
  3138. }
  3139. $result = $object->updateline(
  3140. GETPOST('lineid', 'int'),
  3141. $description,
  3142. $pu,
  3143. $qty,
  3144. $remise_percent,
  3145. $date_start,
  3146. $date_end,
  3147. $vat_rate,
  3148. $localtax1_rate,
  3149. $localtax2_rate,
  3150. $price_base_type,
  3151. $info_bits,
  3152. $type,
  3153. GETPOST('fk_parent_line', 'int'),
  3154. 0,
  3155. $fournprice,
  3156. $buyingprice,
  3157. $label,
  3158. $special_code,
  3159. $array_options,
  3160. price2num(GETPOST('progress', 'alpha')),
  3161. GETPOST('units', 'alpha'),
  3162. $pu_ht_devise
  3163. );
  3164. if ($result >= 0) {
  3165. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  3166. // Define output language
  3167. $outputlangs = $langs;
  3168. $newlang = '';
  3169. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  3170. $newlang = GETPOST('lang_id', 'aZ09');
  3171. }
  3172. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  3173. $newlang = $object->thirdparty->default_lang;
  3174. }
  3175. if (!empty($newlang)) {
  3176. $outputlangs = new Translate("", $conf);
  3177. $outputlangs->setDefaultLang($newlang);
  3178. $outputlangs->load('products');
  3179. }
  3180. $ret = $object->fetch($id); // Reload to get new records
  3181. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  3182. }
  3183. unset($_POST['qty']);
  3184. unset($_POST['type']);
  3185. unset($_POST['productid']);
  3186. unset($_POST['remise_percent']);
  3187. unset($_POST['price_ht']);
  3188. unset($_POST['multicurrency_price_ht']);
  3189. unset($_POST['price_ttc']);
  3190. unset($_POST['tva_tx']);
  3191. unset($_POST['product_ref']);
  3192. unset($_POST['product_label']);
  3193. unset($_POST['product_desc']);
  3194. unset($_POST['fournprice']);
  3195. unset($_POST['buying_price']);
  3196. unset($_POST['np_marginRate']);
  3197. unset($_POST['np_markRate']);
  3198. unset($_POST['dp_desc']);
  3199. unset($_POST['idprod']);
  3200. unset($_POST['units']);
  3201. unset($_POST['date_starthour']);
  3202. unset($_POST['date_startmin']);
  3203. unset($_POST['date_startsec']);
  3204. unset($_POST['date_startday']);
  3205. unset($_POST['date_startmonth']);
  3206. unset($_POST['date_startyear']);
  3207. unset($_POST['date_endhour']);
  3208. unset($_POST['date_endmin']);
  3209. unset($_POST['date_endsec']);
  3210. unset($_POST['date_endday']);
  3211. unset($_POST['date_endmonth']);
  3212. unset($_POST['date_endyear']);
  3213. unset($_POST['situations']);
  3214. unset($_POST['progress']);
  3215. } else {
  3216. setEventMessages($object->error, $object->errors, 'errors');
  3217. }
  3218. }
  3219. } elseif ($action == 'updatealllines' && $usercancreate && GETPOST('all_percent') == $langs->trans('Modifier')) { // Update all lines of situation invoice
  3220. if (!$object->fetch($id) > 0) {
  3221. dol_print_error($db);
  3222. }
  3223. if (GETPOST('all_progress') != "") {
  3224. $all_progress = GETPOST('all_progress', 'int');
  3225. foreach ($object->lines as $line) {
  3226. $percent = $line->get_prev_progress($object->id);
  3227. if (floatval($all_progress) < floatval($percent)) {
  3228. $mesg = $langs->trans("Line") . ' ' . $i . ' : ' . $langs->trans("CantBeLessThanMinPercent");
  3229. setEventMessages($mesg, null, 'warnings');
  3230. $result = -1;
  3231. } else {
  3232. $object->update_percent($line, GETPOST('all_progress'), false);
  3233. }
  3234. }
  3235. $object->update_price(1);
  3236. }
  3237. } elseif ($action == 'updateline' && $usercancreate && !$cancel) {
  3238. header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); // To show again edited page
  3239. exit();
  3240. } elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $usercancreate) {
  3241. // Outing situation invoice from cycle
  3242. $object->fetch($id, '', '', '', true);
  3243. if (
  3244. in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  3245. && $object->type == Facture::TYPE_SITUATION
  3246. && $usercancreate
  3247. && !$objectidnext
  3248. && $object->is_last_in_cycle()
  3249. && $usercanunvalidate
  3250. ) {
  3251. $outingError = 0;
  3252. $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle
  3253. if ($newCycle > 1) {
  3254. // Search credit notes
  3255. $lastCycle = $object->situation_cycle_ref;
  3256. $lastSituationCounter = $object->situation_counter;
  3257. $linkedCreditNotesList = array();
  3258. if (count($object->tab_next_situation_invoice) > 0) {
  3259. foreach ($object->tab_next_situation_invoice as $next_invoice) {
  3260. if (
  3261. ($next_invoice->type == Facture::TYPE_CREDIT_NOTE || $next_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE)
  3262. && $next_invoice->situation_counter == $object->situation_counter
  3263. && $next_invoice->fk_facture_source == $object->id
  3264. ) {
  3265. $linkedCreditNotesList[] = $next_invoice->id;
  3266. }
  3267. }
  3268. }
  3269. $object->situation_cycle_ref = $newCycle;
  3270. $object->situation_counter = 1;
  3271. $object->situation_final = 0;
  3272. if ($object->update($user) > 0) {
  3273. $errors = 0;
  3274. if (count($linkedCreditNotesList) > 0) {
  3275. // now, credit note must follow
  3276. $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'facture';
  3277. $sql .= ' SET situation_cycle_ref = ' . ((int) $newCycle);
  3278. $sql .= ' , situation_final=0';
  3279. $sql .= ' , situation_counter=' . ((int) $object->situation_counter);
  3280. $sql .= ' WHERE rowid IN (' . $db->sanitize(implode(',', $linkedCreditNotesList)) . ')';
  3281. $resql = $db->query($sql);
  3282. if (!$resql) {
  3283. $errors++;
  3284. }
  3285. // Change each progression persent on each lines
  3286. foreach ($object->lines as $line) {
  3287. // no traitement for special product
  3288. if ($line->product_type == 9) {
  3289. continue;
  3290. }
  3291. if (!empty($object->tab_previous_situation_invoice)) {
  3292. // search the last invoice in cycle
  3293. $lineIndex = count($object->tab_previous_situation_invoice) - 1;
  3294. $searchPreviousInvoice = true;
  3295. while ($searchPreviousInvoice) {
  3296. if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  3297. $searchPreviousInvoice = false; // find, exit;
  3298. break;
  3299. } else {
  3300. $lineIndex--; // go to previous invoice in cycle
  3301. }
  3302. }
  3303. $maxPrevSituationPercent = 0;
  3304. foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  3305. if ($prevLine->id == $line->fk_prev_id) {
  3306. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  3307. }
  3308. }
  3309. $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent;
  3310. if ($line->update() < 0) {
  3311. $errors++;
  3312. }
  3313. }
  3314. }
  3315. }
  3316. if (!$errors) {
  3317. setEventMessages($langs->trans('Updated'), '', 'mesgs');
  3318. header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
  3319. } else {
  3320. setEventMessages($langs->trans('ErrorOutingSituationInvoiceCreditNote'), array(), 'errors');
  3321. }
  3322. } else {
  3323. setEventMessages($langs->trans('ErrorOutingSituationInvoiceOnUpdate'), array(), 'errors');
  3324. }
  3325. } else {
  3326. setEventMessages($langs->trans('ErrorFindNextSituationInvoice'), array(), 'errors');
  3327. }
  3328. }
  3329. } elseif (
  3330. $action == 'import_lines_from_object'
  3331. && $usercancreate
  3332. && $object->statut == Facture::STATUS_DRAFT
  3333. && ($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 || $object->type == Facture::TYPE_RECEIPT)
  3334. ) {
  3335. // add lines from objectlinked
  3336. $fromElement = GETPOST('fromelement');
  3337. $fromElementid = GETPOST('fromelementid');
  3338. $importLines = GETPOST('line_checkbox');
  3339. if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
  3340. if ($fromElement == 'commande') {
  3341. dol_include_once('/' . $fromElement . '/class/' . $fromElement . '.class.php');
  3342. $lineClassName = 'OrderLine';
  3343. } elseif ($fromElement == 'propal') {
  3344. dol_include_once('/comm/' . $fromElement . '/class/' . $fromElement . '.class.php');
  3345. $lineClassName = 'PropaleLigne';
  3346. }
  3347. $nextRang = count($object->lines) + 1;
  3348. $importCount = 0;
  3349. $error = 0;
  3350. foreach ($importLines as $lineId) {
  3351. $lineId = intval($lineId);
  3352. $originLine = new $lineClassName($db);
  3353. if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
  3354. $originLine->fetch_optionals();
  3355. $desc = $originLine->desc;
  3356. $pu_ht = $originLine->subprice;
  3357. $qty = $originLine->qty;
  3358. $txtva = $originLine->tva_tx;
  3359. $txlocaltax1 = $originLine->localtax1_tx;
  3360. $txlocaltax2 = $originLine->localtax2_tx;
  3361. $fk_product = $originLine->fk_product;
  3362. $remise_percent = $originLine->remise_percent;
  3363. $date_start = $originLine->date_start;
  3364. $date_end = $originLine->date_end;
  3365. $ventil = 0;
  3366. $info_bits = $originLine->info_bits;
  3367. $fk_remise_except = $originLine->fk_remise_except;
  3368. $price_base_type = 'HT';
  3369. $pu_ttc = 0;
  3370. $type = $originLine->product_type;
  3371. $rang = $nextRang++;
  3372. $special_code = $originLine->special_code;
  3373. $origin = $originLine->element;
  3374. $origin_id = $originLine->id;
  3375. $fk_parent_line = 0;
  3376. $fk_fournprice = $originLine->fk_fournprice;
  3377. $pa_ht = $originLine->pa_ht;
  3378. $label = $originLine->label;
  3379. $array_options = $originLine->array_options;
  3380. if ($object->type == Facture::TYPE_SITUATION) {
  3381. $situation_percent = 0;
  3382. } else {
  3383. $situation_percent = 100;
  3384. }
  3385. $fk_prev_id = '';
  3386. $fk_unit = $originLine->fk_unit;
  3387. $pu_ht_devise = $originLine->multicurrency_subprice;
  3388. $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $ventil, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $type, $rang, $special_code, $origin, $origin_id, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $situation_percent, $fk_prev_id, $fk_unit, $pu_ht_devise);
  3389. if ($res > 0) {
  3390. $importCount++;
  3391. } else {
  3392. $error++;
  3393. }
  3394. } else {
  3395. $error++;
  3396. }
  3397. }
  3398. if ($error) {
  3399. setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
  3400. }
  3401. }
  3402. }
  3403. // Actions when printing a doc from card
  3404. include DOL_DOCUMENT_ROOT . '/core/actions_printing.inc.php';
  3405. // Actions to send emails
  3406. if (empty($id)) {
  3407. $id = $facid;
  3408. }
  3409. $triggersendname = 'BILL_SENTBYMAIL';
  3410. $paramname = 'id';
  3411. $autocopy = 'MAIN_MAIL_AUTOCOPY_INVOICE_TO';
  3412. $trackid = 'inv' . $object->id;
  3413. include DOL_DOCUMENT_ROOT . '/core/actions_sendmails.inc.php';
  3414. // Actions to build doc
  3415. $upload_dir = $conf->facture->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity];
  3416. $permissiontoadd = $usercancreate;
  3417. include DOL_DOCUMENT_ROOT . '/core/actions_builddoc.inc.php';
  3418. if ($action == 'update_extras') {
  3419. $object->oldcopy = dol_clone($object);
  3420. // Fill array 'array_options' with data from add form
  3421. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  3422. if ($ret < 0) {
  3423. $error++;
  3424. }
  3425. if (!$error) {
  3426. // Actions on extra fields
  3427. $result = $object->insertExtraFields('BILL_MODIFY');
  3428. if ($result < 0) {
  3429. setEventMessages($object->error, $object->errors, 'errors');
  3430. $error++;
  3431. }
  3432. }
  3433. if ($error) {
  3434. $action = 'edit_extras';
  3435. }
  3436. }
  3437. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
  3438. if ($action == 'addcontact') {
  3439. $result = $object->fetch($id);
  3440. if ($result > 0 && $id > 0) {
  3441. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  3442. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  3443. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  3444. }
  3445. if ($result >= 0) {
  3446. header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
  3447. exit();
  3448. } else {
  3449. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  3450. $langs->load("errors");
  3451. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  3452. } else {
  3453. setEventMessages($object->error, $object->errors, 'errors');
  3454. }
  3455. }
  3456. } elseif ($action == 'swapstatut') {
  3457. // bascule du statut d'un contact
  3458. if ($object->fetch($id)) {
  3459. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  3460. } else {
  3461. dol_print_error($db);
  3462. }
  3463. } elseif ($action == 'deletecontact') {
  3464. // Efface un contact
  3465. $object->fetch($id);
  3466. $result = $object->delete_contact($lineid);
  3467. if ($result >= 0) {
  3468. header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
  3469. exit();
  3470. } else {
  3471. dol_print_error($db);
  3472. }
  3473. }
  3474. if ($error) {
  3475. $action = 'edit_extras';
  3476. }
  3477. }
  3478. }
  3479. /*
  3480. * View
  3481. */
  3482. $form = new Form($db);
  3483. $formother = new FormOther($db);
  3484. $formfile = new FormFile($db);
  3485. $formmargin = new FormMargin($db);
  3486. $soc = new Societe($db);
  3487. $paymentstatic = new Paiement($db);
  3488. $bankaccountstatic = new Account($db);
  3489. if (isModEnabled('project')) {
  3490. $formproject = new FormProjets($db);
  3491. }
  3492. $now = dol_now();
  3493. $title = $object->ref . " - " . $langs->trans('Card');
  3494. if ($action == 'create') {
  3495. $title = $langs->trans("NewBill");
  3496. }
  3497. $help_url = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
  3498. llxHeader('', $title, $help_url);
  3499. // Mode creation
  3500. if ($action == 'create') {
  3501. $facturestatic = new Facture($db);
  3502. $extrafields->fetch_name_optionals_label($facturestatic->table_element);
  3503. print load_fiche_titre($langs->trans('NewBill'), '', 'bill');
  3504. if ($socid > 0 && !$customerchange) {
  3505. $res = $soc->fetch($socid);
  3506. }
  3507. $currency_code = $conf->currency;
  3508. $fk_account = 0;
  3509. // Load objectsrc
  3510. $remise_absolue = 0;
  3511. if (!empty($origin) && !empty($originid)) {
  3512. // Parse element/subelement (ex: project_task)
  3513. $element = $subelement = $origin;
  3514. $regs = array();
  3515. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  3516. $element = $regs[1];
  3517. $subelement = $regs[2];
  3518. }
  3519. if ($element == 'project') {
  3520. $projectid = $originid;
  3521. if (empty($cond_reglement_id)) {
  3522. $cond_reglement_id = $soc->cond_reglement_id;
  3523. }
  3524. if (empty($mode_reglement_id)) {
  3525. $mode_reglement_id = $soc->mode_reglement_id;
  3526. }
  3527. if (empty($fk_account)) {
  3528. $fk_account = $soc->fk_account;
  3529. }
  3530. if (!$remise_percent) {
  3531. $remise_percent = $soc->remise_percent;
  3532. }
  3533. if (!$dateinvoice) {
  3534. // Do not set 0 here (0 for a date is 1970)
  3535. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ? -1 : '') : $dateinvoice);
  3536. }
  3537. } else {
  3538. // For compatibility
  3539. if ($element == 'order' || $element == 'commande') {
  3540. $element = $subelement = 'commande';
  3541. }
  3542. if ($element == 'propal') {
  3543. $element = 'comm/propal';
  3544. $subelement = 'propal';
  3545. }
  3546. if ($element == 'contract') {
  3547. $element = $subelement = 'contrat';
  3548. }
  3549. if ($element == 'shipping') {
  3550. $element = $subelement = 'expedition';
  3551. }
  3552. dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
  3553. $classname = ucfirst($subelement);
  3554. $objectsrc = new $classname($db);
  3555. $objectsrc->fetch($originid);
  3556. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
  3557. $objectsrc->fetch_lines();
  3558. }
  3559. $objectsrc->fetch_thirdparty();
  3560. $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project);
  3561. $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : ''));
  3562. // only if socid not filled else it's allready done upper
  3563. if (empty($socid)) {
  3564. $soc = $objectsrc->thirdparty;
  3565. }
  3566. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ? -1 : '') : $dateinvoice);
  3567. if ($element == 'expedition') {
  3568. $ref_client = (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : '');
  3569. $elem = $subelem = $objectsrc->origin;
  3570. $expeoriginid = $objectsrc->origin_id;
  3571. dol_include_once('/' . $elem . '/class/' . $subelem . '.class.php');
  3572. $classname = ucfirst($subelem);
  3573. $expesrc = new $classname($db);
  3574. $expesrc->fetch($expeoriginid);
  3575. $cond_reglement_id = (!empty($expesrc->cond_reglement_id) ? $expesrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 1));
  3576. $mode_reglement_id = (!empty($expesrc->mode_reglement_id) ? $expesrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
  3577. $fk_account = (!empty($expesrc->fk_account) ? $expesrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  3578. $remise_percent = (!empty($expesrc->remise_percent) ? $expesrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
  3579. $remise_absolue = (!empty($expesrc->remise_absolue) ? $expesrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  3580. if (!empty($conf->multicurrency->enabled)) {
  3581. $currency_code = (!empty($expesrc->multicurrency_code) ? $expesrc->multicurrency_code : (!empty($soc->multicurrency_code) ? $soc->multicurrency_code : $objectsrc->multicurrency_code));
  3582. $currency_tx = (!empty($expesrc->multicurrency_tx) ? $expesrc->multicurrency_tx : (!empty($soc->multicurrency_tx) ? $soc->multicurrency_tx : $objectsrc->multicurrency_tx));
  3583. }
  3584. //Replicate extrafields
  3585. $expesrc->fetch_optionals();
  3586. $object->array_options = $expesrc->array_options;
  3587. } else {
  3588. $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0));
  3589. $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
  3590. $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  3591. $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
  3592. $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  3593. if (isModEnabled('multicurrency')) {
  3594. if (!empty($objectsrc->multicurrency_code)) {
  3595. $currency_code = $objectsrc->multicurrency_code;
  3596. }
  3597. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
  3598. $currency_tx = $objectsrc->multicurrency_tx;
  3599. }
  3600. }
  3601. // Replicate extrafields
  3602. $objectsrc->fetch_optionals();
  3603. $object->array_options = $objectsrc->array_options;
  3604. }
  3605. }
  3606. } else {
  3607. $cond_reglement_id = $soc->cond_reglement_id;
  3608. $mode_reglement_id = $soc->mode_reglement_id;
  3609. $fk_account = $soc->fk_account;
  3610. $remise_percent = $soc->remise_percent;
  3611. $remise_absolue = 0;
  3612. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ? -1 : '') : $dateinvoice); // Do not set 0 here (0 for a date is 1970)
  3613. if (isModEnabled('multicurrency') && !empty($soc->multicurrency_code)) {
  3614. $currency_code = $soc->multicurrency_code;
  3615. }
  3616. }
  3617. // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
  3618. if (empty($cond_reglement_id)) {
  3619. $cond_reglement_id = GETPOST("cond_reglement_id", 'int');
  3620. }
  3621. // when payment mode is empty (means not override by payment mode form a other object, like third-party), try to use default value
  3622. if (empty($mode_reglement_id)) {
  3623. $mode_reglement_id = GETPOST("mode_reglement_id", 'int');
  3624. }
  3625. // when bank account is empty (means not override by payment mode form a other object, like third-party), try to use default value
  3626. if ($socid > 0 && $fk_account) { // A company has already been set and it has a default fk_account
  3627. $fk_account = GETPOSTISSET('fk_account') ? GETPOST("fk_account", 'int') : $fk_account; // The GETPOST is used only if form was posted to avoid to take default value, because in such case, the default must be the one of the company
  3628. } else { // No company forced
  3629. $fk_account = GETPOST("fk_account", 'int');
  3630. }
  3631. if (!empty($soc->id)) {
  3632. $absolute_discount = $soc->getAvailableDiscounts();
  3633. }
  3634. $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null));
  3635. $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null));
  3636. if (!empty($conf->use_javascript_ajax)) {
  3637. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3638. print ajax_combobox('fac_replacement');
  3639. print ajax_combobox('fac_avoir');
  3640. print ajax_combobox('situations');
  3641. }
  3642. if ($origin == 'contrat') {
  3643. $langs->load("admin");
  3644. $text = $langs->trans("ToCreateARecurringInvoice");
  3645. $text .= ' ' . $langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates"));
  3646. if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) {
  3647. $text .= ' ' . $langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
  3648. }
  3649. print info_admin($text, 0, 0, 0, 'opacitymedium') . '<br>';
  3650. }
  3651. print '<form name="add" action="' . $_SERVER["PHP_SELF"] . '" method="POST" id="formtocreate" name="formtocreate">';
  3652. print '<input type="hidden" name="token" value="' . newToken() . '">';
  3653. print '<input type="hidden" name="action" id="formtocreateaction" value="add">';
  3654. if ($soc->id > 0) {
  3655. print '<input type="hidden" name="socid" value="' . $soc->id . '">' . "\n";
  3656. }
  3657. if ($customerchange) {
  3658. print '<input type="hidden" name="customerchange" value="' . $customerchange . '">' . "\n";
  3659. }
  3660. print '<input name="ref" type="hidden" value="provisoire">';
  3661. print '<input name="ref_client" type="hidden" value="' . $ref_client . '">';
  3662. print '<input name="force_cond_reglement_id" type="hidden" value="0">';
  3663. print '<input name="force_mode_reglement_id" type="hidden" value="0">';
  3664. print '<input name="force_fk_account" type="hidden" value="0">';
  3665. print '<input type="hidden" name="origin" value="' . $origin . '">';
  3666. print '<input type="hidden" name="originid" value="' . $originid . '">';
  3667. print '<input type="hidden" name="originentity" value="' . GETPOST('originentity') . '">';
  3668. if (!empty($currency_tx)) {
  3669. print '<input type="hidden" name="originmulticurrency_tx" value="' . $currency_tx . '">';
  3670. }
  3671. print dol_get_fiche_head('');
  3672. print '<table class="border centpercent">';
  3673. // Ref
  3674. //print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$langs->trans('Draft').'</td></tr>';
  3675. $exampletemplateinvoice = new FactureRec($db);
  3676. $invoice_predefined = new FactureRec($db);
  3677. if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) {
  3678. $invoice_predefined->fetch(GETPOST('fac_rec', 'int'));
  3679. }
  3680. // Thirdparty
  3681. if ($soc->id > 0 && (!GETPOST('fac_rec', 'int') || !empty($invoice_predefined->frequency))) {
  3682. // If thirdparty known and not a predefined invoiced without a recurring rule
  3683. print '<tr><td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
  3684. print '<td colspan="2">';
  3685. print $soc->getNomUrl(1, 'customer');
  3686. print '<input type="hidden" name="socid" value="' . $soc->id . '">';
  3687. // Outstanding Bill
  3688. $arrayoutstandingbills = $soc->getOutstandingBills();
  3689. $outstandingBills = $arrayoutstandingbills['opened'];
  3690. print ' - <span class="opacitymedium">' . $langs->trans('CurrentOutstandingBill') . ':</span> ';
  3691. print '<span class="amount">' . price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency) . '</span>';
  3692. if ($soc->outstanding_limit != '') {
  3693. if ($outstandingBills > $soc->outstanding_limit) {
  3694. print img_warning($langs->trans("OutstandingBillReached"));
  3695. }
  3696. print ' / ' . price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
  3697. }
  3698. print '</td>';
  3699. print '</tr>' . "\n";
  3700. } elseif ($customerchange) {
  3701. print '<tr><td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
  3702. print '<td colspan="2">';
  3703. print img_picto('', 'company') . $form->select_company($soc->id, 'socid', '((s.client = 1 OR s.client = 3) AND s.status = 1)', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  3704. print '</td>';
  3705. print '</tr>' . "\n";
  3706. } else {
  3707. print '<tr><td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
  3708. print '<td colspan="2">';
  3709. print img_picto('', 'company') . $form->select_company($soc->id, 'socid', '((s.client = 1 OR s.client = 3) AND s.status = 1)', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  3710. // Option to reload page to retrieve customer informations.
  3711. if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) {
  3712. print '<script type="text/javascript">
  3713. $(document).ready(function() {
  3714. $("#socid").change(function() {
  3715. /*
  3716. console.log("Submit page");
  3717. $(\'input[name="action"]\').val(\'create\');
  3718. $(\'input[name="force_cond_reglement_id"]\').val(\'1\');
  3719. $(\'input[name="force_mode_reglement_id"]\').val(\'1\');
  3720. $(\'input[name="force_fk_account"]\').val(\'1\');
  3721. $("#formtocreate").submit(); */
  3722. // For company change, we must reuse data of comany, not input already done, so we call a GET with action=create, not a POST submit.
  3723. console.log("We have changed the company - Reload page");
  3724. var socid = $(this).val();
  3725. var fac_rec = $(\'#fac_rec\').val();
  3726. window.location.href = "' . $_SERVER["PHP_SELF"] . '?action=create&socid="+socid+"&fac_rec="+fac_rec;
  3727. });
  3728. });
  3729. </script>';
  3730. }
  3731. if (!GETPOST('fac_rec', 'int')) {
  3732. print ' <a href="' . DOL_URL_ROOT . '/societe/card.php?action=create&client=3&fournisseur=0&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?action=create') . '"><span class="fa fa-plus-circle valignmiddle paddingleft" title="' . $langs->trans("AddThirdParty") . '"></span></a>';
  3733. }
  3734. print '</td>';
  3735. print '</tr>' . "\n";
  3736. }
  3737. // Overwrite some values if creation of invoice is from a predefined invoice
  3738. if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) {
  3739. $invoice_predefined->fetch(GETPOST('fac_rec', 'int'));
  3740. $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
  3741. if (empty($projectid)) {
  3742. $projectid = $invoice_predefined->fk_project;
  3743. }
  3744. $cond_reglement_id = $invoice_predefined->cond_reglement_id;
  3745. $mode_reglement_id = $invoice_predefined->mode_reglement_id;
  3746. $fk_account = $invoice_predefined->fk_account;
  3747. $note_public = $invoice_predefined->note_public;
  3748. $note_private = $invoice_predefined->note_private;
  3749. if (!empty($invoice_predefined->multicurrency_code)) {
  3750. $currency_code = $invoice_predefined->multicurrency_code;
  3751. }
  3752. if (!empty($invoice_predefined->multicurrency_tx)) {
  3753. $currency_tx = $invoice_predefined->multicurrency_tx;
  3754. }
  3755. $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc';
  3756. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as r';
  3757. $sql .= ' WHERE r.fk_soc = ' . ((int) $invoice_predefined->socid);
  3758. $resql = $db->query($sql);
  3759. if ($resql) {
  3760. $num = $db->num_rows($resql);
  3761. $i = 0;
  3762. if ($num > 0) {
  3763. print '<tr><td>' . $langs->trans('CreateFromRepeatableInvoice') . '</td><td>';
  3764. //print '<input type="hidden" name="fac_rec" id="fac_rec" value="'.GETPOST('fac_rec', 'int').'">';
  3765. print '<select class="flat" id="fac_rec" name="fac_rec">'; // We may want to change the template to use
  3766. print '<option value="0" selected></option>';
  3767. while ($i < $num) {
  3768. $objp = $db->fetch_object($resql);
  3769. print '<option value="' . $objp->rowid . '"';
  3770. if (GETPOST('fac_rec', 'int') == $objp->rowid) {
  3771. print ' selected';
  3772. $exampletemplateinvoice->fetch(GETPOST('fac_rec', 'int'));
  3773. }
  3774. print '>' . $objp->title . ' (' . price($objp->total_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  3775. $i++;
  3776. }
  3777. print '</select>';
  3778. print ajax_combobox("fac_rec");
  3779. // Option to reload page to retrieve customer informations. Note, this clear other input
  3780. if (empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED)) {
  3781. print '<script type="text/javascript">
  3782. $(document).ready(function() {
  3783. $("#fac_rec").change(function() {
  3784. console.log("We have changed the template invoice - Reload page");
  3785. var fac_rec = $(this).val();
  3786. var socid = $(\'#socid\').val();
  3787. // For template invoice change, we must reuse data of template, not input already done, so we call a GET with action=create, not a POST submit.
  3788. window.location.href = "' . $_SERVER["PHP_SELF"] . '?action=create&socid="+socid+"&fac_rec="+fac_rec;
  3789. });
  3790. });
  3791. </script>';
  3792. }
  3793. print '</td></tr>';
  3794. }
  3795. $db->free($resql);
  3796. } else {
  3797. dol_print_error($db);
  3798. }
  3799. }
  3800. print '<tr><td class="tdtop fieldrequired">' . $langs->trans('Type') . '</td><td colspan="2">';
  3801. print '<div class="tagtable">' . "\n";
  3802. // Standard invoice
  3803. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3804. $tmp = '<input type="radio" id="radio_standard" name="type" value="0"' . (GETPOST('type', 'int') ? '' : ' checked') . '> ';
  3805. $tmp = $tmp . '<label for="radio_standard" >' . $langs->trans("InvoiceStandardAsk") . '</label>';
  3806. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3, 'standardonsmartphone');
  3807. print '<table class="nobordernopadding"><tr>';
  3808. print '<td>';
  3809. print $desc;
  3810. print '</td>';
  3811. if ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid))) {
  3812. /*print '<td class="nowrap" style="padding-left: 5px">';
  3813. $arraylist = array(
  3814. //'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  3815. //'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  3816. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  3817. );
  3818. print $form->selectarray('typestandard', $arraylist, GETPOST('typestandard', 'aZ09'), 0, 0, 0, '', 1);
  3819. print '</td>';*/
  3820. print '<td class="nowrap" style="padding-left: 15px">';
  3821. print '<span class="opacitymedium">' . $langs->trans('PercentOfOriginalObject') . '</span>:<input class="right" placeholder="100%" type="text" id="valuestandardinvoice" name="valuestandardinvoice" size="3" value="' . (GETPOSTISSET('valuestandardinvoice') ? GETPOST('valuestandardinvoice', 'alpha') : '100%') . '"/>';
  3822. print '</td>';
  3823. }
  3824. print '</tr></table>';
  3825. print '</div></div>';
  3826. #########################################
  3827. # Receipt
  3828. #########################################
  3829. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3830. $tmp = '<input type="radio" id="radio_receipt" name="type" value="7")> ';
  3831. $tmp = $tmp . '<label for="radio_receipt" >' . $langs->trans("receiptAsk") . '</label>';
  3832. $desc = $form->textwithpicto($tmp, $langs->transnoentities("receiptDesc"), 1, 'help', '', 0, 3);
  3833. print '<table class="nobordernopadding"><tr>';
  3834. print '<td>';
  3835. print $desc;
  3836. print '</td>';
  3837. if ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid))) {
  3838. print '<td class="nowrap" style="padding-left: 15px">';
  3839. print '<span class="opacitymedium">' . $langs->trans('PercentOfOriginalObject') . '</span>:<input class="right" placeholder="100%" type="text" id="valuepeceipt" name="valuepeceipt" size="3" value="' . (GETPOSTISSET('valuepeceipt') ? GETPOST('valuepeceipt', 'alpha') : '100%') . '"/>';
  3840. print '</td>';
  3841. }
  3842. print '</tr></table>';
  3843. print '</div></div>';
  3844. if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid)))) {
  3845. // Deposit - Down payment
  3846. if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) {
  3847. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3848. $tmp = '<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
  3849. print '<script type="text/javascript">
  3850. jQuery(document).ready(function() {
  3851. jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
  3852. jQuery("#radio_standard").prop("checked", true);
  3853. });
  3854. jQuery("#typereceipt, #valuereceipt").click(function() {
  3855. jQuery("#radio_receipt").prop("checked", true);
  3856. });
  3857. jQuery("#typedeposit, #valuedeposit").click(function() {
  3858. jQuery("#radio_deposit").prop("checked", true);
  3859. });
  3860. jQuery("#typedeposit").change(function() {
  3861. console.log("We change type of down payment");
  3862. jQuery("#radio_deposit").prop("checked", true);
  3863. setRadioForTypeOfIncoice();
  3864. });
  3865. jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_creditnote, #radio_template", #radio_receipt".change(function() {
  3866. setRadioForTypeOfIncoice();
  3867. });
  3868. function setRadioForTypeOfIncoice() {
  3869. console.log("Change radio");
  3870. if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
  3871. jQuery(".checkforselect").prop("disabled", true);
  3872. jQuery(".checkforselect").prop("checked", false);
  3873. } else {
  3874. jQuery(".checkforselect").prop("disabled", false);
  3875. jQuery(".checkforselect").prop("checked", true);
  3876. }
  3877. };
  3878. });
  3879. </script>';
  3880. print '<table class="nobordernopadding"><tr>';
  3881. print '<td>';
  3882. $tmp = $tmp . '<label for="radio_deposit">' . $langs->trans("InvoiceDeposit") . '</label>';
  3883. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3, 'depositonsmartphone');
  3884. print $desc;
  3885. print '</td>';
  3886. if (($origin == 'propal') || ($origin == 'commande')) {
  3887. print '<td class="nowrap" style="padding-left: 15px">';
  3888. $arraylist = array(
  3889. 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  3890. 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  3891. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  3892. );
  3893. $typedeposit = GETPOST('typedeposit', 'aZ09');
  3894. $valuedeposit = GETPOST('valuedeposit', 'int');
  3895. if (empty($typedeposit) && !empty($objectsrc->deposit_percent)) {
  3896. $origin_payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $objectsrc->cond_reglement_id);
  3897. if (!empty($origin_payment_conditions_deposit_percent)) {
  3898. $typedeposit = 'variable';
  3899. }
  3900. }
  3901. if (empty($valuedeposit) && $typedeposit == 'variable' && !empty($objectsrc->deposit_percent)) {
  3902. $valuedeposit = $objectsrc->deposit_percent;
  3903. }
  3904. print $form->selectarray('typedeposit', $arraylist, $typedeposit, 0, 0, 0, '', 1);
  3905. print '</td>';
  3906. print '<td class="nowrap" style="padding-left: 5px">';
  3907. print '<span class="opacitymedium paddingleft">' . $langs->trans("AmountOrPercent") . '</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="' . $valuedeposit . '"/>';
  3908. print '</td>';
  3909. }
  3910. print '</tr></table>';
  3911. print '</div></div>';
  3912. }
  3913. }
  3914. if ($socid > 0) {
  3915. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  3916. // First situation invoice
  3917. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3918. $tmp = '<input id="radio_situation" type="radio" name="type" value="5"' . (GETPOST('type') == 5 ? ' checked' : '') . '> ';
  3919. $tmp = $tmp . '<label for="radio_situation" >' . $langs->trans("InvoiceFirstSituationAsk") . '</label>';
  3920. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3, 'firstsituationonsmartphone');
  3921. print $desc;
  3922. print '</div></div>';
  3923. // Next situation invoice
  3924. $opt = $form->selectSituationInvoices(GETPOST('originid', 'int'), $socid);
  3925. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3926. $tmp = '<input type="radio" name="type" value="5"' . (GETPOST('type') == 5 && GETPOST('originid', 'int') ? ' checked' : '');
  3927. if ($opt == ('<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
  3928. $tmp .= ' disabled';
  3929. }
  3930. $tmp .= '> ';
  3931. $text = $tmp . '<label>' . $langs->trans("InvoiceSituationAsk") . '</label> ';
  3932. $text .= '<select class="flat" id="situations" name="situations"';
  3933. if ($opt == ('<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
  3934. $text .= ' disabled';
  3935. }
  3936. $text .= '>';
  3937. $text .= $opt;
  3938. $text .= '</select>';
  3939. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceSituationDesc"), 1, 'help', '', 0, 3);
  3940. print $desc;
  3941. print '</div></div>';
  3942. }
  3943. // Replacement
  3944. if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
  3945. // Type de facture
  3946. $facids = $facturestatic->list_replacable_invoices($soc->id);
  3947. if ($facids < 0) {
  3948. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  3949. exit();
  3950. }
  3951. $options = "";
  3952. if (is_array($facids)) {
  3953. foreach ($facids as $facparam) {
  3954. $options .= '<option value="' . $facparam['id'] . '"';
  3955. if ($facparam['id'] == GETPOST('fac_replacement', 'int')) {
  3956. $options .= ' selected';
  3957. }
  3958. $options .= '>' . $facparam['ref'];
  3959. $options .= ' (' . $facturestatic->LibStatut($facparam['paid'], $facparam['status'], 0, $facparam['alreadypaid']) . ')';
  3960. $options .= '</option>';
  3961. }
  3962. }
  3963. print '<!-- replacement line -->';
  3964. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3965. $tmp = '<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
  3966. if (!$options || $invoice_predefined->id > 0) {
  3967. $tmp .= ' disabled';
  3968. }
  3969. $tmp .= '> ';
  3970. print '<script type="text/javascript">
  3971. jQuery(document).ready(function() {
  3972. jQuery("#fac_replacement").change(function() {
  3973. jQuery("#radio_replacement").prop("checked", true);
  3974. });
  3975. });
  3976. </script>';
  3977. $text = $tmp . '<label for="radio_replacement">' . $langs->trans("InvoiceReplacementAsk") . '</label>';
  3978. $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
  3979. if (!$options || $invoice_predefined->id > 0) {
  3980. $text .= ' disabled';
  3981. }
  3982. $text .= '>';
  3983. if ($options) {
  3984. $text .= '<option value="-1">&nbsp;</option>';
  3985. $text .= $options;
  3986. } else {
  3987. $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
  3988. }
  3989. $text .= '</select>';
  3990. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  3991. print $desc;
  3992. print '</div></div>';
  3993. }
  3994. } else {
  3995. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  3996. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3997. $tmp = '<input type="radio" name="type" id="radio_situation" value="0" disabled> ';
  3998. $text = $tmp . '<label>' . $langs->trans("InvoiceSituationAsk") . '</label> ';
  3999. $text .= '<span class="opacitymedium">(' . $langs->trans("YouMustCreateInvoiceFromThird") . ')</span> ';
  4000. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3, 'firstsituationonsmartphone');
  4001. print $desc;
  4002. print '</div></div>';
  4003. }
  4004. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4005. $tmp = '<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
  4006. $text = $tmp . '<label for="radio_replacement" class="opacitymedium">' . $langs->trans("InvoiceReplacement") . '</label> ';
  4007. //$text .= '<span class="opacitymedium hideonsmartphone">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
  4008. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc") . '<br><br>' . $langs->trans("YouMustCreateInvoiceFromThird"), 1, 'help', '', 0, 3, 'replacementonsmartphone');
  4009. print $desc;
  4010. print '</div></div>';
  4011. }
  4012. if (empty($origin)) {
  4013. if ($socid > 0) {
  4014. // Credit note
  4015. if (GETPOST('type', 'int') == 8) {
  4016. // Show link for credit note
  4017. $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
  4018. if ($facids < 0) {
  4019. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  4020. exit;
  4021. }
  4022. $optionsav = "";
  4023. $newinvoice_static = new Facture($db);
  4024. foreach ($facids as $key => $valarray) {
  4025. $newinvoice_static->id = $key;
  4026. $newinvoice_static->ref = $valarray['ref'];
  4027. $newinvoice_static->statut = $valarray['status'];
  4028. $newinvoice_static->type = $valarray['type'];
  4029. $newinvoice_static->paye = $valarray['paye'];
  4030. $optionsav .= '<option value="' . $key . '"';
  4031. if ($key == GETPOST('fac_avoir')) {
  4032. $optionsav .= ' selected';
  4033. // pre-filled extra fields with selected credit note
  4034. $newinvoice_static->fetch_optionals($key);
  4035. $object->array_options = $newinvoice_static->array_options;
  4036. }
  4037. $optionsav .= '>';
  4038. $optionsav .= $newinvoice_static->ref;
  4039. $optionsav .= ' (' . $newinvoice_static->getLibStatut(1, $valarray['paymentornot']) . ')';
  4040. $optionsav .= '</option>';
  4041. }
  4042. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4043. $tmp = '<input type="radio" id="radio_creditnote_receipt" name="type" value="8"'.(GETPOST('type') == 8 ? ' checked' : '');
  4044. if ((!$optionsav && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) {
  4045. $tmp .= ' disabled';
  4046. }
  4047. $tmp .= '> ';
  4048. // Show credit note options only if we checked credit note
  4049. print '<script type="text/javascript">
  4050. jQuery(document).ready(function() {
  4051. if (! jQuery("#radio_creditnote_receipt").is(":checked"))
  4052. {
  4053. jQuery("#credit_note_receipt_options").hide();
  4054. }
  4055. jQuery("#radio_creditnote_receipt").click(function() {
  4056. jQuery("#credit_note_receipt_options").show();
  4057. });
  4058. jQuery("#radio_standard, #radio_replacement, #radio_deposit, #radio_receipt").click(function() {
  4059. jQuery("#credit_note_receipt_options").hide();
  4060. });
  4061. });
  4062. </script>';
  4063. $text = '<label>'.$tmp.$langs->transnoentities("ReceiptAvoirAsk").'</label> ';
  4064. // $text.='<input type="text" value="">';
  4065. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  4066. if (!$optionsav || $invoice_predefined->id > 0) {
  4067. $text .= ' disabled';
  4068. }
  4069. $text .= '>';
  4070. if ($optionsav) {
  4071. $text .= '<option value="-1"></option>';
  4072. $text .= $optionsav;
  4073. } else {
  4074. $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
  4075. }
  4076. $text .= '</select>';
  4077. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  4078. print $desc;
  4079. print '<div id="credit_note_receipt_options" class="clearboth">';
  4080. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="$(\'#credit_note_receipt_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithLines', 'int') > 0 ? 'checked' : '').' /> <label for="ReceiptinvoiceAvoirWithLines">'.$langs->trans('ReceiptinvoiceAvoirWithLines')."</label>";
  4081. //print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_receipt_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  4082. print '</div>';
  4083. print '</div></div>';
  4084. }
  4085. elseif (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) {
  4086. // Show link for credit note
  4087. $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
  4088. if ($facids < 0) {
  4089. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  4090. exit;
  4091. }
  4092. $optionsav = "";
  4093. $newinvoice_static = new Facture($db);
  4094. foreach ($facids as $key => $valarray) {
  4095. $newinvoice_static->id = $key;
  4096. $newinvoice_static->ref = $valarray['ref'];
  4097. $newinvoice_static->statut = $valarray['status'];
  4098. $newinvoice_static->type = $valarray['type'];
  4099. $newinvoice_static->paye = $valarray['paye'];
  4100. $optionsav .= '<option value="'.$key.'"';
  4101. if ($key == GETPOST('fac_avoir') && !$customerchange) {
  4102. $optionsav .= ' selected';
  4103. // pre-filled extra fields with selected credit note
  4104. $newinvoice_static->fetch_optionals($key);
  4105. $object->array_options = $newinvoice_static->array_options;
  4106. }
  4107. $optionsav .= '>';
  4108. $optionsav .= $newinvoice_static->ref;
  4109. $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray['paymentornot']).')';
  4110. $optionsav .= '</option>';
  4111. }
  4112. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4113. $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"' . (GETPOST('type') == 2 ? ' checked' : '');
  4114. if ((!$optionsav && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) {
  4115. $tmp .= ' disabled';
  4116. }
  4117. $tmp .= '> ';
  4118. // Show credit note options only if we checked credit note
  4119. print '<script type="text/javascript">
  4120. jQuery(document).ready(function() {
  4121. if (! jQuery("#radio_creditnote").is(":checked"))
  4122. {
  4123. jQuery("#credit_note_options").hide();
  4124. }
  4125. jQuery("#radio_creditnote").click(function() {
  4126. jQuery("#credit_note_options").show();
  4127. });
  4128. jQuery("#radio_standard, #radio_replacement, #radio_deposit, #radio_receipt").click(function() {
  4129. jQuery("#credit_note_options").hide();
  4130. });
  4131. });
  4132. </script>';
  4133. $text = '<label>' . $tmp . $langs->transnoentities("InvoiceAvoirAsk") . '</label> ';
  4134. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  4135. if (!$optionsav || $invoice_predefined->id > 0) {
  4136. $text .= ' disabled';
  4137. }
  4138. $text .= '>';
  4139. if ($optionsav) {
  4140. $text .= '<option value="-1"></option>';
  4141. $text .= $optionsav;
  4142. } else {
  4143. $text .= '<option value="-1">' . $langs->trans("NoInvoiceToCorrect") . '</option>';
  4144. }
  4145. $text .= '</select>';
  4146. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  4147. print $desc;
  4148. print '<div id="credit_note_options" class="clearboth paddingtop marginbottomonly">';
  4149. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" ' . (GETPOST('invoiceAvoirWithLines', 'int') > 0 ? 'checked' : '') . ' /> <label for="invoiceAvoirWithLines">' . $langs->trans('invoiceAvoirWithLines') . "</label>";
  4150. print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" ' . (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '') . ' /> <label for="invoiceAvoirWithPaymentRestAmount">' . $langs->trans('invoiceAvoirWithPaymentRestAmount') . "</label>";
  4151. print '</div>';
  4152. print '</div></div>';
  4153. }
  4154. } else {
  4155. //-------------------------------------
  4156. //
  4157. // Change Customername
  4158. //
  4159. //-------------------------------------
  4160. if ($customerchange) {
  4161. $facidsCC = $facturestatic->list_qualified_avoir_invoices($soc->id);
  4162. if ($facidsCC < 0) {
  4163. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  4164. exit;
  4165. }
  4166. $optionsav = "";
  4167. $newinvoice_staticCC = new Facture($db);
  4168. foreach ($facidsCC as $key => $valarray) {
  4169. $newinvoice_staticCC->id = $key;
  4170. $newinvoice_staticCC->ref = $valarray['ref'];
  4171. $newinvoice_staticCC->statut = $valarray['status'];
  4172. $newinvoice_staticCC->type = $valarray['type'];
  4173. $newinvoice_staticCC->paye = $valarray['paye'];
  4174. $optionsav .= '<option value="'.$key.'"';
  4175. if ($key == GETPOST('fac_avoir')) {
  4176. $optionsav .= ' selected';
  4177. // pre-filled extra fields with selected credit note
  4178. $newinvoice_staticCC->fetch_optionals($key);
  4179. $object->array_options = $newinvoice_staticCC->array_options;
  4180. }
  4181. $optionsav .= '>';
  4182. $optionsav .= $newinvoice_staticCC->ref;
  4183. $optionsav .= ' ('.$newinvoice_staticCC->getLibStatut(1, $valarray['paymentornot']).')';
  4184. $optionsav .= '</option>';
  4185. }
  4186. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4187. $tmp = '<input type="radio" id="radio_creditnoteCustomerchange" name="type" value="6" checked';
  4188. if ((!$optionsav && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) {
  4189. $tmp .= ' disabled';
  4190. }
  4191. $tmp .= '> ';
  4192. // Show credit note options only if we checked credit note
  4193. print '<script type="text/javascript">
  4194. jQuery(document).ready(function() {
  4195. if (! jQuery("#radio_creditnoteCustomerchange").is(":checked"))
  4196. {
  4197. jQuery("#credit_note_options").hide();
  4198. }
  4199. $("#radio_standard, #radio_deposit, #radio_replacement, #radio_creditnote, #fac_replacement, #radio_receipt").prop("disabled", true);
  4200. jQuery("#radio_creditnoteCustomerchange").click(function() {
  4201. jQuery("#credit_note_options").show();
  4202. });
  4203. jQuery("#radio_standard, #radio_replacement, #radio_deposit, #radio_receipt").click(function() {
  4204. jQuery("#credit_note_options").hide();
  4205. });
  4206. });
  4207. </script>';
  4208. $text = '<label>'.$tmp.$langs->trans("customerchangeLabel").'</label> ';
  4209. // $text.='<input type="text" value="">';
  4210. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  4211. if (!$optionsav || $invoice_predefined->id > 0) {
  4212. $text .= ' disabled';
  4213. }
  4214. $text .= '>';
  4215. if ($optionsav) {
  4216. $text .= '<option value="-1"></option>';
  4217. $text .= $optionsav;
  4218. } else {
  4219. $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
  4220. }
  4221. $text .= '</select>';
  4222. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  4223. print $desc;
  4224. print '<div id="credit_note_options" class="clearboth">';
  4225. $invoiceAvoirWithLinesCustomerChangeString = $langs->trans('invoiceAvoirWithLinesCustomerChange');
  4226. if(GETPOST('type') == 7){
  4227. $invoiceAvoirWithLinesCustomerChangeString = $langs->trans('invoiceAvoirWithLinesCustomerChangeReceipt');
  4228. }
  4229. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLinesCustomerChange" id="invoiceAvoirWithLinesCustomerChange" value="'.GETPOST('type').'" '.((GETPOST('type') == 0 || GETPOST('type') == 7) ? 'checked' : '').' /> <label for="invoiceAvoirWithLinesCustomerChange">'.$invoiceAvoirWithLinesCustomerChangeString."</label>";
  4230. //print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLinesReceiptCustomerChange" id="invoiceAvoirWithLinesReceiptCustomerChange" value="'.GETPOST('type').'" '.(GETPOST('type') == 7 ? 'checked' : '').' /> <label for="invoiceAvoirWithLinesReceiptCustomerChange">'.$langs->trans('invoiceAvoirWithLinesReceiptCustomerChange')."</label>";
  4231. //print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  4232. print '</div>';
  4233. print '</div></div>';
  4234. }
  4235. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4236. if (empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  4237. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
  4238. } else {
  4239. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="2" > ';
  4240. }
  4241. $text = $tmp . '<label class="opacitymedium" for="radio_creditnote">' . $langs->trans("InvoiceAvoir") . '</label> ';
  4242. //$text .= '<span class="opacitymedium hideonsmartphone">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
  4243. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc") . '<br><br>' . $langs->trans("YouMustCreateInvoiceFromThird"), 1, 'help', '', 0, 3, 'creditnoteonsmartphone');
  4244. print $desc;
  4245. print '</div></div>' . "\n";
  4246. }
  4247. }
  4248. // Template invoice
  4249. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  4250. $tmp = '<input type="radio" name="type" id="radio_template" value="0" disabled> ';
  4251. $text = $tmp . '<label class="opacitymedium" for="radio_template">' . $langs->trans("RepeatableInvoice") . '</label> ';
  4252. $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3, 'templateonsmartphone');
  4253. print $desc;
  4254. print '</div></div>';
  4255. print '</div>';
  4256. if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) { // Hidden conf
  4257. // Add auto select default document model
  4258. $listtType = array(Facture::TYPE_STANDARD, Facture::TYPE_REPLACEMENT, Facture::TYPE_CREDIT_NOTE, Facture::TYPE_RECEIPT_CREDIT_NOTE, Facture::TYPE_DEPOSIT, Facture::TYPE_SITUATION);
  4259. $jsListType = '';
  4260. foreach ($listtType as $type) {
  4261. $thisTypeConfName = 'FACTURE_ADDON_PDF_' . $type;
  4262. $curent = !empty($conf->global->{$thisTypeConfName}) ? $conf->global->{$thisTypeConfName} : $conf->global->FACTURE_ADDON_PDF;
  4263. $jsListType .= (!empty($jsListType) ? ',' : '') . '"' . $type . '":"' . $curent . '"';
  4264. }
  4265. print '<script type="text/javascript">
  4266. $(document).ready(function() {
  4267. var listType = {' . $jsListType . '};
  4268. $("[name=\'type\'").change(function() {
  4269. console.log("change name=type");
  4270. if ($( this ).prop("checked"))
  4271. {
  4272. if(($( this ).val() in listType))
  4273. {
  4274. $("#model").val(listType[$( this ).val()]);
  4275. }
  4276. else
  4277. {
  4278. $("#model").val("' . $conf->global->FACTURE_ADDON_PDF . '");
  4279. }
  4280. }
  4281. });
  4282. });
  4283. </script>';
  4284. }
  4285. print '</td></tr>';
  4286. if ($socid > 0) {
  4287. // Discounts for third party
  4288. print '<tr><td>' . $langs->trans('DiscountStillRemaining') . '</td><td colspan="2">';
  4289. $thirdparty = $soc;
  4290. $discount_type = 0;
  4291. $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin', 'alpha') . '&originid=' . GETPOST('originid', 'int'));
  4292. include DOL_DOCUMENT_ROOT . '/core/tpl/object_discounts.tpl.php';
  4293. print '</td></tr>';
  4294. }
  4295. $newdateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver');
  4296. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  4297. // Date invoice
  4298. print '<tr><td class="fieldrequired">' . $langs->trans('DateInvoice') . '</td><td colspan="2">';
  4299. print $form->selectDate($newdateinvoice ? $newdateinvoice : $dateinvoice, '', '', '', '', "add", 1, 1);
  4300. print '</td></tr>';
  4301. // Date point of tax
  4302. if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
  4303. print '<tr><td class="fieldrequired">' . $langs->trans('DatePointOfTax') . '</td><td colspan="2">';
  4304. print $form->selectDate($date_pointoftax ? $date_pointoftax : -1, 'date_pointoftax', '', '', '', "add", 1, 1);
  4305. print '</td></tr>';
  4306. }
  4307. // Payment term
  4308. print '<tr><td class="nowrap fieldrequired">' . $langs->trans('PaymentConditionsShort') . '</td><td colspan="2">';
  4309. print $form->getSelectConditionsPaiements(GETPOSTISSET('cond_reglement_id') ? GETPOST('cond_reglement_id', 'int') : $cond_reglement_id, 'cond_reglement_id');
  4310. print '</td></tr>';
  4311. if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  4312. $rwStyle = 'display:none;';
  4313. if (in_array(GETPOST('type', 'int'), $retainedWarrantyInvoiceAvailableType)) {
  4314. $rwStyle = '';
  4315. }
  4316. $retained_warranty = GETPOST('retained_warranty', 'int');
  4317. if (empty($retained_warranty)) {
  4318. if (!empty($objectsrc->retained_warranty)) { // use previous situation value
  4319. $retained_warranty = $objectsrc->retained_warranty;
  4320. }
  4321. }
  4322. $retained_warranty_js_default = !empty($retained_warranty) ? $retained_warranty : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT;
  4323. print '<tr class="retained-warranty-line" style="' . $rwStyle . '" ><td class="nowrap">' . $langs->trans('RetainedWarranty') . '</td><td colspan="2">';
  4324. print '<input id="new-situation-invoice-retained-warranty" name="retained_warranty" type="number" value="' . $retained_warranty . '" step="0.01" min="0" max="100" />%';
  4325. // Retained warranty payment term
  4326. print '<tr class="retained-warranty-line" style="' . $rwStyle . '" ><td class="nowrap">' . $langs->trans('PaymentConditionsShortRetainedWarranty') . '</td><td colspan="2">';
  4327. $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  4328. if (empty($retained_warranty_fk_cond_reglement)) {
  4329. $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  4330. if (!empty($objectsrc->retained_warranty_fk_cond_reglement)) { // use previous situation value
  4331. $retained_warranty_fk_cond_reglement = $objectsrc->retained_warranty_fk_cond_reglement;
  4332. } else {
  4333. $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  4334. }
  4335. }
  4336. print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
  4337. print '</td></tr>';
  4338. print '<script type="text/javascript">
  4339. $(document).ready(function() {
  4340. $("[name=\'type\']").change(function() {
  4341. if($( this ).prop("checked") && $.inArray($( this ).val(), ' . json_encode($retainedWarrantyInvoiceAvailableType) . ' ) !== -1)
  4342. {
  4343. $(".retained-warranty-line").show();
  4344. $("#new-situation-invoice-retained-warranty").val("' . floatval($retained_warranty_js_default) . '");
  4345. }
  4346. else{
  4347. $(".retained-warranty-line").hide();
  4348. $("#new-situation-invoice-retained-warranty").val("");
  4349. }
  4350. });
  4351. $("[name=\'type\']:checked").trigger("change");
  4352. });
  4353. </script>';
  4354. }
  4355. // Payment mode
  4356. print '<tr><td class="fieldrequired">' . $langs->trans('PaymentMode') . '</td><td colspan="2">';
  4357. print img_picto('', 'payment', 'class="pictofixedwidth"');
  4358. $factureTMPOBJ = new Facture($db);
  4359. $factureTMPOBJ->fetch(GETPOST('fac_avoir'));
  4360. if(isset($factureTMPOBJ->mode_reglement_id)){
  4361. $mode_reglement_id = $factureTMPOBJ->mode_reglement_id;
  4362. }
  4363. print $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ? GETPOST('mode_reglement_id') : $mode_reglement_id, 'mode_reglement_id', 'CRDT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx', 1);
  4364. print '</td></tr>';
  4365. $alert = $langs->trans('ReglementAlert');
  4366. print '<div class="jnotify-container payementmethodAlert" style="display:none;"><div class="jnotify-notification jnotify-notification-error"><div class="jnotify-background"></div><a class="jnotify-close" onclick="closePayementMethodAlert()">×</a><div class="jnotify-message"><div>'.$alert.'</div></div></div></div>';
  4367. print '<script type="text/javascript">
  4368. function closePayementMethodAlert(){
  4369. $(".payementmethodAlert").css({\'display\':\'none\'})
  4370. }
  4371. $(document).ready(function() {
  4372. $("#formtocreate").submit(function(event) {
  4373. event.preventDefault();
  4374. var selectedValue = $("#selectmode_reglement_id").val();
  4375. if (selectedValue === "") {
  4376. $(".payementmethodAlert").css({\'display\':\'block\'});
  4377. } else {
  4378. $("#formtocreate").off("submit").submit();
  4379. }
  4380. });
  4381. });
  4382. </script>';
  4383. // Bank Account
  4384. if (isModEnabled("banque")) {
  4385. if(isset($factureTMPOBJ->fk_account)){
  4386. $fk_account = $factureTMPOBJ->fk_account;
  4387. }
  4388. print '<tr><td>' . $langs->trans('BankAccount') . '</td><td colspan="2">';
  4389. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4390. print $form->select_comptes(($fk_account < 0 ? '' : $fk_account), 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
  4391. print '</td></tr>';
  4392. }
  4393. // Project
  4394. if (isModEnabled('project')) {
  4395. $langs->load('projects');
  4396. print '<tr><td>' . $langs->trans('Project') . '</td><td colspan="2">';
  4397. print img_picto('', 'project') . $formproject->select_projects(($socid > 0 ? $socid : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
  4398. 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 : '')) . '"><span class="fa fa-plus-circle valignmiddle" title="' . $langs->trans("AddProject") . '"></span></a>';
  4399. print '</td></tr>';
  4400. }
  4401. // Incoterms
  4402. if (isModEnabled('incoterm')) {
  4403. print '<tr>';
  4404. print '<td><label for="incoterm_id">' . $form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms : '', 1) . '</label></td>';
  4405. print '<td colspan="2" class="maxwidthonsmartphone">';
  4406. $incoterm_id = GETPOST('incoterm_id');
  4407. $incoterm_location = GETPOST('location_incoterms');
  4408. if (empty($incoterm_id)) {
  4409. $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
  4410. $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
  4411. }
  4412. print $form->select_incoterms($incoterm_id, $incoterm_location);
  4413. print '</td></tr>';
  4414. }
  4415. // Other attributes
  4416. $parameters = array('objectsrc' => !empty($objectsrc) ? $objectsrc : 0, 'colspan' => ' colspan="2"', 'cols' => '2', 'socid' => $socid);
  4417. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  4418. print $hookmanager->resPrint;
  4419. if (empty($reshook)) {
  4420. if (!empty($conf->global->THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE) && !empty($soc->id)) {
  4421. // copy from thirdparty
  4422. $tpExtrafields = new Extrafields($db);
  4423. $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
  4424. if ($soc->fetch_optionals() > 0) {
  4425. $object->array_options = array_merge($object->array_options, $soc->array_options);
  4426. }
  4427. }
  4428. ;
  4429. print $object->showOptionals($extrafields, 'create', $parameters);
  4430. }
  4431. // Template to use by default
  4432. print '<tr><td>' . $langs->trans('Model') . '</td>';
  4433. print '<td colspan="2">';
  4434. print img_picto('', 'pdf', 'class="pictofixedwidth"');
  4435. include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
  4436. $liste = ModelePDFFactures::liste_modeles($db);
  4437. if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) {
  4438. // Hidden conf
  4439. $paramkey = 'FACTURE_ADDON_PDF_' . $object->type;
  4440. $preselected = !empty($conf->global->$paramkey) ? $conf->global->$paramkey : $conf->global->FACTURE_ADDON_PDF;
  4441. } else {
  4442. $preselected = $conf->global->FACTURE_ADDON_PDF;
  4443. }
  4444. print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
  4445. print "</td></tr>";
  4446. // Multicurrency
  4447. if (isModEnabled('multicurrency')) {
  4448. $currency_code = $factureTMPOBJ->multicurrency_code;
  4449. print '<tr>';
  4450. print '<td>' . $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0) . '</td>';
  4451. print '<td colspan="2" class="maxwidthonsmartphone">';
  4452. print img_picto('', 'currency', 'class="pictofixedwidth"');
  4453. print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
  4454. print '</td></tr>';
  4455. }
  4456. // Help of substitution key
  4457. $htmltext = '';
  4458. if (GETPOST('fac_rec', 'int') > 0) {
  4459. $dateexample = ($newdateinvoice ? $newdateinvoice : $dateinvoice);
  4460. if (empty($dateexample)) {
  4461. $dateexample = dol_now();
  4462. }
  4463. $substitutionarray = array(
  4464. '__TOTAL_HT__' => $langs->trans("AmountHT") . ' (' . $langs->trans("Example") . ': ' . price($exampletemplateinvoice->total_ht) . ')',
  4465. '__TOTAL_TTC__' => $langs->trans("AmountTTC") . ' (' . $langs->trans("Example") . ': ' . price($exampletemplateinvoice->total_ttc) . ')',
  4466. '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m') . ')',
  4467. '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($dateexample, '%m') . ')',
  4468. '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m') . ')',
  4469. '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B') . ')',
  4470. '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($dateexample, '%B') . ')',
  4471. '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B') . ')',
  4472. '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("PreviousYearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y') . ')',
  4473. '__INVOICE_YEAR__' => $langs->trans("YearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date($dateexample, '%Y') . ')',
  4474. '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice") . ' (' . $langs->trans("Example") . ': ' . dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y') . ')'
  4475. );
  4476. $htmltext = '<i>' . $langs->trans("FollowingConstantsWillBeSubstituted") . ':<br>';
  4477. foreach ($substitutionarray as $key => $val) {
  4478. $htmltext .= $key . ' = ' . $langs->trans($val) . '<br>';
  4479. }
  4480. $htmltext .= '</i>';
  4481. }
  4482. // Public note
  4483. print '<tr>';
  4484. print '<td class="tdtop">';
  4485. print $form->textwithpicto($langs->trans('NotePublic'), $htmltext);
  4486. print '</td>';
  4487. print '<td valign="top" colspan="2">';
  4488. $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  4489. print $doleditor->Create(1);
  4490. // Private note
  4491. if (empty($user->socid)) {
  4492. print '<tr>';
  4493. print '<td class="tdtop">';
  4494. print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext);
  4495. print '</td>';
  4496. print '<td valign="top" colspan="2">';
  4497. $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  4498. print $doleditor->Create(1);
  4499. // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
  4500. print '</td></tr>';
  4501. }
  4502. // Lines from source (TODO Show them also when creating invoice from template invoice)
  4503. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  4504. $langs->loadLangs(array('orders', 'propal'));
  4505. // TODO for compatibility
  4506. if ($origin == 'contrat') {
  4507. // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
  4508. $objectsrc->remise_absolue = $remise_absolue;
  4509. $objectsrc->remise_percent = $remise_percent;
  4510. $objectsrc->update_price(1, 'auto', 1);
  4511. }
  4512. print "\n<!-- Show ref of origin " . $classname . " -->\n";
  4513. print '<input type="hidden" name="amount" value="' . $objectsrc->total_ht . '">' . "\n";
  4514. print '<input type="hidden" name="total" value="' . $objectsrc->total_ttc . '">' . "\n";
  4515. print '<input type="hidden" name="tva" value="' . $objectsrc->total_tva . '">' . "\n";
  4516. // The commented lines below are fields already added as hidden parameters before
  4517. //print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  4518. //print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  4519. switch (get_class($objectsrc)) {
  4520. case 'Propal':
  4521. $newclassname = 'CommercialProposal';
  4522. break;
  4523. case 'Commande':
  4524. $newclassname = 'Order';
  4525. break;
  4526. case 'Expedition':
  4527. $newclassname = 'Sending';
  4528. break;
  4529. case 'Contrat':
  4530. $newclassname = 'Contract';
  4531. break;
  4532. case 'Fichinter':
  4533. $newclassname = 'Intervention';
  4534. break;
  4535. default:
  4536. $newclassname = get_class($objectsrc);
  4537. }
  4538. // Ref of origin
  4539. print '<tr><td>' . $langs->trans($newclassname) . '</td>';
  4540. print '<td colspan="2">';
  4541. print $objectsrc->getNomUrl(1);
  4542. // We check if Origin document (id and type is known) has already at least one invoice attached to it
  4543. $objectsrc->fetchObjectLinked($originid, $origin, '', 'facture');
  4544. if (is_array($objectsrc->linkedObjects['facture']) && count($objectsrc->linkedObjects['facture']) >= 1) {
  4545. setEventMessages('WarningBillExist', null, 'warnings');
  4546. echo ' - ' . $langs->trans('LatestRelatedBill') . ' ' . end($objectsrc->linkedObjects['facture'])->getNomUrl(1);
  4547. }
  4548. echo '</td></tr>';
  4549. print '<tr><td>' . $langs->trans('AmountHT') . '</td><td colspan="2">' . price($objectsrc->total_ht) . '</td></tr>';
  4550. print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td colspan="2">' . price($objectsrc->total_tva) . "</td></tr>";
  4551. if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1
  4552. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax1) . "</td></tr>";
  4553. }
  4554. if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2
  4555. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax2) . "</td></tr>";
  4556. }
  4557. print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td colspan="2">' . price($objectsrc->total_ttc) . "</td></tr>";
  4558. if (isModEnabled('multicurrency')) {
  4559. print '<tr><td>' . $langs->trans('MulticurrencyAmountHT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ht) . '</td></tr>';
  4560. print '<tr><td>' . $langs->trans('MulticurrencyAmountVAT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_tva) . "</td></tr>";
  4561. print '<tr><td>' . $langs->trans('MulticurrencyAmountTTC') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>";
  4562. }
  4563. }
  4564. print "</table>\n";
  4565. print dol_get_fiche_end();
  4566. print $form->buttonsSaveCancel("CreateDraft");
  4567. // Show origin lines
  4568. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  4569. print '<br>';
  4570. $title = $langs->trans('ProductsAndServices');
  4571. print load_fiche_titre($title);
  4572. print '<div class="div-table-responsive-no-min">';
  4573. print '<table class="noborder centpercent">';
  4574. $objectsrc->printOriginLinesList('', $selectedLines);
  4575. print '</table>';
  4576. print '</div>';
  4577. }
  4578. print "</form>\n";
  4579. } elseif ($id > 0 || !empty($ref)) {
  4580. if (empty($object->id)) {
  4581. $langs->load('errors');
  4582. echo '<div class="error">' . $langs->trans("ErrorRecordNotFound") . '</div>';
  4583. llxFooter();
  4584. exit;
  4585. }
  4586. /*
  4587. * Show object in view mode
  4588. */
  4589. $result = $object->fetch($id, $ref);
  4590. if ($result <= 0) {
  4591. dol_print_error($db, $object->error, $object->errors);
  4592. exit();
  4593. }
  4594. // fetch optionals attributes and labels
  4595. $extrafields->fetch_name_optionals_label($object->table_element);
  4596. if ($user->socid > 0 && $user->socid != $object->socid) {
  4597. accessforbidden('', 0, 1);
  4598. }
  4599. $result = $object->fetch_thirdparty();
  4600. $result = $soc->fetch($object->socid);
  4601. if ($result < 0) {
  4602. dol_print_error($db);
  4603. }
  4604. $selleruserevenustamp = $mysoc->useRevenueStamp();
  4605. $totalpaid = $object->getSommePaiement();
  4606. $totalcreditnotes = $object->getSumCreditNotesUsed();
  4607. $totaldeposits = $object->getSumDepositsUsed();
  4608. //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
  4609. // selleruserrevenuestamp=".$selleruserevenustamp;
  4610. // We can also use bcadd to avoid pb with floating points
  4611. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  4612. // $resteapayer=bcadd($object->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
  4613. // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  4614. $resteapayer = price2num($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
  4615. // Multicurrency
  4616. if (isModEnabled('multicurrency')) {
  4617. $multicurrency_totalpaid = $object->getSommePaiement(1);
  4618. $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
  4619. $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
  4620. $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaid - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
  4621. // Code to fix case of corrupted data
  4622. // TODO We should not need this. Also data comes from a not reliable value of $object->multicurrency_total_ttc that may be wrong if it was
  4623. // calculated by summing lines that were in a currency for some of them and into another for others (lines from discount/down payment into another currency for example)
  4624. if ($resteapayer == 0 && $multicurrency_resteapayer != 0 && $object->multicurrency_code != $conf->currency) {
  4625. $resteapayer = price2num($multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
  4626. }
  4627. }
  4628. if ($object->paye) {
  4629. $resteapayer = 0;
  4630. }
  4631. $resteapayer = round($resteapayer, 2);
  4632. $resteapayeraffiche = $resteapayer;
  4633. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this
  4634. $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  4635. $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  4636. } else {
  4637. $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
  4638. $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
  4639. }
  4640. $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
  4641. $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
  4642. $absolute_discount = price2num($absolute_discount, 'MT');
  4643. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  4644. $author = new User($db);
  4645. if ($object->user_author) {
  4646. $author->fetch($object->user_author);
  4647. }
  4648. $objectidnext = $object->getIdReplacingInvoice();
  4649. $head = facture_prepare_head($object);
  4650. print dol_get_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), -1, 'bill');
  4651. $formconfirm = '';
  4652. // Confirmation de la conversion de l'avoir en reduc
  4653. if ($action == 'converttoreduc') {
  4654. if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION || $object->type == Facture::TYPE_RECEIPT) {
  4655. $type_fac = 'ExcessReceived';
  4656. } elseif ($object->type == Facture::TYPE_CREDIT_NOTE) {
  4657. $type_fac = 'CreditNote';
  4658. } elseif ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  4659. $type_fac = 'CreditNote';
  4660. } elseif ($object->type == Facture::TYPE_DEPOSIT) {
  4661. $type_fac = 'Deposit';
  4662. }
  4663. $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac)));
  4664. $text .= '<br>' . $langs->trans('ConfirmConvertToReduc2');
  4665. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
  4666. }
  4667. // Confirmation to delete invoice
  4668. if ($action == 'delete') {
  4669. $text = $langs->trans('ConfirmDeleteBill', $object->ref);
  4670. $formquestion = array();
  4671. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $object->statut >= 1) {
  4672. $qualified_for_stock_change = 0;
  4673. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4674. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  4675. } else {
  4676. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  4677. }
  4678. if ($qualified_for_stock_change) {
  4679. $langs->load("stocks");
  4680. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  4681. $formproduct = new FormProduct($db);
  4682. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  4683. $forcecombo = 0;
  4684. if ($conf->browser->name == 'ie') {
  4685. $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
  4686. }
  4687. $formquestion = array(
  4688. // 'text' => $langs->trans("ConfirmClone"),
  4689. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
  4690. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
  4691. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, $langs->trans("NoStockAction"), 0, $forcecombo))
  4692. );
  4693. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
  4694. } else {
  4695. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
  4696. }
  4697. } else {
  4698. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
  4699. }
  4700. }
  4701. // Confirmation to remove invoice from cycle
  4702. if ($action == 'situationout') {
  4703. $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref);
  4704. $label = $langs->trans("ConfirmOuting");
  4705. $formquestion = array();
  4706. // remove situation from cycle
  4707. if (
  4708. in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  4709. && $usercancreate
  4710. && !$objectidnext
  4711. && $object->is_last_in_cycle()
  4712. && $usercanunvalidate
  4713. ) {
  4714. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1);
  4715. }
  4716. }
  4717. // Confirmation of validation
  4718. if ($action == 'valid') {
  4719. // we check object has a draft number
  4720. $objectref = substr($object->ref, 1, 4);
  4721. if ($objectref == 'PROV') {
  4722. $savdate = $object->date;
  4723. if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
  4724. $object->date = dol_now();
  4725. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  4726. }
  4727. $numref = $object->getNextNumRef($soc);
  4728. // $object->date=$savdate;
  4729. } else {
  4730. $numref = $object->ref;
  4731. }
  4732. $text = $langs->trans('ConfirmValidateBill', $numref);
  4733. if (isModEnabled('notification')) {
  4734. require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
  4735. $notify = new Notify($db);
  4736. $text .= '<br>';
  4737. $text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
  4738. }
  4739. $formquestion = array();
  4740. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  4741. $qualified_for_stock_change = 0;
  4742. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4743. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  4744. } else {
  4745. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  4746. }
  4747. if ($qualified_for_stock_change) {
  4748. $langs->load("stocks");
  4749. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  4750. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  4751. $formproduct = new FormProduct($db);
  4752. $warehouse = new Entrepot($db);
  4753. $warehouse_array = $warehouse->list_array();
  4754. if (count($warehouse_array) == 1) {
  4755. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
  4756. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
  4757. } else {
  4758. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
  4759. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  4760. }
  4761. $formquestion = array(
  4762. // 'text' => $langs->trans("ConfirmClone"),
  4763. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  4764. // 1),
  4765. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  4766. // => 1),
  4767. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  4768. );
  4769. }
  4770. }
  4771. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->total_ttc < 0) { // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
  4772. $text .= '<br>' . img_warning() . ' ' . $langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
  4773. }
  4774. // mandatoryPeriod
  4775. $nbMandated = 0;
  4776. foreach ($object->lines as $line) {
  4777. $res = $line->fetch_product();
  4778. if ($res > 0) {
  4779. if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end))) {
  4780. $nbMandated++;
  4781. break;
  4782. }
  4783. }
  4784. }
  4785. if ($nbMandated > 0)
  4786. $text .= '<div><span class="clearboth nowraponall warning">' . $langs->trans("mandatoryPeriodNeedTobeSetMsgValidate") . '</span></div>';
  4787. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, (($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->total_ttc < 0) ? "no" : "yes"), 2);
  4788. }
  4789. // Confirm back to draft status
  4790. if ($action == 'modif') {
  4791. $text = $langs->trans('ConfirmUnvalidateBill', $object->ref);
  4792. $formquestion = array();
  4793. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  4794. $qualified_for_stock_change = 0;
  4795. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4796. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  4797. } else {
  4798. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  4799. }
  4800. if ($qualified_for_stock_change) {
  4801. $langs->load("stocks");
  4802. require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
  4803. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  4804. $formproduct = new FormProduct($db);
  4805. $warehouse = new Entrepot($db);
  4806. $warehouse_array = $warehouse->list_array();
  4807. if (count($warehouse_array) == 1) {
  4808. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
  4809. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
  4810. } else {
  4811. $label = $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  4812. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  4813. }
  4814. $formquestion = array(
  4815. // 'text' => $langs->trans("ConfirmClone"),
  4816. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  4817. // 1),
  4818. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  4819. // => 1),
  4820. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  4821. );
  4822. }
  4823. }
  4824. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('UnvalidateBill'), $text, 'confirm_modif', $formquestion, "yes", 1);
  4825. }
  4826. // Confirmation du classement paye
  4827. if ($action == 'paid' && ($resteapayer <= 0 || (!empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $resteapayer == $object->total_ttc))) {
  4828. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', "yes", 1);
  4829. }
  4830. if ($action == 'paid' && $resteapayer > 0 && (empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $resteapayer != $object->total_ttc)) {
  4831. $close = array();
  4832. // Code
  4833. $i = 0;
  4834. $close[$i]['code'] = 'discount_vat'; // escompte
  4835. $i++;
  4836. $close[$i]['code'] = 'badcustomer';
  4837. $i++;
  4838. $close[$i]['code'] = 'bankcharge';
  4839. $i++;
  4840. $close[$i]['code'] = 'other';
  4841. $i++;
  4842. // Help
  4843. $i = 0;
  4844. $close[$i]['label'] = $langs->trans("HelpEscompte") . '<br><br>' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
  4845. $i++;
  4846. $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  4847. $i++;
  4848. $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBankChargeDesc");
  4849. $i++;
  4850. $close[$i]['label'] = $langs->trans("Other");
  4851. $i++;
  4852. // Texte
  4853. $i = 0;
  4854. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1);
  4855. $i++;
  4856. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1);
  4857. $i++;
  4858. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBankCharge", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1);
  4859. $i++;
  4860. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
  4861. $i++;
  4862. // arrayreasons[code]=reason
  4863. foreach ($close as $key => $val) {
  4864. $arrayreasons[$close[$key]['code']] = $close[$key]['reason'];
  4865. }
  4866. // Cree un tableau formulaire
  4867. $formquestion = array('text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
  4868. // Paiement incomplet. On demande si motif = escompte ou autre
  4869. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 340, 600);
  4870. }
  4871. // Confirmation du classement abandonne
  4872. if ($action == 'canceled') {
  4873. // S'il y a une facture de remplacement pas encore validee (etat brouillon),
  4874. // on ne permet pas de classer abandonner la facture.
  4875. if ($objectidnext) {
  4876. $facturereplacement = new Facture($db);
  4877. $facturereplacement->fetch($objectidnext);
  4878. $statusreplacement = $facturereplacement->statut;
  4879. }
  4880. if ($objectidnext && $statusreplacement == 0) {
  4881. print '<div class="error">' . $langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated") . '</div>';
  4882. } else {
  4883. // Code
  4884. $close[1]['code'] = 'badcustomer';
  4885. $close[2]['code'] = 'abandon';
  4886. // Help
  4887. $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  4888. $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
  4889. // Texte
  4890. $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close[1]['label'], 1);
  4891. $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
  4892. // arrayreasons
  4893. $arrayreasons[$close[1]['code']] = $close[1]['reason'];
  4894. $arrayreasons[$close[2]['code']] = $close[2]['reason'];
  4895. // Cree un tableau formulaire
  4896. $formquestion = array('text' => $langs->trans("ConfirmCancelBillQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
  4897. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 270);
  4898. }
  4899. }
  4900. if ($action == 'deletepayment') {
  4901. $payment_id = GETPOST('paiement_id');
  4902. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&paiement_id=' . $payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 'no', 1);
  4903. }
  4904. // Confirmation de la suppression d'une ligne produit
  4905. if ($action == 'ask_deleteline') {
  4906. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
  4907. }
  4908. // Clone confirmation
  4909. if ($action == 'clone') {
  4910. // Create an array for form
  4911. $formquestion = array(
  4912. 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)),
  4913. array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
  4914. );
  4915. // Request confirmation to clone
  4916. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250);
  4917. }
  4918. if ($action == "remove_file_comfirm") {
  4919. $file = GETPOST('file', 'alpha');
  4920. $formconfirm = $form->formconfirm(
  4921. $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&file=' . $file,
  4922. $langs->trans('DeleteFileHeader'),
  4923. $langs->trans('DeleteFileText') . "<br><br>" . $file,
  4924. 'remove_file',
  4925. '',
  4926. 'no',
  4927. 2
  4928. );
  4929. }
  4930. // Call Hook formConfirm
  4931. $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid, 'remainingtopay' => &$resteapayer);
  4932. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  4933. if (empty($reshook)) {
  4934. $formconfirm .= $hookmanager->resPrint;
  4935. } elseif ($reshook > 0) {
  4936. $formconfirm = $hookmanager->resPrint;
  4937. }
  4938. // Print form confirm
  4939. print $formconfirm;
  4940. // Invoice content
  4941. $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1' . (!empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
  4942. $morehtmlref = '<div class="refidno">';
  4943. // Ref invoice
  4944. if ($object->status == $object::STATUS_DRAFT && !$mysoc->isInEEC() && !empty($conf->global->INVOICE_ALLOW_FREE_REF)) {
  4945. $morehtmlref .= $form->editfieldkey("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', 0, 1);
  4946. $morehtmlref .= $form->editfieldval("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', null, null, '', 1);
  4947. $morehtmlref .= '<br>';
  4948. }
  4949. // Ref customer
  4950. $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1);
  4951. $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string' . (isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ? ':' . $conf->global->THIRDPARTY_REF_INPUT_SIZE : ''), '', null, null, '', 1);
  4952. // Thirdparty
  4953. $morehtmlref .= '<br>' . $object->thirdparty->getNomUrl(1, 'customer');
  4954. if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
  4955. $morehtmlref .= ' (<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?socid=' . $object->thirdparty->id . '&search_societe=' . urlencode($object->thirdparty->name) . '">' . $langs->trans("OtherBills") . '</a>)';
  4956. }
  4957. // Project
  4958. if (isModEnabled('project')) {
  4959. $langs->load("projects");
  4960. $morehtmlref .= '<br>';
  4961. if ($usercancreate) {
  4962. $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
  4963. if ($action != 'classify') {
  4964. $morehtmlref .= '<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> ';
  4965. }
  4966. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
  4967. } else {
  4968. if (!empty($object->fk_project)) {
  4969. $proj = new Project($db);
  4970. $proj->fetch($object->fk_project);
  4971. $morehtmlref .= $proj->getNomUrl(1);
  4972. if ($proj->title) {
  4973. $morehtmlref .= '<span class="opacitymedium"> - ' . dol_escape_htmltag($proj->title) . '</span>';
  4974. }
  4975. }
  4976. }
  4977. }
  4978. $morehtmlref .= '</div>';
  4979. $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status
  4980. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '');
  4981. print '<div class="fichecenter">';
  4982. print '<div class="fichehalfleft">';
  4983. print '<div class="underbanner clearboth"></div>';
  4984. print '<input type="hidden" id="printedTicketsNumber" name="printedticketsnumber" value="'.$Bbticketcounter->numberOfPrintedTickets.'">';
  4985. print '<table class="border centpercent tableforfield">';
  4986. // Type
  4987. print '<tr><td class="titlefield fieldname_type">' . $langs->trans('Type') . '</td><td class="valuefield fieldname_type">';
  4988. print $object->getLibType(2);
  4989. if ($object->module_source) {
  4990. print ' <span class="opacitymediumbycolor paddingleft">(' . $langs->trans("POS") . ' ' . ucfirst($object->module_source) . ' - ' . $langs->trans("Terminal") . ' ' . $object->pos_source . ')</span>';
  4991. }
  4992. if ($object->type == Facture::TYPE_REPLACEMENT) {
  4993. $facreplaced = new Facture($db);
  4994. $facreplaced->fetch($object->fk_facture_source);
  4995. print ' <span class="opacitymediumbycolor paddingleft">' . $langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)) . '</span>';
  4996. }
  4997. if ($object->type == Facture::TYPE_CREDIT_NOTE && !empty($object->fk_facture_source)) {
  4998. $facusing = new Facture($db);
  4999. $facusing->fetch($object->fk_facture_source);
  5000. print ' <span class="opacitymediumbycolor paddingleft">' . $langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)) . '</span>';
  5001. }
  5002. if ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && !empty($object->fk_facture_source)) {
  5003. $facusing = new Facture($db);
  5004. $facusing->fetch($object->fk_facture_source);
  5005. print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("CorrectReceipt", $facusing->getNomUrl(1)).'</span>';
  5006. }
  5007. if ($object->type == 0 && !empty($object->fk_facture_source)) {
  5008. $facusing = new Facture($db);
  5009. $facusing->fetch($object->fk_facture_source);
  5010. print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("ReplaceInvoice", $facusing->getNomUrl(1)).'</span>';
  5011. }
  5012. $facidavoir = $object->getListIdAvoirFromInvoice();
  5013. if (count($facidavoir) > 0) {
  5014. print ' <span class="opacitymediumbycolor paddingleft">' . $langs->transnoentities("InvoiceHasAvoir");
  5015. $i = 0;
  5016. foreach ($facidavoir as $id) {
  5017. if ($i == 0) {
  5018. print ' ';
  5019. } else {
  5020. print ',';
  5021. }
  5022. $facavoir = new Facture($db);
  5023. $facavoir->fetch($id);
  5024. print $facavoir->getNomUrl(1);
  5025. }
  5026. print '</span>';
  5027. }
  5028. if ($objectidnext > 0) {
  5029. $facthatreplace = new Facture($db);
  5030. $facthatreplace->fetch($objectidnext);
  5031. print ' <span class="opacitymediumbycolor paddingleft">' . str_replace('{s1}', $facthatreplace->getNomUrl(1), $langs->transnoentities("ReplacedByInvoice", '{s1}')) . '</span>';
  5032. }
  5033. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5034. $discount = new DiscountAbsolute($db);
  5035. $result = $discount->fetch(0, $object->id);
  5036. if ($result > 0) {
  5037. print ' <span class="opacitymediumbycolor paddingleft">';
  5038. $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
  5039. $s = str_replace('{s1}', $object->getLibType(0), $s);
  5040. $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
  5041. print $s;
  5042. print '</span><br>';
  5043. }
  5044. }
  5045. if ($object->fk_fac_rec_source > 0) {
  5046. $tmptemplate = new FactureRec($db);
  5047. $result = $tmptemplate->fetch($object->fk_fac_rec_source);
  5048. if ($result > 0) {
  5049. print ' <span class="opacitymediumbycolor paddingleft">';
  5050. $s = $langs->transnoentities("GeneratedFromTemplate", '{s1}');
  5051. $s = str_replace('{s1}', '<a href="' . DOL_URL_ROOT . '/compta/facture/card-rec.php?facid=' . $tmptemplate->id . '">' . dol_escape_htmltag($tmptemplate->ref) . '</a>', $s);
  5052. print $s;
  5053. print '</span>';
  5054. }
  5055. }
  5056. print '</td></tr>';
  5057. // Relative and absolute discounts
  5058. print '<!-- Discounts -->' . "\n";
  5059. print '<tr><td>' . $langs->trans('DiscountStillRemaining') . '</td>';
  5060. print '<td>';
  5061. $thirdparty = $soc;
  5062. $discount_type = 0;
  5063. $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id);
  5064. include DOL_DOCUMENT_ROOT . '/core/tpl/object_discounts.tpl.php';
  5065. print '</td></tr>';
  5066. // Date invoice
  5067. print '<tr><td>';
  5068. print '<table class="nobordernopadding centpercent"><tr><td>';
  5069. print $langs->trans('DateInvoice');
  5070. print '</td>';
  5071. if ($action != 'editinvoicedate' && !empty($object->brouillon) && $usercancreate && empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
  5072. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editinvoicedate&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  5073. }
  5074. print '</tr></table>';
  5075. print '</td><td>';
  5076. if ($action == 'editinvoicedate') {
  5077. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date, 'invoicedate');
  5078. } else {
  5079. print '<span class="valuedate">' . dol_print_date($object->date, 'day') . '</span>';
  5080. }
  5081. print '</td>';
  5082. print '</tr>';
  5083. if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
  5084. // Date invoice point of tax
  5085. print '<tr><td>';
  5086. print '<table class="nobordernopadding centpercent"><tr><td>';
  5087. print $langs->trans('DatePointOfTax');
  5088. print '</td>';
  5089. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editdate_pointoftax&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  5090. print '</tr></table>';
  5091. print '</td><td>';
  5092. if ($action == 'editdate_pointoftax') {
  5093. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_pointoftax, 'date_pointoftax');
  5094. } else {
  5095. print '<span class="valuedate">' . dol_print_date($object->date_pointoftax, 'day') . '</span>';
  5096. }
  5097. print '</td></tr>';
  5098. }
  5099. // Payment term
  5100. print '<tr><td>';
  5101. print '<table class="nobordernopadding centpercent"><tr><td>';
  5102. print $langs->trans('PaymentConditionsShort');
  5103. print '</td>';
  5104. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $action != 'editconditions' && $usercancreate) {
  5105. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editconditions&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetConditions'), 1) . '</a></td>';
  5106. }
  5107. print '</tr></table>';
  5108. print '</td><td>';
  5109. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5110. if ($action == 'editconditions') {
  5111. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id');
  5112. } else {
  5113. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none');
  5114. }
  5115. } else {
  5116. print '&nbsp;';
  5117. }
  5118. print '</td></tr>';
  5119. // Date payment term
  5120. print '<tr><td>';
  5121. print '<table class="nobordernopadding centpercent"><tr><td>';
  5122. print $langs->trans('DateMaxPayment');
  5123. print '</td>';
  5124. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $action != 'editpaymentterm' && $usercancreate) {
  5125. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editpaymentterm&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
  5126. }
  5127. print '</tr></table>';
  5128. print '</td><td>';
  5129. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5130. if ($action == 'editpaymentterm') {
  5131. $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_lim_reglement, 'paymentterm');
  5132. } else {
  5133. print '<span class="valuedate">' . dol_print_date($object->date_lim_reglement, 'day') . '</span>';
  5134. if ($object->hasDelay()) {
  5135. print img_warning($langs->trans('Late'));
  5136. }
  5137. }
  5138. } else {
  5139. print '&nbsp;';
  5140. }
  5141. print '</td></tr>';
  5142. // Payment mode
  5143. print '<tr><td>';
  5144. print '<table class="nobordernopadding centpercent"><tr><td>';
  5145. print $langs->trans('PaymentMode');
  5146. print '</td>';
  5147. if ($action != 'editmode' && $usercancreate) {
  5148. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editmode&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetMode'), 1) . '</a></td>';
  5149. }
  5150. print '</tr></table>';
  5151. print '</td><td>';
  5152. if ($action == 'editmode') {
  5153. $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
  5154. } else {
  5155. $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->mode_reglement_id, 'none', 'CRDT');
  5156. }
  5157. print '</td></tr>';
  5158. // Multicurrency
  5159. if (isModEnabled('multicurrency')) {
  5160. // Multicurrency code
  5161. print '<tr>';
  5162. print '<td>';
  5163. print '<table class="nobordernopadding centpercent"><tr><td>';
  5164. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  5165. print '</td>';
  5166. if ($usercancreate && $action != 'editmulticurrencycode' && !empty($object->brouillon)) {
  5167. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencycode&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
  5168. }
  5169. print '</tr></table>';
  5170. print '</td><td>';
  5171. $htmlname = (($usercancreate && $action == 'editmulticurrencycode') ? 'multicurrency_code' : 'none');
  5172. $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, $htmlname);
  5173. print '</td></tr>';
  5174. // Multicurrency rate
  5175. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  5176. print '<tr>';
  5177. print '<td>';
  5178. print '<table class="nobordernopadding" width="100%"><tr><td>';
  5179. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  5180. print '</td>';
  5181. if ($usercancreate && $action != 'editmulticurrencyrate' && !empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  5182. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencyrate&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
  5183. }
  5184. print '</tr></table>';
  5185. print '</td><td>';
  5186. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  5187. if ($action == 'actualizemulticurrencyrate') {
  5188. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  5189. }
  5190. $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, ($usercancreate ? 'multicurrency_tx' : 'none'), $object->multicurrency_code);
  5191. } else {
  5192. $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  5193. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  5194. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  5195. print '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=actualizemulticurrencyrate">' . $langs->trans("ActualizeCurrency") . '</a>';
  5196. print '</div>';
  5197. }
  5198. }
  5199. print '</td></tr>';
  5200. }
  5201. }
  5202. // Bank Account
  5203. if (isModEnabled("banque")) {
  5204. print '<tr><td class="nowrap">';
  5205. print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  5206. print $langs->trans('BankAccount');
  5207. print '<td>';
  5208. if (($action != 'editbankaccount') && $usercancreate) {
  5209. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editbankaccount&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->trans('SetBankAccount'), 1) . '</a></td>';
  5210. }
  5211. print '</tr></table>';
  5212. print '</td><td>';
  5213. if ($action == 'editbankaccount') {
  5214. $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_account, 'fk_account', 1);
  5215. } else {
  5216. $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_account, 'none');
  5217. }
  5218. print "</td>";
  5219. print '</tr>';
  5220. }
  5221. // Incoterms
  5222. if (isModEnabled('incoterm')) {
  5223. print '<tr><td>';
  5224. print '<table class="nobordernopadding centpercent"><tr><td>';
  5225. print $langs->trans('IncotermLabel');
  5226. print '<td><td class="right">';
  5227. if ($usercancreate) {
  5228. print '<a class="editfielda" href="' . DOL_URL_ROOT . '/compta/facture/card.php?facid=' . $object->id . '&action=editincoterm&token=' . newToken() . '">' . img_edit() . '</a>';
  5229. } else {
  5230. print '&nbsp;';
  5231. }
  5232. print '</td></tr></table>';
  5233. print '</td>';
  5234. print '<td>';
  5235. if ($action != 'editincoterm') {
  5236. print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
  5237. } else {
  5238. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'] . '?id=' . $object->id);
  5239. }
  5240. print '</td></tr>';
  5241. }
  5242. if (!empty($object->retained_warranty) || !empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  5243. $displayWarranty = true;
  5244. if (!in_array($object->type, $retainedWarrantyInvoiceAvailableType) && empty($object->retained_warranty)) {
  5245. $displayWarranty = false;
  5246. }
  5247. if ($displayWarranty) {
  5248. // Retained Warranty
  5249. print '<tr class="retained-warranty-lines" ><td>';
  5250. print '<table id="retained-warranty-table" class="nobordernopadding centpercent"><tr><td>';
  5251. print $langs->trans('RetainedWarranty');
  5252. print '</td>';
  5253. if ($action != 'editretainedwarranty' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
  5254. print '<td align="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editretainedwarranty&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('setretainedwarranty'), 1) . '</a></td>';
  5255. }
  5256. print '</tr></table>';
  5257. print '</td><td>';
  5258. if ($action == 'editretainedwarranty' && $object->statut == Facture::STATUS_DRAFT) {
  5259. print '<form id="retained-warranty-form" method="POST" action="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '">';
  5260. print '<input type="hidden" name="action" value="setretainedwarranty">';
  5261. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5262. print '<input name="retained_warranty" type="number" step="0.01" min="0" max="100" value="' . $object->retained_warranty . '" >';
  5263. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  5264. print '</form>';
  5265. } else {
  5266. print price($object->retained_warranty) . '%';
  5267. }
  5268. print '</td></tr>';
  5269. // Retained warranty payment term
  5270. print '<tr class="retained-warranty-lines" ><td>';
  5271. print '<table id="retained-warranty-cond-reglement-table" class="nobordernopadding" width="100%"><tr><td>';
  5272. print $langs->trans('PaymentConditionsShortRetainedWarranty');
  5273. print '</td>';
  5274. if ($action != 'editretainedwarrantypaymentterms' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
  5275. print '<td align="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editretainedwarrantypaymentterms&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('setPaymentConditionsShortRetainedWarranty'), 1) . '</a></td>';
  5276. }
  5277. print '</tr></table>';
  5278. print '</td><td>';
  5279. $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
  5280. if ($object->date > $defaultDate) {
  5281. $defaultDate = $object->date;
  5282. }
  5283. if ($action == 'editretainedwarrantypaymentterms' && $object->statut == Facture::STATUS_DRAFT) {
  5284. //date('Y-m-d',$object->date_lim_reglement)
  5285. print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '">';
  5286. print '<input type="hidden" name="action" value="setretainedwarrantyconditions">';
  5287. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5288. $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  5289. $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $object->retained_warranty_fk_cond_reglement;
  5290. $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  5291. print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
  5292. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  5293. print '</form>';
  5294. } else {
  5295. $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->retained_warranty_fk_cond_reglement, 'none');
  5296. if (!$displayWarranty) {
  5297. print img_picto($langs->trans('RetainedWarrantyNeed100Percent'), 'warning.png', 'class="pictowarning valignmiddle" ');
  5298. }
  5299. }
  5300. print '</td></tr>';
  5301. // Retained Warranty payment date limit
  5302. print '<tr class="retained-warranty-lines" ><td>';
  5303. print '<table id="retained-warranty-date-limit-table" class="nobordernopadding" width="100%"><tr><td>';
  5304. print $langs->trans('RetainedWarrantyDateLimit');
  5305. print '</td>';
  5306. if ($action != 'editretainedwarrantydatelimit' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
  5307. print '<td align="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editretainedwarrantydatelimit&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('setretainedwarrantyDateLimit'), 1) . '</a></td>';
  5308. }
  5309. print '</tr></table>';
  5310. print '</td><td>';
  5311. $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
  5312. if ($object->date > $defaultDate) {
  5313. $defaultDate = $object->date;
  5314. }
  5315. if ($action == 'editretainedwarrantydatelimit' && $object->statut == Facture::STATUS_DRAFT) {
  5316. //date('Y-m-d',$object->date_lim_reglement)
  5317. print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '">';
  5318. print '<input type="hidden" name="action" value="setretainedwarrantydatelimit">';
  5319. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5320. print '<input name="retained_warranty_date_limit" type="date" step="1" min="' . dol_print_date($object->date, '%Y-%m-%d') . '" value="' . dol_print_date($defaultDate, '%Y-%m-%d') . '" >';
  5321. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  5322. print '</form>';
  5323. } else {
  5324. print dol_print_date($object->retained_warranty_date_limit, 'day');
  5325. }
  5326. print '</td></tr>';
  5327. }
  5328. }
  5329. // Other attributes
  5330. $cols = 2;
  5331. include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
  5332. print '</table>';
  5333. print '</div>';
  5334. print '<div class="fichehalfright">';
  5335. print '<!-- amounts -->' . "\n";
  5336. print '<div class="underbanner clearboth"></div>' . "\n";
  5337. print '<table class="border tableforfield centpercent">';
  5338. $sign = 1;
  5339. if (!empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE_SCREEN) && $object->type == $object::TYPE_CREDIT_NOTE) {
  5340. $sign = -1; // We invert sign for output
  5341. }
  5342. if (!empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE_SCREEN) && $object->type == $object::TYPE_RECEIPT_CREDIT_NOTE) {
  5343. $sign = -1; // We invert sign for output
  5344. }
  5345. if (isModEnabled('multicurrency') && ($object->multicurrency_code != $conf->currency)) {
  5346. // Multicurrency Amount HT
  5347. print '<tr><td class="titlefieldmiddle">' . $form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0) . '</td>';
  5348. print '<td class="nowrap right amountcard">' . price($sign * $object->multicurrency_total_ht, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  5349. print '</tr>';
  5350. // Multicurrency Amount VAT
  5351. print '<tr><td>' . $form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0) . '</td>';
  5352. print '<td class="nowrap right amountcard">' . price($sign * $object->multicurrency_total_tva, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  5353. print '</tr>';
  5354. // Multicurrency Amount TTC
  5355. print '<tr><td>' . $form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0) . '</td>';
  5356. print '<td class="nowrap right amountcard">' . price($sign * $object->multicurrency_total_ttc, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
  5357. print '</tr>';
  5358. }
  5359. // Amount
  5360. print '<tr><td class="titlefieldmiddle">' . $langs->trans('AmountHT') . '</td>';
  5361. print '<td class="nowrap right amountcard">' . price($sign * $object->total_ht, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5362. // Vat
  5363. print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td colspan="3" class="nowrap right amountcard">' . price($sign * $object->total_tva, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5364. print '</tr>';
  5365. // Amount Local Taxes
  5366. if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1
  5367. print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
  5368. print '<td class="nowrap right amountcard">' . price($sign * $object->total_localtax1, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5369. }
  5370. if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2
  5371. print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
  5372. print '<td class="nowrap right amountcard">' . price($sign * $object->total_localtax2, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5373. }
  5374. // Revenue stamp
  5375. if ($selleruserevenustamp) { // Test company use revenue stamp
  5376. print '<tr><td>';
  5377. print '<table class="nobordernopadding" width="100%"><tr><td>';
  5378. print $langs->trans('RevenueStamp');
  5379. print '</td>';
  5380. if ($action != 'editrevenuestamp' && !empty($object->brouillon) && $usercancreate) {
  5381. print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editrevenuestamp&token=' . newToken() . '&facid=' . $object->id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '</a></td>';
  5382. }
  5383. print '</tr></table>';
  5384. print '</td><td>';
  5385. if ($action == 'editrevenuestamp') {
  5386. print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
  5387. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5388. print '<input type="hidden" name="action" value="setrevenuestamp">';
  5389. print '<input type="hidden" name="revenuestamp" id="revenuestamp_val" value="' . price2num($object->revenuestamp) . '">';
  5390. print $formother->select_revenue_stamp('', 'revenuestamp_type', $mysoc->country_code);
  5391. print ' &rarr; <span id="revenuestamp_span"></span>';
  5392. print ' <input type="submit" class="button buttongen button-save" value="' . $langs->trans('Modify') . '">';
  5393. print '</form>';
  5394. print " <script>
  5395. $(document).ready(function(){
  5396. js_recalculate_revenuestamp();
  5397. $('select[name=revenuestamp_type]').on('change',function(){
  5398. js_recalculate_revenuestamp();
  5399. });
  5400. });
  5401. function js_recalculate_revenuestamp(){
  5402. var valselected = $('select[name=revenuestamp_type]').val();
  5403. console.log('Calculate revenue stamp from '+valselected);
  5404. var revenue = 0;
  5405. if (valselected.indexOf('%') == -1)
  5406. {
  5407. revenue = valselected;
  5408. }
  5409. else
  5410. {
  5411. var revenue_type = parseFloat(valselected);
  5412. var amount_net = " . round($object->total_ht, 2) . ";
  5413. revenue = revenue_type * amount_net / 100;
  5414. revenue = revenue.toFixed(2);
  5415. }
  5416. $('#revenuestamp_val').val(revenue);
  5417. $('#revenuestamp_span').html(revenue);
  5418. }
  5419. </script>";
  5420. } else {
  5421. print price($object->revenuestamp, 1, '', 1, -1, -1, $conf->currency);
  5422. }
  5423. print '</td></tr>';
  5424. }
  5425. // Total with tax
  5426. print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td class="nowrap right amountcard">' . price($sign * $object->total_ttc, 1, '', 1, -1, -1, $conf->currency) . '</td></tr>';
  5427. print '</table>';
  5428. $nbrows = 8;
  5429. $nbcols = 3;
  5430. if (isModEnabled('project')) {
  5431. $nbrows++;
  5432. }
  5433. if (isModEnabled("banque")) {
  5434. $nbrows++;
  5435. $nbcols++;
  5436. }
  5437. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) {
  5438. $nbrows++;
  5439. }
  5440. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) {
  5441. $nbrows++;
  5442. }
  5443. if ($selleruserevenustamp) {
  5444. $nbrows++;
  5445. }
  5446. if (isModEnabled('multicurrency')) {
  5447. $nbrows += 5;
  5448. }
  5449. if (isModEnabled('incoterm')) {
  5450. $nbrows += 1;
  5451. }
  5452. // List of previous situation invoices
  5453. if (($object->situation_cycle_ref > 0) && !empty($conf->global->INVOICE_USE_SITUATION)) {
  5454. print '<!-- List of situation invoices -->';
  5455. print '<table class="noborder situationstable" width="100%">';
  5456. print '<tr class="liste_titre">';
  5457. print '<td>' . $langs->trans('ListOfSituationInvoices') . '</td>';
  5458. print '<td></td>';
  5459. print '<td class="center">' . $langs->trans('Situation') . '</td>';
  5460. if (isModEnabled("banque")) {
  5461. print '<td class="right"></td>';
  5462. }
  5463. print '<td class="right">' . $langs->trans('AmountHT') . '</td>';
  5464. print '<td class="right">' . $langs->trans('AmountTTC') . '</td>';
  5465. print '<td width="18">&nbsp;</td>';
  5466. print '</tr>';
  5467. $total_prev_ht = $total_prev_ttc = 0;
  5468. $total_global_ht = $total_global_ttc = 0;
  5469. if (count($object->tab_previous_situation_invoice) > 0) {
  5470. // List of previous invoices
  5471. $current_situation_counter = array();
  5472. foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
  5473. $tmptotalpaidforthisinvoice = $prev_invoice->getSommePaiement();
  5474. $total_prev_ht += $prev_invoice->total_ht;
  5475. $total_prev_ttc += $prev_invoice->total_ttc;
  5476. $current_situation_counter[] = (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE || $prev_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? -1 : 1) * $prev_invoice->situation_counter;
  5477. print '<tr class="oddeven">';
  5478. print '<td>' . $prev_invoice->getNomUrl(1) . '</td>';
  5479. print '<td></td>';
  5480. print '<td align="center" >' . (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE || $prev_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')) . $prev_invoice->situation_counter . '</td>';
  5481. if (isModEnabled("banque")) {
  5482. print '<td class="right"></td>';
  5483. }
  5484. print '<td class="right"><span class="amount">' . price($prev_invoice->total_ht) . '</span></td>';
  5485. print '<td class="right"><span class="amount">' . price($prev_invoice->total_ttc) . '</span></td>';
  5486. print '<td class="right">' . $prev_invoice->getLibStatut(3, $tmptotalpaidforthisinvoice) . '</td>';
  5487. print '</tr>';
  5488. }
  5489. }
  5490. $total_global_ht += $total_prev_ht;
  5491. $total_global_ttc += $total_prev_ttc;
  5492. $total_global_ht += $object->total_ht;
  5493. $total_global_ttc += $object->total_ttc;
  5494. $current_situation_counter[] = (($object->type == Facture::TYPE_CREDIT_NOTE || $prev_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? -1 : 1) * $object->situation_counter;
  5495. print '<tr class="oddeven">';
  5496. print '<td>' . $object->getNomUrl(1) . '</td>';
  5497. print '<td></td>';
  5498. print '<td class="center">' . (($object->type == Facture::TYPE_CREDIT_NOTE || $prev_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')) . $object->situation_counter . '</td>';
  5499. if (isModEnabled("banque")) {
  5500. print '<td class="right"></td>';
  5501. }
  5502. print '<td class="right"><span class="amount">' . price($object->total_ht) . '</span></td>';
  5503. print '<td class="right"><span class="amount">' . price($object->total_ttc) . '</span></td>';
  5504. print '<td class="right">' . $object->getLibStatut(3, $object->getSommePaiement()) . '</td>';
  5505. print '</tr>';
  5506. print '<tr class="oddeven">';
  5507. print '<td colspan="2" class="left"><b>' . $langs->trans('CurrentSituationTotal') . '</b></td>';
  5508. print '<td>';
  5509. $i = 0;
  5510. foreach ($current_situation_counter as $sit) {
  5511. $curSign = $sit > 0 ? '+' : '-';
  5512. $curType = $sit > 0 ? $langs->trans('situationInvoiceShortcode_S') : $langs->trans('situationInvoiceShortcode_AS');
  5513. if ($i > 0) {
  5514. print ' ' . $curSign . ' ';
  5515. }
  5516. print $curType . abs($sit);
  5517. $i++;
  5518. }
  5519. print '</td>';
  5520. if (isModEnabled("banque")) {
  5521. print '<td></td>';
  5522. }
  5523. print '<td class="right"><b>' . price($total_global_ht) . '</b></td>';
  5524. print '<td class="right"><b>' . price($total_global_ttc) . '</b></td>';
  5525. print '<td width="18">&nbsp;</td>';
  5526. print '</tr>';
  5527. if (count($object->tab_next_situation_invoice) > 0) {
  5528. // List of next invoices
  5529. /*print '<tr class="liste_titre">';
  5530. print '<td>' . $langs->trans('ListOfNextSituationInvoices') . '</td>';
  5531. print '<td></td>';
  5532. print '<td></td>';
  5533. if (isModEnabled('banque')) print '<td class="right"></td>';
  5534. print '<td class="right">' . $langs->trans('AmountHT') . '</td>';
  5535. print '<td class="right">' . $langs->trans('AmountTTC') . '</td>';
  5536. print '<td width="18">&nbsp;</td>';
  5537. print '</tr>';*/
  5538. $total_next_ht = $total_next_ttc = 0;
  5539. foreach ($object->tab_next_situation_invoice as $next_invoice) {
  5540. $totalpaid = $next_invoice->getSommePaiement();
  5541. $total_next_ht += $next_invoice->total_ht;
  5542. $total_next_ttc += $next_invoice->total_ttc;
  5543. print '<tr class="oddeven">';
  5544. print '<td>' . $next_invoice->getNomUrl(1) . '</td>';
  5545. print '<td></td>';
  5546. print '<td class="center">' . (($next_invoice->type == Facture::TYPE_CREDIT_NOTE || $next_invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')) . $next_invoice->situation_counter . '</td>';
  5547. if (isModEnabled("banque")) {
  5548. print '<td class="right"></td>';
  5549. }
  5550. print '<td class="right"><span class="amount">' . price($next_invoice->total_ht) . '</span></td>';
  5551. print '<td class="right"><span class="amount">' . price($next_invoice->total_ttc) . '</span></td>';
  5552. print '<td class="right">' . $next_invoice->getLibStatut(3, $totalpaid) . '</td>';
  5553. print '</tr>';
  5554. }
  5555. $total_global_ht += $total_next_ht;
  5556. $total_global_ttc += $total_next_ttc;
  5557. print '<tr class="oddeven">';
  5558. print '<td colspan="3" class="right"></td>';
  5559. if (isModEnabled("banque")) {
  5560. print '<td class="right"></td>';
  5561. }
  5562. print '<td class="right"><b>' . price($total_global_ht) . '</b></td>';
  5563. print '<td class="right"><b>' . price($total_global_ttc) . '</b></td>';
  5564. print '<td width="18">&nbsp;</td>';
  5565. print '</tr>';
  5566. }
  5567. print '</table>';
  5568. }
  5569. $sign = 1;
  5570. if ($object->type == $object::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5571. $sign = -1;
  5572. }
  5573. // List of payments already done
  5574. print '<!-- List of payments already done -->';
  5575. print '<div class="div-table-responsive-no-min">';
  5576. print '<table class="noborder paymenttable centpercent">';
  5577. print '<tr class="liste_titre">';
  5578. print '<td class="liste_titre">' . ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '</td>';
  5579. print '<td class="liste_titre"><span class="hideonsmartphone">' . $langs->trans('Date') . '</span></td>';
  5580. print '<td class="liste_titre"><span class="hideonsmartphone">' . $langs->trans('Type') . '</span></td>';
  5581. if (isModEnabled("banque")) {
  5582. print '<td class="liste_titre"><span class="hideonsmartphone">' . $langs->trans('BankAccount') . '</span></td>';
  5583. }
  5584. print '<td class="liste_titre right">' . $langs->trans('Amount') . '</td>';
  5585. print '<td class="liste_titre" width="18">&nbsp;</td>';
  5586. print '</tr>';
  5587. // Payments already done (from payment on this invoice)
  5588. $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
  5589. $sql .= ' c.code as payment_code, c.libelle as payment_label,';
  5590. $sql .= ' pf.amount,';
  5591. $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal, ba.currency_code as bacurrency_code';
  5592. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p';
  5593. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_paiement as c ON p.fk_paiement = c.id';
  5594. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid';
  5595. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid';
  5596. $sql .= ' WHERE pf.fk_facture = ' . ((int) $object->id) . ' AND pf.fk_paiement = p.rowid';
  5597. $sql .= ' AND p.entity IN (' . getEntity('invoice') . ')';
  5598. $sql .= ' ORDER BY p.datep, p.tms';
  5599. $result = $db->query($sql);
  5600. if ($result) {
  5601. $num = $db->num_rows($result);
  5602. $i = 0;
  5603. if ($num > 0) {
  5604. while ($i < $num) {
  5605. $objp = $db->fetch_object($result);
  5606. $paymentstatic->id = $objp->rowid;
  5607. $paymentstatic->datepaye = $db->jdate($objp->dp);
  5608. $paymentstatic->ref = $objp->ref;
  5609. $paymentstatic->num_payment = $objp->num_payment;
  5610. $paymentstatic->paiementcode = $objp->payment_code;
  5611. print '<tr class="oddeven"><td class="nowraponall">';
  5612. print $paymentstatic->getNomUrl(1);
  5613. print '</td>';
  5614. print '<td>';
  5615. $dateofpayment = $db->jdate($objp->dp);
  5616. $tmparray = dol_getdate($dateofpayment);
  5617. if ($tmparray['seconds'] == 0 && $tmparray['minutes'] == 0 && ($tmparray['hours'] == 0 || $tmparray['hours'] == 12)) { // We set hours to 0:00 or 12:00 because we don't know it
  5618. print dol_print_date($dateofpayment, 'day');
  5619. } else { // Hours was set to real date of payment (special case for POS for example)
  5620. print dol_print_date($dateofpayment, 'dayhour', 'tzuser');
  5621. }
  5622. print '</td>';
  5623. $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label;
  5624. print '<td>' . $label . ' ' . $objp->num_payment . '</td>';
  5625. if (isModEnabled("banque")) {
  5626. $bankaccountstatic->id = $objp->baid;
  5627. $bankaccountstatic->ref = $objp->baref;
  5628. $bankaccountstatic->label = $objp->baref;
  5629. $bankaccountstatic->number = $objp->banumber;
  5630. $bankaccountstatic->currency_code = $objp->bacurrency_code;
  5631. if (isModEnabled('accounting')) {
  5632. $bankaccountstatic->account_number = $objp->account_number;
  5633. $accountingjournal = new AccountingJournal($db);
  5634. $accountingjournal->fetch($objp->fk_accountancy_journal);
  5635. $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
  5636. }
  5637. print '<td class="nowraponall">';
  5638. if ($bankaccountstatic->id) {
  5639. print $bankaccountstatic->getNomUrl(1, 'transactions');
  5640. }
  5641. print '</td>';
  5642. }
  5643. print '<td class="right"><span class="amount">' . price($sign * $objp->amount) . '</span></td>';
  5644. print '<td class="center">';
  5645. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) {
  5646. print '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=deletepayment&token=' . newToken() . '&paiement_id=' . $objp->rowid . '">';
  5647. print img_delete();
  5648. print '</a>';
  5649. }
  5650. print '</td>';
  5651. print '</tr>';
  5652. $i++;
  5653. }
  5654. }
  5655. $db->free($result);
  5656. } else {
  5657. dol_print_error($db);
  5658. }
  5659. if ($object->type != Facture::TYPE_CREDIT_NOTE || $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5660. // Total already paid
  5661. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5662. print '<span class="opacitymedium">';
  5663. if ($object->type != Facture::TYPE_DEPOSIT) {
  5664. print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
  5665. } else {
  5666. print $langs->trans('AlreadyPaid');
  5667. }
  5668. print '</span></td><td class="right' . (($totalpaid > 0) ? ' amountalreadypaid' : '') . '">' . price($totalpaid) . '</td><td>&nbsp;</td></tr>';
  5669. $resteapayeraffiche = $resteapayer;
  5670. $cssforamountpaymentcomplete = 'amountpaymentcomplete';
  5671. // Loop on each credit note or deposit amount applied
  5672. $creditnoteamount = 0;
  5673. $depositamount = 0;
  5674. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  5675. $sql .= " re.description, re.fk_facture_source";
  5676. $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re";
  5677. $sql .= " WHERE fk_facture = " . ((int) $object->id);
  5678. $resql = $db->query($sql);
  5679. if ($resql) {
  5680. $num = $db->num_rows($resql);
  5681. $i = 0;
  5682. $invoice = new Facture($db);
  5683. while ($i < $num) {
  5684. $obj = $db->fetch_object($resql);
  5685. $invoice->fetch($obj->fk_facture_source);
  5686. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5687. print '<span class="opacitymedium">';
  5688. if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
  5689. print $langs->trans("CreditNote") . ' ';
  5690. }
  5691. if ($invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5692. print $langs->trans("ReceiptCreditNote").' ';
  5693. }
  5694. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  5695. print $langs->trans("Deposit") . ' ';
  5696. }
  5697. print $invoice->getNomUrl(0);
  5698. print '</span>';
  5699. print '</td>';
  5700. print '<td class="right"><span class="amount">' . price($obj->amount_ttc) . '</span></td>';
  5701. print '<td class="right">';
  5702. print '<a href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=unlinkdiscount&token=' . newToken() . '&discountid=' . $obj->rowid . '">' . img_delete() . '</a>';
  5703. print '</td></tr>';
  5704. $i++;
  5705. if ($invoice->type == Facture::TYPE_CREDIT_NOTE || $invoice->type == Facture::TYPE_RECEIPT_CREDIT_NOTE) {
  5706. $creditnoteamount += $obj->amount_ttc;
  5707. }
  5708. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  5709. $depositamount += $obj->amount_ttc;
  5710. }
  5711. }
  5712. } else {
  5713. dol_print_error($db);
  5714. }
  5715. // Paye partiellement 'escompte'
  5716. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
  5717. print '<tr><td colspan="' . $nbcols . '" class="nowrap right">';
  5718. print '<span class="opacitymedium">';
  5719. print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), -1);
  5720. print '</span>';
  5721. print '</td><td class="right"><span class="amount">' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')) . '</span></td><td>&nbsp;</td></tr>';
  5722. $resteapayeraffiche = 0;
  5723. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5724. }
  5725. // Paye partiellement ou Abandon 'badcustomer'
  5726. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') {
  5727. print '<tr><td colspan="' . $nbcols . '" class="nowrap right">';
  5728. print '<span class="opacitymedium">';
  5729. print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), -1);
  5730. print '</span>';
  5731. print '</td><td class="right">' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')) . '</td><td>&nbsp;</td></tr>';
  5732. // $resteapayeraffiche=0;
  5733. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5734. }
  5735. // Paye partiellement ou Abandon 'product_returned'
  5736. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
  5737. print '<tr><td colspan="' . $nbcols . '" class="nowrap right">';
  5738. print '<span class="opacitymedium">';
  5739. print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), -1);
  5740. print '</span>';
  5741. print '</td><td class="right"><span class="amount">' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')) . '</span></td><td>&nbsp;</td></tr>';
  5742. $resteapayeraffiche = 0;
  5743. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5744. }
  5745. // Paye partiellement ou Abandon 'abandon'
  5746. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') {
  5747. print '<tr><td colspan="' . $nbcols . '" class="nowrap right">';
  5748. $text = $langs->trans("HelpAbandonOther");
  5749. if ($object->close_note) {
  5750. $text .= '<br><br><b>' . $langs->trans("Reason") . '</b>:' . $object->close_note;
  5751. }
  5752. print '<span class="opacitymedium">';
  5753. print $form->textwithpicto($langs->trans("Abandoned"), $text, -1);
  5754. print '</span>';
  5755. print '</td><td class="right"><span class="amount">' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')) . '</span></td><td>&nbsp;</td></tr>';
  5756. $resteapayeraffiche = 0;
  5757. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5758. }
  5759. // Billed
  5760. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5761. print '<span class="opacitymedium">';
  5762. print $langs->trans("Billed");
  5763. print '</td><td class="right">' . price($object->total_ttc) . '</td><td>&nbsp;</td></tr>';
  5764. // Remainder to pay
  5765. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5766. print '<span class="opacitymedium">';
  5767. print $langs->trans('RemainderToPay');
  5768. if ($resteapayeraffiche < 0) {
  5769. print ' (' . $langs->trans('NegativeIfExcessReceived') . ')';
  5770. }
  5771. print '</span>';
  5772. print '</td>';
  5773. print '<td class="right' . ($resteapayeraffiche ? ' amountremaintopay' : (' ' . $cssforamountpaymentcomplete)) . '">' . price($resteapayeraffiche) . '</td><td>&nbsp;</td></tr>';
  5774. // Remainder to pay Multicurrency
  5775. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  5776. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5777. print '<span class="opacitymedium">';
  5778. print $langs->trans('RemainderToPayMulticurrency');
  5779. if ($resteapayeraffiche < 0) {
  5780. print ' (' . $langs->trans('NegativeIfExcessReceived') . ')';
  5781. }
  5782. print '</span>';
  5783. print '</td>';
  5784. print '<td class="right' . ($resteapayeraffiche ? ' amountremaintopay' : (' ' . $cssforamountpaymentcomplete)) . '">';
  5785. //print (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code).' ';
  5786. print price(price2num($object->multicurrency_tx * $resteapayeraffiche, 'MT'), 1, $langs, 1, -1, -1, (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code)) . '</td><td>&nbsp;</td></tr>';
  5787. }
  5788. // Retained warranty : usualy use on construction industry
  5789. if (!empty($object->situation_final) && !empty($object->retained_warranty) && $displayWarranty) {
  5790. // Billed - retained warranty
  5791. if ($object->type == Facture::TYPE_SITUATION) {
  5792. $retainedWarranty = $total_global_ttc * $object->retained_warranty / 100;
  5793. } else {
  5794. // Because one day retained warranty could be used on standard invoices
  5795. $retainedWarranty = $object->total_ttc * $object->retained_warranty / 100;
  5796. }
  5797. $billedWithRetainedWarranty = $object->total_ttc - $retainedWarranty;
  5798. print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("ToPayOn", dol_print_date($object->date_lim_reglement, 'day')) . ' :</td><td align="right">' . price($billedWithRetainedWarranty) . '</td><td>&nbsp;</td></tr>';
  5799. // retained warranty
  5800. print '<tr><td colspan="' . $nbcols . '" align="right">';
  5801. print $langs->trans("RetainedWarranty") . ' (' . $object->retained_warranty . '%)';
  5802. print !empty($object->retained_warranty_date_limit) ? ' ' . $langs->trans("ToPayOn", dol_print_date($object->retained_warranty_date_limit, 'day')) : '';
  5803. print ' :</td><td align="right">' . price($retainedWarranty) . '</td><td>&nbsp;</td></tr>';
  5804. }
  5805. } else { // Credit note
  5806. $resteapayeraffiche = $resteapayer;
  5807. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  5808. // Total already paid back
  5809. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5810. print '<span class="opacitymedium">' . $langs->trans('AlreadyPaidBack') . '</span>';
  5811. print '</td><td class="right"><span class="amount">' . price($sign * $totalpaid) . '</span></td><td>&nbsp;</td></tr>';
  5812. // Billed
  5813. print '<tr><td colspan="' . $nbcols . '" class="right"><span class="opacitymedium">' . $langs->trans("Billed") . '</span></td><td class="right">' . price($sign * $object->total_ttc) . '</td><td>&nbsp;</td></tr>';
  5814. // Remainder to pay back
  5815. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5816. print '<span class="opacitymedium">' . $langs->trans('RemainderToPayBack');
  5817. if ($resteapayeraffiche > 0) {
  5818. print ' (' . $langs->trans('NegativeIfExcessRefunded') . ')';
  5819. }
  5820. print '</span></td>';
  5821. print '<td class="right' . ($resteapayeraffiche ? ' amountremaintopayback' : (' ' . $cssforamountpaymentcomplete)) . '">' . price($sign * $resteapayeraffiche) . '</td>';
  5822. print '<td class="nowrap">&nbsp;</td></tr>';
  5823. // Remainder to pay back Multicurrency
  5824. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  5825. print '<tr><td colspan="' . $nbcols . '" class="right">';
  5826. print '<span class="opacitymedium">' . $langs->trans('RemainderToPayBackMulticurrency');
  5827. if ($resteapayeraffiche > 0) {
  5828. print ' (' . $langs->trans('NegativeIfExcessRefunded') . ')';
  5829. }
  5830. print '</span>';
  5831. print '</td>';
  5832. print '<td class="right' . ($resteapayeraffiche ? ' amountremaintopayback' : (' ' . $cssforamountpaymentcomplete)) . '">' . (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency) . ' ' . price(price2num($sign * $object->multicurrency_tx * $resteapayeraffiche, 'MT')) . '</td><td>&nbsp;</td></tr>';
  5833. }
  5834. // Sold credit note
  5835. // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
  5836. // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
  5837. // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
  5838. }
  5839. print '</table>';
  5840. print '</div>';
  5841. // Margin Infos
  5842. if (isModEnabled('margin')) {
  5843. $formmargin->displayMarginInfos($object);
  5844. }
  5845. print '</div>';
  5846. print '</div>';
  5847. print '<div class="clearboth"></div><br><br>';
  5848. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  5849. $blocname = 'contacts';
  5850. $title = $langs->trans('ContactsAddresses');
  5851. include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
  5852. }
  5853. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  5854. $blocname = 'notes';
  5855. $title = $langs->trans('Notes');
  5856. include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
  5857. }
  5858. // Get object lines
  5859. $result = $object->getLinesArray();
  5860. // Add products/services form
  5861. //$forceall = 1;
  5862. global $inputalsopricewithtax;
  5863. $inputalsopricewithtax = 1;
  5864. // Show global modifiers for situation invoices
  5865. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  5866. if ($object->situation_cycle_ref && $object->statut == 0) {
  5867. print '<!-- Area to change globally the situation percent -->' . "\n";
  5868. print '<div class="div-table-responsive">';
  5869. print '<form name="updatealllines" id="updatealllines" action="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '#updatealllines" method="POST">';
  5870. print '<input type="hidden" name="token" value="' . newToken() . '" />';
  5871. print '<input type="hidden" name="action" value="updatealllines" />';
  5872. print '<input type="hidden" name="id" value="' . $object->id . '" />';
  5873. print '<table id="tablelines_all_progress" class="noborder noshadow" width="100%">';
  5874. print '<tr class="liste_titre nodrag nodrop">';
  5875. // Adds a line numbering column
  5876. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  5877. print '<td align="center" width="5">&nbsp;</td>';
  5878. }
  5879. print '<td class="minwidth500imp">' . $langs->trans('ModifyAllLines') . '</td>';
  5880. print '<td class="right">' . $langs->trans('Progress') . '</td>';
  5881. print '<td>&nbsp;</td>';
  5882. print "</tr>\n";
  5883. print '<tr class="nodrag nodrop">';
  5884. // Adds a line numbering column
  5885. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  5886. print '<td align="center" width="5">&nbsp;</td>';
  5887. }
  5888. print '<td>&nbsp;</td>';
  5889. print '<td class="nowrap right"><input type="text" size="1" value="" name="all_progress">%</td>';
  5890. print '<td class="right"><input type="submit" class="button" name="all_percent" value="Modifier" /></td>';
  5891. print '</tr>';
  5892. print '</table>';
  5893. print '</form>';
  5894. print '</div>';
  5895. }
  5896. }
  5897. print ' <form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">
  5898. <input type="hidden" name="token" value="' . newToken() . '">
  5899. <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline') . '">
  5900. <input type="hidden" name="mode" value="">
  5901. <input type="hidden" name="page_y" value="">
  5902. <input type="hidden" name="id" value="' . $object->id . '">
  5903. ';
  5904. if (!empty($conf->use_javascript_ajax) && $object->statut == 0) {
  5905. include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
  5906. }
  5907. print '<div class="div-table-responsive-no-min">';
  5908. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  5909. // Show object lines
  5910. $objectCount = count($object->lines);
  5911. if (!empty($object->lines)) {
  5912. $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
  5913. }
  5914. //if ($objectCount < 1) {
  5915. // Form to add new line
  5916. if ($object->statut == 0 && $usercancreate && $action != 'valid' && $action != 'editline') {
  5917. if ($action != 'editline' && $action != 'selectlines') {
  5918. // Add free products/services
  5919. $parameters = array();
  5920. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  5921. if ($reshook < 0)
  5922. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  5923. if (empty($reshook))
  5924. $object->formAddObjectLine(1, $mysoc, $soc);
  5925. }
  5926. }
  5927. //}
  5928. print "</table>\n";
  5929. print "</div>";
  5930. print "</form>\n";
  5931. print dol_get_fiche_end();
  5932. // Actions buttons
  5933. if ($action != 'prerelance' && $action != 'presend' && $action != 'valid' && $action != 'editline') {
  5934. print '<div class="tabsAction">';
  5935. $parameters = array();
  5936. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  5937. if (empty($reshook)) {
  5938. $params = array(
  5939. 'attr' => array(
  5940. 'class' => 'classfortooltip'
  5941. )
  5942. );
  5943. // Editer une facture deja validee, sans paiement effectue et pas exporte en compta
  5944. if ($object->statut == Facture::STATUS_VALIDATED) {
  5945. // We check if lines of invoice are not already transfered into accountancy
  5946. $ventilExportCompta = $object->getVentilExportCompta();
  5947. if ($ventilExportCompta == 0) {
  5948. if (!empty($conf->global->INVOICE_CAN_BE_EDITED_EVEN_IF_PAYMENT_DONE) || ($resteapayer == price2num($object->total_ttc, 'MT', 1) && empty($object->paye))) {
  5949. if (!$objectidnext && $object->is_last_in_cycle()) {
  5950. if ($usercanunvalidate) {
  5951. print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=modif&token=' . newToken(), '', true, $params);
  5952. } else {
  5953. $params['attr']['title'] = $langs->trans('NotEnoughPermissions');
  5954. print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=modif&token=' . newToken(), '', false, $params);
  5955. }
  5956. } elseif (!$object->is_last_in_cycle()) {
  5957. $params['attr']['title'] = $langs->trans('NotLastInCycle');
  5958. print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
  5959. } else {
  5960. $params['attr']['title'] = $langs->trans('DisabledBecauseReplacedInvoice');
  5961. print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
  5962. }
  5963. }
  5964. } else {
  5965. $params['attr']['title'] = $langs->trans('DisabledBecauseDispatchedInBookkeeping');
  5966. print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
  5967. }
  5968. }
  5969. $discount = new DiscountAbsolute($db);
  5970. $result = $discount->fetch(0, $object->id);
  5971. /** **************************************************************************************
  5972. *
  5973. * NTAK BUTTONS
  5974. *
  5975. ************************************************************************************** */
  5976. if ($conf->ntak->enabled && $object->statut == Facture::STATUS_CLOSED) {
  5977. // send ntak button
  5978. if (empty($object->array_options['options_ntak_id']) || $object->array_options['options_ntak_status'] == NtakConst::INVOICE_SENDING_RESPONSE_STATUS_SEND_AGAIN) {
  5979. print dolGetButtonAction($langs->trans('NtakSendBtn'), '', 'default', $_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=sendntak&token='.newToken(), '', true, $params);
  5980. }
  5981. // get ntak status button
  5982. if (in_array($object->array_options['options_ntak_status'], [NtakConst::INVOICE_SENDING_RESPONSE_STATUS_ACCEPTED, NtakConst::INVOICE_SENDING_RESPONSE_STATUS_SEND_AGAIN])) {
  5983. print dolGetButtonAction($langs->trans('NtakGetStatusBtn'), '', 'default', $_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=getntakstatus&token='.newToken(), '', true, $params);
  5984. }
  5985. }
  5986. /** **************************************************************************************
  5987. *
  5988. * /NTAK BUTTONS
  5989. *
  5990. ************************************************************************************** */
  5991. // Reopen an invoice
  5992. if (
  5993. (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_RECEIPT)
  5994. || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id))
  5995. || ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && empty($discount->id))
  5996. || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id))
  5997. || ($object->type == Facture::TYPE_SITUATION && empty($discount->id)))
  5998. && ($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data
  5999. && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || $usercanreopen)
  6000. ) { // A paid invoice (partially or completely)
  6001. if ($object->close_code != 'replaced' || (!$objectidnext)) { // Not replaced by another invoice or replaced but the replacement invoice has been deleted
  6002. print dolGetButtonAction($langs->trans('ReOpen'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=reopen&token=' . newToken(), '', true, $params);
  6003. } else {
  6004. $params['attr']['title'] = $langs->trans("DisabledBecauseReplacedInvoice");
  6005. print dolGetButtonAction($langs->trans('ReOpen'), '', 'default', '#', '', false, $params);
  6006. }
  6007. }
  6008. // Create contract
  6009. if (!empty($conf->global->CONTRACT_CREATE_FROM_INVOICE)) {
  6010. if (isModEnabled('contrat') && $object->statut == Facture::STATUS_VALIDATED) {
  6011. $langs->load("contracts");
  6012. if ($usercancreatecontract) {
  6013. print '<a class="butAction" href="' . DOL_URL_ROOT . '/contrat/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '">' . $langs->trans('AddContract') . '</a>';
  6014. }
  6015. }
  6016. }
  6017. // Validate
  6018. if ($object->statut == Facture::STATUS_DRAFT && 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) || ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->total_ttc <= 0))) {
  6019. if ($usercanvalidate) {
  6020. print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=valid&token=' . newToken(), '', true, $params);
  6021. }
  6022. }
  6023. // Send by mail
  6024. if (empty($user->socid)) {
  6025. if (($object->statut == Facture::STATUS_VALIDATED || $object->statut == Facture::STATUS_CLOSED) || !empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) {
  6026. if ($objectidnext) {
  6027. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('SendMail') . '</span>';
  6028. } else {
  6029. if ($usercansend) {
  6030. print dolGetButtonAction('', $langs->trans('SendMail'), 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&action=presend&mode=init#formmailbeforetitle', '', true, $params);
  6031. } else {
  6032. print dolGetButtonAction('', $langs->trans('SendMail'), 'default', '#', '', false, $params);
  6033. }
  6034. }
  6035. }
  6036. }
  6037. // Request a direct debit order
  6038. if ($object->statut > Facture::STATUS_DRAFT && $object->paye == 0 && $num == 0) {
  6039. if ($resteapayer > 0) {
  6040. if ($usercancreatewithdrarequest) {
  6041. if (!$objectidnext && $object->close_code != 'replaced') { // Not replaced by another invoice
  6042. print '<a class="butAction" href="' . DOL_URL_ROOT . '/compta/facture/prelevement.php?facid=' . $object->id . '" title="' . dol_escape_htmltag($langs->trans("MakeWithdrawRequest")) . '">' . $langs->trans("MakeWithdrawRequest") . '</a>';
  6043. } else {
  6044. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('MakeWithdrawRequest') . '</span>';
  6045. }
  6046. } else {
  6047. //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  6048. }
  6049. } else {
  6050. //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("AmountMustBePositive")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  6051. }
  6052. }
  6053. // POS Ticket
  6054. if (isModEnabled('takepos') && $object->module_source == 'takepos') {
  6055. $langs->load("cashdesk");
  6056. $receipt_url = DOL_URL_ROOT . "/takepos/receipt.php";
  6057. print '<a target="_blank" rel="noopener noreferrer" class="butAction" href="' . $receipt_url . '?facid=' . ((int) $object->id) . '">' . $langs->trans('POSTicket') . '</a>';
  6058. }
  6059. // Create payment
  6060. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercanissuepayment) {
  6061. if ($objectidnext) {
  6062. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('DoPayment') . '</span>';
  6063. } else {
  6064. if ($object->type == Facture::TYPE_DEPOSIT && $resteapayer == 0) {
  6065. // For down payment, we refuse to receive more than amount to pay.
  6066. $params['attr']['title'] = $langs->trans('DisabledBecauseRemainderToPayIsZero');
  6067. print dolGetButtonAction($langs->trans('DoPayment'), '', 'default', '#', '', false, $params);
  6068. } else {
  6069. // Sometimes we can receive more, so we accept to enter more and will offer a button to convert into discount (but it is not a credit note, just a prepayment done)
  6070. //print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPayment').'</a>';
  6071. print dolGetButtonAction($langs->trans('DoPayment'), '', 'default', DOL_URL_ROOT . '/compta/paiement.php?facid=' . $object->id . '&amp;action=create&amp;accountid=' . $object->fk_account, '', true, $params);
  6072. }
  6073. }
  6074. }
  6075. $sumofpayment = $totalpaid;
  6076. $sumofpaymentall = $totalpaid + $totalcreditnotes + $totaldeposits;
  6077. // Reverse back money or convert to reduction
  6078. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) {
  6079. // For credit note only
  6080. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment) {
  6081. if ($resteapayer == 0) {
  6082. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseRemainderToPayIsZero") . '">' . $langs->trans('DoPaymentBack') . '</span>';
  6083. } else {
  6084. print '<a class="butAction" href="' . DOL_URL_ROOT . '/compta/paiement.php?facid=' . $object->id . '&amp;action=create&amp;accountid=' . $object->fk_account . '">' . $langs->trans('DoPaymentBack') . '</a>';
  6085. }
  6086. }
  6087. if ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment) {
  6088. if ($resteapayer == 0) {
  6089. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span>';
  6090. } else {
  6091. print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a>';
  6092. }
  6093. }
  6094. // For standard invoice with excess received
  6095. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION || $object->type == Facture::TYPE_RECEIPT) && $object->statut == Facture::STATUS_VALIDATED && empty($object->paye) && $resteapayer < 0 && $usercancreate && empty($discount->id)) {
  6096. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc">' . $langs->trans('ConvertExcessReceivedToReduc') . '</a>';
  6097. }
  6098. // For credit note
  6099. if (
  6100. $object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercancreate
  6101. && (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $sumofpayment == 0)
  6102. ) {
  6103. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc" title="' . dol_escape_htmltag($langs->trans("ConfirmConvertToReduc2")) . '">' . $langs->trans('ConvertToReduc') . '</a>';
  6104. }
  6105. // For Receipt Credit Note
  6106. if (
  6107. $object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercancreate
  6108. && (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $sumofpayment == 0)
  6109. ) {
  6110. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReduc2")).'">'.$langs->trans('ConvertToReduc').'</a>';
  6111. }
  6112. // For down payment invoice (deposit)
  6113. if ($object->type == Facture::TYPE_DEPOSIT && $usercancreate && $object->statut > Facture::STATUS_DRAFT && empty($discount->id)) {
  6114. if (price2num($object->total_ttc, 'MT') == price2num($sumofpaymentall, 'MT') || ($object->type == Facture::STATUS_ABANDONED && in_array($object->close_code, array('bankcharge', 'discount_vat', 'other')))) {
  6115. // We can close a down payment only if paid amount is same than amount of down payment (by definition)
  6116. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc">' . $langs->trans('ConvertToReduc') . '</a>';
  6117. } else {
  6118. print '<span class="butActionRefused" title="' . $langs->trans("AmountPaidMustMatchAmountOfDownPayment") . '">' . $langs->trans('ConvertToReduc') . '</span>';
  6119. }
  6120. }
  6121. }
  6122. // Classify paid
  6123. if (
  6124. $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment && (
  6125. ($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_RECEIPT_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && ($resteapayer <= 0 || (!empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $object->total_ttc == $resteapayer))) ||
  6126. ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0) ||
  6127. ($object->type == Facture::TYPE_RECEIPT_CREDIT_NOTE && $resteapayer >= 0) ||
  6128. ($object->type == Facture::TYPE_DEPOSIT && $object->total_ttc > 0)
  6129. )
  6130. ) {
  6131. if ($object->type == Facture::TYPE_DEPOSIT && price2num($object->total_ttc, 'MT') != price2num($sumofpaymentall, 'MT')) {
  6132. // We can close a down payment only if paid amount is same than amount of down payment (by definition)
  6133. $params['attr']['title'] = $langs->trans('AmountPaidMustMatchAmountOfDownPayment');
  6134. print dolGetButtonAction($langs->trans('ClassifyPaid'), '', 'default', '#', '', false, $params);
  6135. } else {
  6136. print dolGetButtonAction($langs->trans('ClassifyPaid'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=paid', '', true, $params);
  6137. }
  6138. }
  6139. // Classify 'closed not completely paid' (possible if validated and not yet filed paid)
  6140. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && (empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $resteapayer != $object->total_ttc) && $usercanissuepayment) {
  6141. if ($totalpaid > 0 || $totalcreditnotes > 0) {
  6142. // If one payment or one credit note was linked to this invoice
  6143. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=paid">' . $langs->trans('ClassifyPaidPartially') . '</a>';
  6144. } else {
  6145. if (empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED)) {
  6146. if ($objectidnext) {
  6147. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseReplacedInvoice") . '">' . $langs->trans('ClassifyCanceled') . '</span>';
  6148. } else {
  6149. print '<a class="butAction' . ($conf->use_javascript_ajax ? ' reposition' : '') . '" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=canceled">' . $langs->trans('ClassifyCanceled') . '</a>';
  6150. }
  6151. }
  6152. }
  6153. }
  6154. // Create a credit note
  6155. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_RECEIPT || ($object->type == Facture::TYPE_DEPOSIT && empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) {
  6156. if (!$objectidnext) {
  6157. print '<a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?socid=' . $object->socid . '&amp;fac_avoir=' . $object->id . '&amp;action=create&amp;type=2' . ($object->fk_project > 0 ? '&amp;projectid=' . $object->fk_project : '') . ($object->entity > 0 ? '&amp;originentity=' . $object->entity : '') . '">' . $langs->trans("CreateCreditNote") . '</a>';
  6158. }
  6159. }
  6160. // Create Receipt Credit Note
  6161. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_RECEIPT || ($object->type == Facture::TYPE_DEPOSIT && empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) {
  6162. if (!$objectidnext) {
  6163. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&amp;invoiceAvoirWithLines=1&amp;action=create&amp;type=8'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').($object->entity > 0 ? '&amp;originentity='.$object->entity : '').'">'.$langs->trans("CreateReceiptCreditNote").'</a>';
  6164. }
  6165. }
  6166. // Customer name change
  6167. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_RECEIPT || ($object->type == Facture::TYPE_DEPOSIT && empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) {
  6168. if (!$objectidnext) {
  6169. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid=-1&amp;fac_avoir='.$object->id.'&amp;action=create&amp;type='. $object->type .''.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').($object->entity > 0 ? '&amp;originentity='.$object->entity : '').'&amp;customerchange=1">'.$langs->trans("ChangeCustomer").'</a>';
  6170. }
  6171. }
  6172. // For situation invoice with excess received
  6173. if (
  6174. $object->statut > Facture::STATUS_DRAFT
  6175. && $object->type == Facture::TYPE_SITUATION
  6176. && ($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits) > 0
  6177. && $usercancreate
  6178. && !$objectidnext
  6179. && $object->is_last_in_cycle()
  6180. && getDolGlobalInt('INVOICE_USE_SITUATION_CREDIT_NOTE')
  6181. ) {
  6182. if ($usercanunvalidate) {
  6183. print '<a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?socid=' . $object->socid . '&amp;fac_avoir=' . $object->id . '&amp;invoiceAvoirWithLines=1&amp;action=create&amp;type=2' . ($object->fk_project > 0 ? '&amp;projectid=' . $object->fk_project : '') . '">' . $langs->trans("CreateCreditNote") . '</a>';
  6184. } else {
  6185. print '<span class="butActionRefused classfortooltip" title="' . $langs->trans("NotEnoughPermissions") . '">' . $langs->trans("CreateCreditNote") . '</span>';
  6186. }
  6187. }
  6188. // Clone
  6189. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_RECEIPT) && $usercancreate) {
  6190. print dolGetButtonAction($langs->trans('ToClone'), '', 'default', $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=clone&amp;object=invoice', '', true, $params);
  6191. }
  6192. // Clone as predefined / Create template
  6193. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_RECEIPT) && $object->statut == 0 && $usercancreate) {
  6194. if (!$objectidnext && count($object->lines) > 0) {
  6195. print dolGetButtonAction($langs->trans('ChangeIntoRepeatableInvoice'), '', 'default', DOL_URL_ROOT . '/compta/facture/card-rec.php?facid=' . $object->id . '&amp;action=create', '', true, $params);
  6196. }
  6197. }
  6198. // Remove situation from cycle
  6199. if (
  6200. in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  6201. && $object->type == Facture::TYPE_SITUATION
  6202. && $usercancreate
  6203. && !$objectidnext
  6204. && $object->situation_counter > 1
  6205. && $object->is_last_in_cycle()
  6206. && $usercanunvalidate
  6207. ) {
  6208. if (($object->total_ttc - $totalcreditnotes) == 0) {
  6209. print '<a id="butSituationOut" class="butAction" href="' . $_SERVER['PHP_SELF'] . '?facid=' . $object->id . '&amp;action=situationout">' . $langs->trans("RemoveSituationFromCycle") . '</a>';
  6210. } else {
  6211. print '<a id="butSituationOutRefused" class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("DisabledBecauseNotEnouthCreditNote") . '" >' . $langs->trans("RemoveSituationFromCycle") . '</a>';
  6212. }
  6213. }
  6214. // Create next situation invoice
  6215. if ($usercancreate && ($object->type == 5) && ($object->statut == 1 || $object->statut == 2)) {
  6216. if ($object->is_last_in_cycle() && $object->situation_final != 1) {
  6217. print '<a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=create&amp;type=5&amp;origin=facture&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '" >' . $langs->trans('CreateNextSituationInvoice') . '</a>';
  6218. } elseif (!$object->is_last_in_cycle()) {
  6219. print '<a class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("DisabledBecauseNotLastInCycle") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a>';
  6220. } else {
  6221. print '<a class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("DisabledBecauseFinal") . '">' . $langs->trans('CreateNextSituationInvoice') . '</a>';
  6222. }
  6223. }
  6224. // Delete
  6225. $isErasable = $object->is_erasable();
  6226. $params = array(
  6227. 'attr' => array(
  6228. 'class' => 'classfortooltip'
  6229. )
  6230. );
  6231. if ($usercandelete || ($usercancreate && $isErasable == 1)) { // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions)
  6232. $enableDelete = false;
  6233. $deleteHref = '#';
  6234. $htmltooltip = '';
  6235. if ($isErasable == -4) {
  6236. $htmltooltip = $langs->trans('DisabledBecausePayments');
  6237. } elseif ($isErasable == -3) {
  6238. $htmltooltip = $langs->trans('DisabledBecauseNotLastSituationInvoice');
  6239. } elseif ($isErasable == -2) {
  6240. $htmltooltip = $langs->trans('DisabledBecauseNotLastInvoice');
  6241. } elseif ($isErasable == -1) {
  6242. $htmltooltip = $langs->trans('DisabledBecauseDispatchedInBookkeeping');
  6243. } elseif ($isErasable <= 0) { // Any other cases
  6244. $htmltooltip = $langs->trans('DisabledBecauseNotErasable');
  6245. } elseif ($objectidnext) {
  6246. $htmltooltip = $langs->trans('DisabledBecauseReplacedInvoice');
  6247. } else {
  6248. $deleteHref = $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=delete&token=' . newToken();
  6249. $enableDelete = true;
  6250. }
  6251. print dolGetButtonAction($htmltooltip, $langs->trans('Delete'), 'delete', $deleteHref, '', $enableDelete, $params);
  6252. } else {
  6253. print dolGetButtonAction($langs->trans('Delete'), $langs->trans('Delete'), 'delete', '#', '', false);
  6254. }
  6255. }
  6256. print '</div>';
  6257. }
  6258. // Select mail models is same action as presend
  6259. if (GETPOST('modelselected', 'alpha')) {
  6260. $action = 'presend';
  6261. }
  6262. if ($action != 'prerelance' && $action != 'presend') {
  6263. print '<div class="fichecenter"><div class="fichehalfleft">';
  6264. print '<a name="builddoc"></a>'; // ancre
  6265. // Generated documents
  6266. $filename = dol_sanitizeFileName($object->ref);
  6267. $filedir = $conf->facture->multidir_output[$object->entity] . '/' . dol_sanitizeFileName($object->ref);
  6268. $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id;
  6269. $genallowed = $usercanread;
  6270. $delallowed = $usercancreate;
  6271. print $formfile->showdocuments(
  6272. 'facture',
  6273. $filename,
  6274. $filedir,
  6275. $urlsource,
  6276. $genallowed,
  6277. $delallowed,
  6278. $object->model_pdf,
  6279. 1,
  6280. 0,
  6281. 0,
  6282. 28,
  6283. 0,
  6284. '',
  6285. '',
  6286. '',
  6287. $soc->default_lang,
  6288. '',
  6289. $object,
  6290. 0,
  6291. 'remove_file_comfirm'
  6292. );
  6293. $somethingshown = $formfile->numoffiles;
  6294. // Show links to link elements
  6295. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
  6296. $compatibleImportElementsList = false;
  6297. if (
  6298. $usercancreate
  6299. && $object->statut == Facture::STATUS_DRAFT
  6300. && ($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 || $object->type == Facture::TYPE_RECEIPT)
  6301. ) {
  6302. $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements
  6303. }
  6304. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
  6305. // Show online payment link
  6306. $useonlinepayment = (isModEnabled('paypal') || isModEnabled('stripe') || isModEnabled('paybox'));
  6307. if ($object->statut != Facture::STATUS_DRAFT && $useonlinepayment) {
  6308. print '<br><!-- Link to pay -->' . "\n";
  6309. require_once DOL_DOCUMENT_ROOT . '/core/lib/payments.lib.php';
  6310. print showOnlinePaymentUrl('invoice', $object->ref) . '<br>';
  6311. }
  6312. print '</div><div class="fichehalfright">';
  6313. // List of actions on element
  6314. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
  6315. $formactions = new FormActions($db);
  6316. $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1);
  6317. print '</div></div>';
  6318. }
  6319. // Presend form
  6320. $modelmail = 'facture_send';
  6321. $defaulttopic = 'SendBillRef';
  6322. $diroutput = $conf->facture->multidir_output[$object->entity];
  6323. $trackid = 'inv' . $object->id;
  6324. include DOL_DOCUMENT_ROOT . '/core/tpl/card_presend.tpl.php';
  6325. }
  6326. // End of page
  6327. llxFooter();
  6328. $db->close();
  6329. ?>
  6330. <script src="/custom/bbus/js/bbus.js"></script>;
  6331. <link rel="stylesheet" type="text/css" href="/custom/bbus/views/bbus.css">
  6332. <script>
  6333. $(document).ready(function () {
  6334. $('#remise_percent').attr('readonly', true);
  6335. $('#options_discount_percent').change(function () {
  6336. var selectedValue = $(this).val();
  6337. $("#remise_percent").val(selectedValue);
  6338. $('#remise_percent').attr('readonly', true);
  6339. });
  6340. });
  6341. </script>