commande.class.php 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836
  1. <?php
  2. /* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  6. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  7. * Copyright (C) 2011 Jean Heimburger <jean@tiaris.info>
  8. * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  11. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  12. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  13. * Copyright (C) 2016-2022 Ferran Marcet <fmarcet@2byte.es>
  14. * Copyright (C) 2021-2023 Frédéric France <frederic.france@netlogic.fr>
  15. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  16. *
  17. * This program is free software; you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation; either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  29. */
  30. /**
  31. * \file htdocs/commande/class/commande.class.php
  32. * \ingroup commande
  33. * \brief class for orders
  34. */
  35. include_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  39. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  41. /**
  42. * Class to manage customers orders
  43. */
  44. class Commande extends CommonOrder
  45. {
  46. /**
  47. * @var string ID to identify managed object
  48. */
  49. public $element = 'commande';
  50. /**
  51. * @var string Name of table without prefix where object is stored
  52. */
  53. public $table_element = 'commande';
  54. /**
  55. * @var string Name of subtable line
  56. */
  57. public $table_element_line = 'commandedet';
  58. /**
  59. * @var string Name of class line
  60. */
  61. public $class_element_line = 'OrderLine';
  62. /**
  63. * @var string Field name with ID of parent key if this field has a parent
  64. */
  65. public $fk_element = 'fk_commande';
  66. /**
  67. * @var string String with name of icon for commande class. Here is object_order.png
  68. */
  69. public $picto = 'order';
  70. /**
  71. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  72. * @var int
  73. */
  74. public $ismultientitymanaged = 1;
  75. /**
  76. * @var int Does object support extrafields ? 0=No, 1=Yes
  77. */
  78. public $isextrafieldmanaged = 1;
  79. /**
  80. * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  81. * @var integer
  82. */
  83. public $restrictiononfksoc = 1;
  84. /**
  85. * {@inheritdoc}
  86. */
  87. protected $table_ref_field = 'ref';
  88. /**
  89. * @var int Thirdparty ID
  90. */
  91. public $socid;
  92. /**
  93. * @var string Thirdparty ref of order
  94. */
  95. public $ref_client;
  96. /**
  97. * @var string Thirdparty ref of order
  98. */
  99. public $ref_customer;
  100. /**
  101. * @var int Contact ID
  102. */
  103. public $contactid;
  104. /**
  105. * Status of the order
  106. * @var int
  107. */
  108. public $statut;
  109. /**
  110. * @var int Status Billed or not
  111. */
  112. public $billed;
  113. /**
  114. * @var string Limit date payment
  115. */
  116. public $date_lim_reglement;
  117. /**
  118. * @var string Condition payment code
  119. */
  120. public $cond_reglement_code;
  121. /**
  122. * @var string Condition payment label
  123. */
  124. public $cond_reglement_doc;
  125. /**
  126. * @var double Deposit % for payment terms
  127. */
  128. public $deposit_percent;
  129. /**
  130. * @var int bank account ID
  131. */
  132. public $fk_account;
  133. /**
  134. * @var string It holds the label of the payment mode. Use it in case translation cannot be found.
  135. */
  136. public $mode_reglement;
  137. /**
  138. * @var int Payment mode id
  139. */
  140. public $mode_reglement_id;
  141. /**
  142. * @var string Payment mode code
  143. */
  144. public $mode_reglement_code;
  145. /**
  146. * Availability delivery time id
  147. * @var int
  148. */
  149. public $availability_id;
  150. /**
  151. * Availability delivery time code
  152. * @var string
  153. */
  154. public $availability_code;
  155. /**
  156. * Label of availability delivery time. Use it in case translation cannot be found.
  157. * @var string
  158. */
  159. public $availability;
  160. /**
  161. * @var int Source demand reason Id
  162. */
  163. public $demand_reason_id;
  164. /**
  165. * @var string Source reason code. Why we receive order (after a phone campaign, ...)
  166. */
  167. public $demand_reason_code;
  168. /**
  169. * @var int Date of order
  170. */
  171. public $date;
  172. /**
  173. * @var int Date of order
  174. * @deprecated
  175. * @see $date
  176. */
  177. public $date_commande;
  178. /**
  179. * @var int Date expected of shipment (date of start of shipment, not the reception that occurs some days after)
  180. */
  181. public $delivery_date;
  182. /**
  183. * @var int ID
  184. */
  185. public $fk_remise_except;
  186. /**
  187. * @deprecated
  188. */
  189. public $remise_percent;
  190. public $source; // Order mode. How we received order (by phone, by email, ...)
  191. /**
  192. * @var int Warehouse Id
  193. */
  194. public $warehouse_id;
  195. public $extraparams = array();
  196. public $linked_objects = array();
  197. /**
  198. * @var int User author ID
  199. */
  200. public $user_author_id;
  201. /**
  202. * @var int User validator ID
  203. */
  204. public $user_valid;
  205. /**
  206. * @var OrderLine one line of an order
  207. */
  208. public $line;
  209. /**
  210. * @var OrderLine[]
  211. */
  212. public $lines = array();
  213. // Multicurrency
  214. /**
  215. * @var int Currency ID
  216. */
  217. public $fk_multicurrency;
  218. /**
  219. * @var string multicurrency code
  220. */
  221. public $multicurrency_code;
  222. public $multicurrency_tx;
  223. public $multicurrency_total_ht;
  224. public $multicurrency_total_tva;
  225. public $multicurrency_total_ttc;
  226. //! key of module source when order generated from a dedicated module ('cashdesk', 'takepos', ...)
  227. public $module_source;
  228. //! key of pos source ('0', '1', ...)
  229. public $pos_source;
  230. /**
  231. * @var array Array with line of all shipments
  232. */
  233. public $expeditions;
  234. /**
  235. * @var string payment url
  236. */
  237. public $online_payment_url;
  238. /**
  239. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  240. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  241. * 'label' the translation key.
  242. * 'enabled' is a condition when the field must be managed.
  243. * 'position' is the sort order of field.
  244. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  245. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  246. * 'noteditable' says if field is not editable (1 or 0)
  247. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  248. * 'index' if we want an index in database.
  249. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  250. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  251. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  252. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  253. * 'help' is a string visible as a tooltip on field
  254. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  255. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  256. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  257. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  258. *
  259. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  260. */
  261. // BEGIN MODULEBUILDER PROPERTIES
  262. /**
  263. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  264. */
  265. public $fields = array(
  266. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  267. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1),
  268. 'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>25),
  269. 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>26),
  270. 'ref_client' =>array('type'=>'varchar(255)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>28),
  271. 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'isModEnabled("societe")', 'visible'=>-1, 'notnull'=>1, 'position'=>20),
  272. 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Project', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>25),
  273. 'date_commande' =>array('type'=>'date', 'label'=>'Date', 'enabled'=>1, 'visible'=>1, 'position'=>60, 'csslist'=>'nowraponall'),
  274. 'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>62, 'csslist'=>'nowraponall'),
  275. 'date_cloture' =>array('type'=>'datetime', 'label'=>'DateClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>65, 'csslist'=>'nowraponall'),
  276. 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
  277. 'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  278. 'source' =>array('type'=>'smallint(6)', 'label'=>'Source', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
  279. 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1),
  280. 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LocalTax1', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1),
  281. 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LocalTax2', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1),
  282. 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1),
  283. 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>145, 'isameasure'=>1),
  284. 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>150),
  285. 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>155),
  286. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'PDFTemplate', 'enabled'=>1, 'visible'=>0, 'position'=>160),
  287. 'fk_account' =>array('type'=>'integer', 'label'=>'BankAccount', 'enabled'=>'isModEnabled("banque")', 'visible'=>-1, 'position'=>170),
  288. 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'MulticurrencyID', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
  289. 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
  290. 'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>181),
  291. 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  292. 'date_livraison' =>array('type'=>'date', 'label'=>'DateDeliveryPlanned', 'enabled'=>1, 'visible'=>-1, 'position'=>190, 'csslist'=>'nowraponall'),
  293. 'fk_shipping_method' =>array('type'=>'integer', 'label'=>'ShippingMethod', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
  294. 'fk_warehouse' =>array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Fk warehouse', 'enabled'=>'isModEnabled("stock")', 'visible'=>-1, 'position'=>200),
  295. 'fk_availability' =>array('type'=>'integer', 'label'=>'Availability', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
  296. 'fk_input_reason' =>array('type'=>'integer', 'label'=>'InputReason', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
  297. //'fk_delivery_address' =>array('type'=>'integer', 'label'=>'DeliveryAddress', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
  298. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
  299. 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>230),
  300. 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>235),
  301. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>240),
  302. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCurrency', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>245),
  303. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>250, 'isameasure'=>1),
  304. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>255, 'isameasure'=>1),
  305. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>260, 'isameasure'=>1),
  306. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'isModEnabled("multicurrency")', 'visible'=>-1, 'position'=>265, 'isameasure'=>1),
  307. 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
  308. 'module_source' =>array('type'=>'varchar(32)', 'label'=>'POSModule', 'enabled'=>1, 'visible'=>-1, 'position'=>275),
  309. 'pos_source' =>array('type'=>'varchar(32)', 'label'=>'POSTerminal', 'enabled'=>1, 'visible'=>-1, 'position'=>280),
  310. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
  311. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>302),
  312. 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>304, 'csslist'=>'nowraponall'),
  313. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>306),
  314. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>400),
  315. 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
  316. );
  317. // END MODULEBUILDER PROPERTIES
  318. /**
  319. * ERR Not enough stock
  320. */
  321. const STOCK_NOT_ENOUGH_FOR_ORDER = -3;
  322. /**
  323. * Canceled status
  324. */
  325. const STATUS_CANCELED = -1;
  326. /**
  327. * Draft status
  328. */
  329. const STATUS_DRAFT = 0;
  330. /**
  331. * Validated status
  332. */
  333. const STATUS_VALIDATED = 1;
  334. /**
  335. * Shipment on process
  336. */
  337. const STATUS_SHIPMENTONPROCESS = 2; // We set this status when a shipment is validated
  338. const STATUS_ACCEPTED = 2; // For backward compatibility. Use key STATUS_SHIPMENTONPROCESS instead.
  339. /**
  340. * Closed (Sent, billed or not)
  341. */
  342. const STATUS_CLOSED = 3;
  343. /**
  344. * Constructor
  345. *
  346. * @param DoliDB $db Database handler
  347. */
  348. public function __construct($db)
  349. {
  350. $this->db = $db;
  351. }
  352. /**
  353. * Returns the reference to the following non used Order depending on the active numbering module
  354. * defined into COMMANDE_ADDON
  355. *
  356. * @param Societe $soc Object thirdparty
  357. * @return string Order free reference
  358. */
  359. public function getNextNumRef($soc)
  360. {
  361. global $langs, $conf;
  362. $langs->load("order");
  363. if (getDolGlobalString('COMMANDE_ADDON')) {
  364. $mybool = false;
  365. $file = getDolGlobalString('COMMANDE_ADDON') . ".php";
  366. $classname = $conf->global->COMMANDE_ADDON;
  367. // Include file with class
  368. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  369. foreach ($dirmodels as $reldir) {
  370. $dir = dol_buildpath($reldir."core/modules/commande/");
  371. // Load file with numbering class (if found)
  372. $mybool |= @include_once $dir.$file;
  373. }
  374. if ($mybool === false) {
  375. dol_print_error('', "Failed to include file ".$file);
  376. return '';
  377. }
  378. $obj = new $classname();
  379. $numref = $obj->getNextValue($soc, $this);
  380. if ($numref != "") {
  381. return $numref;
  382. } else {
  383. $this->error = $obj->error;
  384. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  385. return "";
  386. }
  387. } else {
  388. print $langs->trans("Error")." ".$langs->trans("Error_COMMANDE_ADDON_NotDefined");
  389. return "";
  390. }
  391. }
  392. /**
  393. * Validate order
  394. *
  395. * @param User $user User making status change
  396. * @param int $idwarehouse Id of warehouse to use for stock decrease
  397. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  398. * @return int <0 if KO, 0=Nothing done, >0 if OK
  399. */
  400. public function valid($user, $idwarehouse = 0, $notrigger = 0)
  401. {
  402. global $conf, $langs;
  403. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  404. $error = 0;
  405. // Protection
  406. if ($this->statut == self::STATUS_VALIDATED) {
  407. dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
  408. return 0;
  409. }
  410. if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
  411. || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')))) {
  412. $this->error = 'NotEnoughPermissions';
  413. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  414. return -1;
  415. }
  416. $now = dol_now();
  417. $this->db->begin();
  418. // Definition du nom de module de numerotation de commande
  419. $soc = new Societe($this->db);
  420. $soc->fetch($this->socid);
  421. // Class of company linked to order
  422. $result = $soc->setAsCustomer();
  423. // Define new ref
  424. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  425. $num = $this->getNextNumRef($soc);
  426. } else {
  427. $num = $this->ref;
  428. }
  429. $this->newref = dol_sanitizeFileName($num);
  430. // Validate
  431. $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
  432. $sql .= " SET ref = '".$this->db->escape($num)."',";
  433. $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
  434. $sql .= " date_valid='".$this->db->idate($now)."',";
  435. $sql .= " fk_user_valid = ".($user->id > 0 ? (int) $user->id : "null").",";
  436. $sql .= " fk_user_modif = ".((int) $user->id);
  437. $sql .= " WHERE rowid = ".((int) $this->id);
  438. dol_syslog(get_class($this)."::valid", LOG_DEBUG);
  439. $resql = $this->db->query($sql);
  440. if (!$resql) {
  441. dol_print_error($this->db);
  442. $this->error = $this->db->lasterror();
  443. $error++;
  444. }
  445. if (!$error) {
  446. // If stock is incremented on validate order, we must increment it
  447. if ($result >= 0 && isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
  448. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  449. $langs->load("agenda");
  450. // Loop on each line
  451. $cpt = count($this->lines);
  452. for ($i = 0; $i < $cpt; $i++) {
  453. if ($this->lines[$i]->fk_product > 0) {
  454. $mouvP = new MouvementStock($this->db);
  455. $mouvP->origin = &$this;
  456. $mouvP->setOrigin($this->element, $this->id);
  457. // We decrement stock of product (and sub-products)
  458. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr", $num));
  459. if ($result < 0) {
  460. $error++;
  461. $this->error = $mouvP->error;
  462. }
  463. }
  464. if ($error) {
  465. break;
  466. }
  467. }
  468. }
  469. }
  470. if (!$error && !$notrigger) {
  471. // Call trigger
  472. $result = $this->call_trigger('ORDER_VALIDATE', $user);
  473. if ($result < 0) {
  474. $error++;
  475. }
  476. // End call triggers
  477. }
  478. if (!$error) {
  479. $this->oldref = $this->ref;
  480. // Rename directory if dir was a temporary ref
  481. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  482. // Now we rename also files into index
  483. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'commande/".$this->db->escape($this->newref)."'";
  484. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  485. $resql = $this->db->query($sql);
  486. if (!$resql) {
  487. $error++; $this->error = $this->db->lasterror();
  488. }
  489. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'commande/".$this->db->escape($this->newref)."'";
  490. $sql .= " WHERE filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  491. $resql = $this->db->query($sql);
  492. if (!$resql) {
  493. $error++; $this->error = $this->db->lasterror();
  494. }
  495. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  496. $oldref = dol_sanitizeFileName($this->ref);
  497. $newref = dol_sanitizeFileName($num);
  498. $dirsource = $conf->commande->multidir_output[$this->entity].'/'.$oldref;
  499. $dirdest = $conf->commande->multidir_output[$this->entity].'/'.$newref;
  500. if (!$error && file_exists($dirsource)) {
  501. dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
  502. if (@rename($dirsource, $dirdest)) {
  503. dol_syslog("Rename ok");
  504. // Rename docs starting with $oldref with $newref
  505. $listoffiles = dol_dir_list($conf->commande->multidir_output[$this->entity].'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  506. foreach ($listoffiles as $fileentry) {
  507. $dirsource = $fileentry['name'];
  508. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  509. $dirsource = $fileentry['path'].'/'.$dirsource;
  510. $dirdest = $fileentry['path'].'/'.$dirdest;
  511. @rename($dirsource, $dirdest);
  512. }
  513. }
  514. }
  515. }
  516. }
  517. // Set new ref and current status
  518. if (!$error) {
  519. $this->ref = $num;
  520. $this->statut = self::STATUS_VALIDATED; // deprecated
  521. $this->status = self::STATUS_VALIDATED;
  522. }
  523. if (!$error) {
  524. $this->db->commit();
  525. return 1;
  526. } else {
  527. $this->db->rollback();
  528. return -1;
  529. }
  530. }
  531. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  532. /**
  533. * Set draft status
  534. *
  535. * @param User $user Object user that modify
  536. * @param int $idwarehouse Warehouse ID to use for stock change (Used only if option STOCK_CALCULATE_ON_VALIDATE_ORDER is on)
  537. * @return int <0 if KO, >0 if OK
  538. */
  539. public function setDraft($user, $idwarehouse = -1)
  540. {
  541. //phpcs:enable
  542. global $conf, $langs;
  543. $error = 0;
  544. // Protection
  545. if ($this->statut <= self::STATUS_DRAFT) {
  546. return 0;
  547. }
  548. if (!((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'creer'))
  549. || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')))) {
  550. $this->error = 'Permission denied';
  551. return -1;
  552. }
  553. dol_syslog(__METHOD__, LOG_DEBUG);
  554. $this->db->begin();
  555. $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
  556. $sql .= " SET fk_statut = ".self::STATUS_DRAFT.",";
  557. $sql .= " fk_user_modif = ".((int) $user->id);
  558. $sql .= " WHERE rowid = ".((int) $this->id);
  559. if ($this->db->query($sql)) {
  560. if (!$error) {
  561. $this->oldcopy = clone $this;
  562. }
  563. // If stock is decremented on validate order, we must reincrement it
  564. if (isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
  565. $result = 0;
  566. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  567. $langs->load("agenda");
  568. $num = count($this->lines);
  569. for ($i = 0; $i < $num; $i++) {
  570. if ($this->lines[$i]->fk_product > 0) {
  571. $mouvP = new MouvementStock($this->db);
  572. $mouvP->origin = &$this;
  573. $mouvP->setOrigin($this->element, $this->id);
  574. // We increment stock of product (and sub-products)
  575. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderBackToDraftInDolibarr", $this->ref));
  576. if ($result < 0) {
  577. $error++; $this->error = $mouvP->error; break;
  578. }
  579. }
  580. }
  581. }
  582. if (!$error) {
  583. // Call trigger
  584. $result = $this->call_trigger('ORDER_UNVALIDATE', $user);
  585. if ($result < 0) {
  586. $error++;
  587. }
  588. }
  589. if (!$error) {
  590. $this->statut = self::STATUS_DRAFT;
  591. $this->db->commit();
  592. return 1;
  593. } else {
  594. $this->db->rollback();
  595. return -1;
  596. }
  597. } else {
  598. $this->error = $this->db->error();
  599. $this->db->rollback();
  600. return -1;
  601. }
  602. }
  603. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  604. /**
  605. * Tag the order as validated (opened)
  606. * Function used when order is reopend after being closed.
  607. *
  608. * @param User $user Object user that change status
  609. * @return int <0 if KO, 0 if nothing is done, >0 if OK
  610. */
  611. public function set_reopen($user)
  612. {
  613. // phpcs:enable
  614. $error = 0;
  615. if ($this->statut != self::STATUS_CANCELED && $this->statut != self::STATUS_CLOSED) {
  616. dol_syslog(get_class($this)."::set_reopen order has not status closed", LOG_WARNING);
  617. return 0;
  618. }
  619. $this->db->begin();
  620. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
  621. $sql .= ' SET fk_statut='.self::STATUS_VALIDATED.', facture=0,';
  622. $sql .= " fk_user_modif = ".((int) $user->id);
  623. $sql .= " WHERE rowid = ".((int) $this->id);
  624. dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG);
  625. $resql = $this->db->query($sql);
  626. if ($resql) {
  627. // Call trigger
  628. $result = $this->call_trigger('ORDER_REOPEN', $user);
  629. if ($result < 0) {
  630. $error++;
  631. }
  632. // End call triggers
  633. } else {
  634. $error++;
  635. $this->error = $this->db->lasterror();
  636. dol_print_error($this->db);
  637. }
  638. if (!$error) {
  639. $this->statut = self::STATUS_VALIDATED;
  640. $this->billed = 0;
  641. $this->db->commit();
  642. return 1;
  643. } else {
  644. foreach ($this->errors as $errmsg) {
  645. dol_syslog(get_class($this)."::set_reopen ".$errmsg, LOG_ERR);
  646. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  647. }
  648. $this->db->rollback();
  649. return -1 * $error;
  650. }
  651. }
  652. /**
  653. * Close order
  654. *
  655. * @param User $user Objet user that close
  656. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  657. * @return int <0 if KO, >0 if OK
  658. */
  659. public function cloture($user, $notrigger = 0)
  660. {
  661. global $conf;
  662. $error = 0;
  663. $usercanclose = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->commande->creer))
  664. || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->commande->order_advance->close)));
  665. if ($usercanclose) {
  666. if ($this->statut == self::STATUS_CLOSED) {
  667. return 0;
  668. }
  669. $this->db->begin();
  670. $now = dol_now();
  671. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  672. $sql .= ' SET fk_statut = '.self::STATUS_CLOSED.',';
  673. $sql .= ' fk_user_cloture = '.((int) $user->id).',';
  674. $sql .= " date_cloture = '".$this->db->idate($now)."',";
  675. $sql .= " fk_user_modif = ".((int) $user->id);
  676. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
  677. if ($this->db->query($sql)) {
  678. if (!$notrigger) {
  679. // Call trigger
  680. $result = $this->call_trigger('ORDER_CLOSE', $user);
  681. if ($result < 0) {
  682. $error++;
  683. }
  684. // End call triggers
  685. }
  686. if (!$error) {
  687. $this->statut = self::STATUS_CLOSED;
  688. $this->db->commit();
  689. return 1;
  690. } else {
  691. $this->db->rollback();
  692. return -1;
  693. }
  694. } else {
  695. $this->error = $this->db->lasterror();
  696. $this->db->rollback();
  697. return -1;
  698. }
  699. }
  700. return 0;
  701. }
  702. /**
  703. * Cancel an order
  704. * If stock is decremented on order validation, we must reincrement it
  705. *
  706. * @param int $idwarehouse Id warehouse to use for stock change.
  707. * @return int <0 if KO, >0 if OK
  708. */
  709. public function cancel($idwarehouse = -1)
  710. {
  711. global $conf, $user, $langs;
  712. $error = 0;
  713. $this->db->begin();
  714. $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
  715. $sql .= " SET fk_statut = ".self::STATUS_CANCELED.",";
  716. $sql .= " fk_user_modif = ".((int) $user->id);
  717. $sql .= " WHERE rowid = ".((int) $this->id);
  718. $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
  719. dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
  720. if ($this->db->query($sql)) {
  721. // If stock is decremented on validate order, we must reincrement it
  722. if (isModEnabled('stock') && getDolGlobalInt('STOCK_CALCULATE_ON_VALIDATE_ORDER') == 1) {
  723. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  724. $langs->load("agenda");
  725. $num = count($this->lines);
  726. for ($i = 0; $i < $num; $i++) {
  727. if ($this->lines[$i]->fk_product > 0) {
  728. $mouvP = new MouvementStock($this->db);
  729. $mouvP->setOrigin($this->element, $this->id);
  730. // We increment stock of product (and sub-products)
  731. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("OrderCanceledInDolibarr", $this->ref)); // price is 0, we don't want WAP to be changed
  732. if ($result < 0) {
  733. $error++;
  734. $this->error = $mouvP->error;
  735. break;
  736. }
  737. }
  738. }
  739. }
  740. if (!$error) {
  741. // Call trigger
  742. $result = $this->call_trigger('ORDER_CANCEL', $user);
  743. if ($result < 0) {
  744. $error++;
  745. }
  746. // End call triggers
  747. }
  748. if (!$error) {
  749. $this->statut = self::STATUS_CANCELED;
  750. $this->db->commit();
  751. return 1;
  752. } else {
  753. foreach ($this->errors as $errmsg) {
  754. dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR);
  755. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  756. }
  757. $this->db->rollback();
  758. return -1 * $error;
  759. }
  760. } else {
  761. $this->error = $this->db->error();
  762. $this->db->rollback();
  763. return -1;
  764. }
  765. }
  766. /**
  767. * Create order
  768. * Note that this->ref can be set or empty. If empty, we will use "(PROV)"
  769. *
  770. * @param User $user Objet user that make creation
  771. * @param int $notrigger Disable all triggers
  772. * @return int <0 if KO, >0 if OK
  773. */
  774. public function create($user, $notrigger = 0)
  775. {
  776. global $conf, $langs, $mysoc;
  777. $error = 0;
  778. // Clean parameters
  779. // Set tmp vars
  780. $date = ($this->date_commande ? $this->date_commande : $this->date);
  781. $delivery_date = $this->delivery_date;
  782. // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
  783. if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
  784. list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
  785. } else {
  786. $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  787. }
  788. if (empty($this->fk_multicurrency)) {
  789. $this->multicurrency_code = $conf->currency;
  790. $this->fk_multicurrency = 0;
  791. $this->multicurrency_tx = 1;
  792. }
  793. dol_syslog(get_class($this)."::create user=".$user->id);
  794. // Check parameters
  795. if (!empty($this->ref)) { // We check that ref is not already used
  796. $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
  797. if ($result > 0) {
  798. $this->error = 'ErrorRefAlreadyExists';
  799. dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
  800. $this->db->rollback();
  801. return -1;
  802. }
  803. }
  804. $soc = new Societe($this->db);
  805. $result = $soc->fetch($this->socid);
  806. if ($result < 0) {
  807. $this->error = "Failed to fetch company";
  808. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  809. return -2;
  810. }
  811. if (getDolGlobalString('ORDER_REQUIRE_SOURCE') && $this->source < 0) {
  812. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Source"));
  813. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  814. return -1;
  815. }
  816. $now = dol_now();
  817. $this->db->begin();
  818. $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande (";
  819. $sql .= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client";
  820. $sql .= ", model_pdf, fk_cond_reglement, deposit_percent, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
  821. $sql .= ", fk_shipping_method";
  822. $sql .= ", fk_warehouse";
  823. $sql .= ", fk_incoterms, location_incoterms";
  824. $sql .= ", entity, module_source, pos_source";
  825. $sql .= ", fk_multicurrency";
  826. $sql .= ", multicurrency_code";
  827. $sql .= ", multicurrency_tx";
  828. $sql .= ")";
  829. $sql .= " VALUES ('(PROV)', ".((int) $this->socid).", '".$this->db->idate($now)."', ".((int) $user->id);
  830. $sql .= ", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "null");
  831. $sql .= ", '".$this->db->idate($date)."'";
  832. $sql .= ", ".($this->source >= 0 && $this->source != '' ? $this->db->escape($this->source) : 'null');
  833. $sql .= ", '".$this->db->escape($this->note_private)."'";
  834. $sql .= ", '".$this->db->escape($this->note_public)."'";
  835. $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  836. $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
  837. $sql .= ", '".$this->db->escape($this->model_pdf)."'";
  838. $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
  839. $sql .= ", ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
  840. $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
  841. $sql .= ", ".($this->fk_account > 0 ? ((int) $this->fk_account) : 'NULL');
  842. $sql .= ", ".($this->availability_id > 0 ? ((int) $this->availability_id) : "null");
  843. $sql .= ", ".($this->demand_reason_id > 0 ? ((int) $this->demand_reason_id) : "null");
  844. $sql .= ", ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : "null");
  845. $sql .= ", ".($this->fk_delivery_address > 0 ? ((int) $this->fk_delivery_address) : 'NULL');
  846. $sql .= ", ".(!empty($this->shipping_method_id) && $this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : 'NULL');
  847. $sql .= ", ".(!empty($this->warehouse_id) && $this->warehouse_id > 0 ? ((int) $this->warehouse_id) : 'NULL');
  848. $sql .= ", ".(int) $this->fk_incoterms;
  849. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  850. $sql .= ", ".setEntity($this);
  851. $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
  852. $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
  853. $sql .= ", ".(int) $this->fk_multicurrency;
  854. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  855. $sql .= ", ".(float) $this->multicurrency_tx;
  856. $sql .= ")";
  857. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  858. $resql = $this->db->query($sql);
  859. if ($resql) {
  860. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commande');
  861. if ($this->id) {
  862. $fk_parent_line = 0;
  863. $num = count($this->lines);
  864. /*
  865. * Insert products details into db
  866. */
  867. for ($i = 0; $i < $num; $i++) {
  868. $line = $this->lines[$i];
  869. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  870. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  871. if (!is_object($line)) {
  872. $line = (object) $line;
  873. }
  874. // Reset fk_parent_line for no child products and special product
  875. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  876. $fk_parent_line = 0;
  877. }
  878. // Complete vat rate with code
  879. $vatrate = $line->tva_tx;
  880. if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) {
  881. $vatrate .= ' ('.$line->vat_src_code.')';
  882. }
  883. if (getDolGlobalString('MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION')) {
  884. $originid = $line->origin_id;
  885. $origintype = $line->origin;
  886. } else {
  887. $originid = $line->id;
  888. $origintype = $this->element;
  889. }
  890. // ref_ext
  891. if (empty($line->ref_ext)) {
  892. $line->ref_ext = '';
  893. }
  894. $result = $this->addline(
  895. $line->desc,
  896. $line->subprice,
  897. $line->qty,
  898. $vatrate,
  899. $line->localtax1_tx,
  900. $line->localtax2_tx,
  901. $line->fk_product,
  902. $line->remise_percent,
  903. $line->info_bits,
  904. $line->fk_remise_except,
  905. 'HT',
  906. 0,
  907. $line->date_start,
  908. $line->date_end,
  909. $line->product_type,
  910. $line->rang,
  911. $line->special_code,
  912. $fk_parent_line,
  913. $line->fk_fournprice,
  914. $line->pa_ht,
  915. $line->label,
  916. $line->array_options,
  917. $line->fk_unit,
  918. $origintype,
  919. $originid,
  920. 0,
  921. $line->ref_ext,
  922. 1
  923. );
  924. if ($result < 0) {
  925. if ($result != self::STOCK_NOT_ENOUGH_FOR_ORDER) {
  926. $this->error = $this->db->lasterror();
  927. $this->errors[] = $this->error;
  928. dol_print_error($this->db);
  929. }
  930. $this->db->rollback();
  931. return -1;
  932. }
  933. // Defined the new fk_parent_line
  934. if ($result > 0 && $line->product_type == 9) {
  935. $fk_parent_line = $result;
  936. }
  937. }
  938. $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
  939. // update ref
  940. $initialref = '(PROV'.$this->id.')';
  941. if (!empty($this->ref)) {
  942. $initialref = $this->ref;
  943. }
  944. $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id);
  945. if ($this->db->query($sql)) {
  946. $this->ref = $initialref;
  947. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  948. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  949. }
  950. // Add object linked
  951. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  952. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  953. if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
  954. foreach ($tmp_origin_id as $origin_id) {
  955. $ret = $this->add_object_linked($origin, $origin_id);
  956. if (!$ret) {
  957. $this->error = $this->db->lasterror();
  958. $error++;
  959. }
  960. }
  961. } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  962. {
  963. $origin_id = $tmp_origin_id;
  964. $ret = $this->add_object_linked($origin, $origin_id);
  965. if (!$ret) {
  966. $this->error = $this->db->lasterror();
  967. $error++;
  968. }
  969. }
  970. }
  971. }
  972. if (!$error && $this->id && getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN') && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
  973. $originforcontact = $this->origin;
  974. $originidforcontact = $this->origin_id;
  975. if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
  976. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  977. $exp = new Expedition($this->db);
  978. $exp->fetch($this->origin_id);
  979. $exp->fetchObjectLinked();
  980. if (count($exp->linkedObjectsIds['commande']) > 0) {
  981. foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
  982. $originforcontact = 'commande';
  983. if (is_object($value)) {
  984. $originidforcontact = $value->id;
  985. } else {
  986. $originidforcontact = $value;
  987. }
  988. break; // We take first one
  989. }
  990. }
  991. }
  992. $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  993. $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
  994. $resqlcontact = $this->db->query($sqlcontact);
  995. if ($resqlcontact) {
  996. while ($objcontact = $this->db->fetch_object($resqlcontact)) {
  997. //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
  998. $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
  999. }
  1000. } else {
  1001. dol_print_error($resqlcontact);
  1002. }
  1003. }
  1004. if (!$error) {
  1005. $result = $this->insertExtraFields();
  1006. if ($result < 0) {
  1007. $error++;
  1008. }
  1009. }
  1010. if (!$error && !$notrigger) {
  1011. // Call trigger
  1012. $result = $this->call_trigger('ORDER_CREATE', $user);
  1013. if ($result < 0) {
  1014. $error++;
  1015. }
  1016. // End call triggers
  1017. }
  1018. if (!$error) {
  1019. $this->db->commit();
  1020. return $this->id;
  1021. } else {
  1022. $this->db->rollback();
  1023. return -1 * $error;
  1024. }
  1025. } else {
  1026. $this->error = $this->db->lasterror();
  1027. $this->db->rollback();
  1028. return -1;
  1029. }
  1030. }
  1031. return 0;
  1032. } else {
  1033. dol_print_error($this->db);
  1034. $this->db->rollback();
  1035. return -1;
  1036. }
  1037. }
  1038. /**
  1039. * Load an object from its id and create a new one in database
  1040. *
  1041. * @param User $user User making the clone
  1042. * @param int $socid Id of thirdparty
  1043. * @return int New id of clone
  1044. */
  1045. public function createFromClone(User $user, $socid = 0)
  1046. {
  1047. global $conf, $user, $hookmanager;
  1048. $error = 0;
  1049. $this->db->begin();
  1050. // get lines so they will be clone
  1051. foreach ($this->lines as $line) {
  1052. $line->fetch_optionals();
  1053. }
  1054. // Load source object
  1055. $objFrom = clone $this;
  1056. // Change socid if needed
  1057. if (!empty($socid) && $socid != $this->socid) {
  1058. $objsoc = new Societe($this->db);
  1059. if ($objsoc->fetch($socid) > 0) {
  1060. $this->socid = $objsoc->id;
  1061. $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
  1062. $this->deposit_percent = (!empty($objsoc->deposit_percent) ? $objsoc->deposit_percent : null);
  1063. $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
  1064. $this->fk_project = 0;
  1065. $this->fk_delivery_address = 0;
  1066. }
  1067. // TODO Change product price if multi-prices
  1068. }
  1069. $this->id = 0;
  1070. $this->ref = '';
  1071. $this->statut = self::STATUS_DRAFT;
  1072. // Clear fields
  1073. $this->user_author_id = $user->id;
  1074. $this->user_validation_id = 0;
  1075. $this->date = dol_now();
  1076. $this->date_commande = dol_now();
  1077. $this->date_creation = '';
  1078. $this->date_validation = '';
  1079. if (!getDolGlobalString('MAIN_KEEP_REF_CUSTOMER_ON_CLONING')) {
  1080. $this->ref_client = '';
  1081. $this->ref_customer = '';
  1082. }
  1083. // Do not clone ref_ext
  1084. $num = count($this->lines);
  1085. for ($i = 0; $i < $num; $i++) {
  1086. $this->lines[$i]->ref_ext = '';
  1087. }
  1088. // Create clone
  1089. $this->context['createfromclone'] = 'createfromclone';
  1090. $result = $this->create($user);
  1091. if ($result < 0) {
  1092. $error++;
  1093. }
  1094. if (!$error) {
  1095. // copy internal contacts
  1096. if ($this->copy_linked_contact($objFrom, 'internal') < 0) {
  1097. $error++;
  1098. }
  1099. }
  1100. if (!$error) {
  1101. // copy external contacts if same company
  1102. if ($this->socid == $objFrom->socid) {
  1103. if ($this->copy_linked_contact($objFrom, 'external') < 0) {
  1104. $error++;
  1105. }
  1106. }
  1107. }
  1108. if (!$error) {
  1109. // Hook of thirdparty module
  1110. if (is_object($hookmanager)) {
  1111. $parameters = array('objFrom'=>$objFrom);
  1112. $action = '';
  1113. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1114. if ($reshook < 0) {
  1115. $this->setErrorsFromObject($hookmanager);
  1116. $error++;
  1117. }
  1118. }
  1119. }
  1120. unset($this->context['createfromclone']);
  1121. // End
  1122. if (!$error) {
  1123. $this->db->commit();
  1124. return $this->id;
  1125. } else {
  1126. $this->db->rollback();
  1127. return -1;
  1128. }
  1129. }
  1130. /**
  1131. * Load an object from a proposal and create a new order into database
  1132. *
  1133. * @param Object $object Object source
  1134. * @param User $user User making creation
  1135. * @return int <0 if KO, 0 if nothing done, 1 if OK
  1136. */
  1137. public function createFromProposal($object, User $user)
  1138. {
  1139. global $conf, $hookmanager;
  1140. dol_include_once('/multicurrency/class/multicurrency.class.php');
  1141. dol_include_once('/core/class/extrafields.class.php');
  1142. $error = 0;
  1143. $this->date_commande = dol_now();
  1144. $this->date = dol_now();
  1145. $this->source = 0;
  1146. $num = count($object->lines);
  1147. for ($i = 0; $i < $num; $i++) {
  1148. $line = new OrderLine($this->db);
  1149. $line->libelle = $object->lines[$i]->libelle;
  1150. $line->label = $object->lines[$i]->label;
  1151. $line->desc = $object->lines[$i]->desc;
  1152. $line->price = $object->lines[$i]->price;
  1153. $line->subprice = $object->lines[$i]->subprice;
  1154. $line->vat_src_code = $object->lines[$i]->vat_src_code;
  1155. $line->tva_tx = $object->lines[$i]->tva_tx;
  1156. $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
  1157. $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
  1158. $line->qty = $object->lines[$i]->qty;
  1159. $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
  1160. $line->remise_percent = $object->lines[$i]->remise_percent;
  1161. $line->fk_product = $object->lines[$i]->fk_product;
  1162. $line->info_bits = $object->lines[$i]->info_bits;
  1163. $line->product_type = $object->lines[$i]->product_type;
  1164. $line->rang = $object->lines[$i]->rang;
  1165. $line->special_code = $object->lines[$i]->special_code;
  1166. $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
  1167. $line->fk_unit = $object->lines[$i]->fk_unit;
  1168. $line->date_start = $object->lines[$i]->date_start;
  1169. $line->date_end = $object->lines[$i]->date_end;
  1170. $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
  1171. $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
  1172. $line->pa_ht = $marginInfos[0];
  1173. $line->marge_tx = $marginInfos[1];
  1174. $line->marque_tx = $marginInfos[2];
  1175. $line->origin = $object->element;
  1176. $line->origin_id = $object->lines[$i]->id;
  1177. // get extrafields from original line
  1178. $object->lines[$i]->fetch_optionals();
  1179. foreach ($object->lines[$i]->array_options as $options_key => $value) {
  1180. $line->array_options[$options_key] = $value;
  1181. }
  1182. $this->lines[$i] = $line;
  1183. }
  1184. $this->entity = $object->entity;
  1185. $this->socid = $object->socid;
  1186. $this->fk_project = $object->fk_project;
  1187. $this->cond_reglement_id = $object->cond_reglement_id;
  1188. $this->deposit_percent = $object->deposit_percent;
  1189. $this->mode_reglement_id = $object->mode_reglement_id;
  1190. $this->fk_account = $object->fk_account;
  1191. $this->availability_id = $object->availability_id;
  1192. $this->demand_reason_id = $object->demand_reason_id;
  1193. $this->delivery_date = $object->delivery_date;
  1194. $this->shipping_method_id = $object->shipping_method_id;
  1195. $this->warehouse_id = $object->warehouse_id;
  1196. $this->fk_delivery_address = $object->fk_delivery_address;
  1197. $this->contact_id = $object->contact_id;
  1198. $this->ref_client = $object->ref_client;
  1199. $this->ref_customer = $object->ref_client;
  1200. if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) {
  1201. $this->note_private = $object->note_private;
  1202. $this->note_public = $object->note_public;
  1203. }
  1204. $this->origin = $object->element;
  1205. $this->origin_id = $object->id;
  1206. // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
  1207. if (!empty($conf->multicurrency->enabled)) {
  1208. if (!empty($object->multicurrency_code)) {
  1209. $this->multicurrency_code = $object->multicurrency_code;
  1210. }
  1211. if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($object->multicurrency_tx)) {
  1212. $this->multicurrency_tx = $object->multicurrency_tx;
  1213. }
  1214. if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
  1215. $tmparray = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date_commande);
  1216. $this->fk_multicurrency = $tmparray[0];
  1217. $this->multicurrency_tx = $tmparray[1];
  1218. } else {
  1219. $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  1220. }
  1221. if (empty($this->fk_multicurrency)) {
  1222. $this->multicurrency_code = $conf->currency;
  1223. $this->fk_multicurrency = 0;
  1224. $this->multicurrency_tx = 1;
  1225. }
  1226. }
  1227. // get extrafields from original line
  1228. $object->fetch_optionals();
  1229. $e = new ExtraFields($this->db);
  1230. $element_extrafields = $e->fetch_name_optionals_label($this->table_element);
  1231. foreach ($object->array_options as $options_key => $value) {
  1232. if (array_key_exists(str_replace('options_', '', $options_key), $element_extrafields)) {
  1233. $this->array_options[$options_key] = $value;
  1234. }
  1235. }
  1236. // Possibility to add external linked objects with hooks
  1237. $this->linked_objects[$this->origin] = $this->origin_id;
  1238. if (isset($object->other_linked_objects) && is_array($object->other_linked_objects) && !empty($object->other_linked_objects)) {
  1239. $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
  1240. }
  1241. $ret = $this->create($user);
  1242. if ($ret > 0) {
  1243. // Actions hooked (by external module)
  1244. $hookmanager->initHooks(array('orderdao'));
  1245. $parameters = array('objFrom'=>$object);
  1246. $action = '';
  1247. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1248. if ($reshook < 0) {
  1249. $this->setErrorsFromObject($hookmanager);
  1250. $error++;
  1251. }
  1252. if (!$error) {
  1253. // Validate immediatly the order
  1254. if (getDolGlobalString('ORDER_VALID_AFTER_CLOSE_PROPAL')) {
  1255. $this->fetch($ret);
  1256. $this->valid($user);
  1257. }
  1258. return $ret;
  1259. } else {
  1260. return -1;
  1261. }
  1262. } else {
  1263. return -1;
  1264. }
  1265. }
  1266. /**
  1267. * Add an order line into database (linked to product/service or not)
  1268. *
  1269. * @param string $desc Description of line
  1270. * @param float $pu_ht Unit price (without tax)
  1271. * @param float $qty Quantite
  1272. * @param float $txtva Force Vat rate, -1 for auto (Can contain the vat_src_code too with syntax '9.9 (CODE)')
  1273. * @param float $txlocaltax1 Local tax 1 rate (deprecated, use instead txtva with code inside)
  1274. * @param float $txlocaltax2 Local tax 2 rate (deprecated, use instead txtva with code inside)
  1275. * @param int $fk_product Id of product
  1276. * @param float $remise_percent Percentage discount of the line
  1277. * @param int $info_bits Bits of type of lines
  1278. * @param int $fk_remise_except Id remise
  1279. * @param string $price_base_type HT or TTC
  1280. * @param float $pu_ttc Prix unitaire TTC
  1281. * @param int $date_start Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
  1282. * @param int $date_end End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html)
  1283. * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
  1284. * @param int $rang Position of line
  1285. * @param int $special_code Special code (also used by externals modules!)
  1286. * @param int $fk_parent_line Parent line
  1287. * @param int $fk_fournprice Id supplier price
  1288. * @param int $pa_ht Buying price (without tax)
  1289. * @param string $label Label
  1290. * @param array $array_options extrafields array. Example array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  1291. * @param string $fk_unit Code of the unit to use. Null to use the default one
  1292. * @param string $origin Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be 'orderdet', 'propaldet'..., else 'order','propal,'....
  1293. * @param int $origin_id Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be Id of origin object (aka line id), else object id
  1294. * @param double $pu_ht_devise Unit price in currency
  1295. * @param string $ref_ext line external reference
  1296. * @param int $noupdateafterinsertline No update after insert of line
  1297. * @return int >0 if OK, <0 if KO
  1298. *
  1299. * @see add_product()
  1300. *
  1301. * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
  1302. * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
  1303. * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit)
  1304. * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
  1305. */
  1306. public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $info_bits = 0, $fk_remise_except = 0, $price_base_type = 'HT', $pu_ttc = 0, $date_start = '', $date_end = '', $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $array_options = 0, $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $ref_ext = '', $noupdateafterinsertline = 0)
  1307. {
  1308. global $mysoc, $conf, $langs, $user;
  1309. $logtext = "::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent";
  1310. $logtext .= ", info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start";
  1311. $logtext .= ", date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise, ref_ext=$ref_ext";
  1312. dol_syslog(get_class($this).$logtext, LOG_DEBUG);
  1313. if ($this->statut == self::STATUS_DRAFT) {
  1314. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1315. // Clean parameters
  1316. if (empty($remise_percent)) {
  1317. $remise_percent = 0;
  1318. }
  1319. if (empty($qty)) {
  1320. $qty = 0;
  1321. }
  1322. if (empty($info_bits)) {
  1323. $info_bits = 0;
  1324. }
  1325. if (empty($rang)) {
  1326. $rang = 0;
  1327. }
  1328. if (empty($txtva)) {
  1329. $txtva = 0;
  1330. }
  1331. if (empty($txlocaltax1)) {
  1332. $txlocaltax1 = 0;
  1333. }
  1334. if (empty($txlocaltax2)) {
  1335. $txlocaltax2 = 0;
  1336. }
  1337. if (empty($fk_parent_line) || $fk_parent_line < 0) {
  1338. $fk_parent_line = 0;
  1339. }
  1340. if (empty($this->fk_multicurrency)) {
  1341. $this->fk_multicurrency = 0;
  1342. }
  1343. if (empty($ref_ext)) {
  1344. $ref_ext = '';
  1345. }
  1346. $remise_percent = price2num($remise_percent);
  1347. $qty = price2num($qty);
  1348. $pu_ht = price2num($pu_ht);
  1349. $pu_ht_devise = price2num($pu_ht_devise);
  1350. $pu_ttc = price2num($pu_ttc);
  1351. $pa_ht = price2num($pa_ht);
  1352. if (!preg_match('/\((.*)\)/', $txtva)) {
  1353. $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
  1354. }
  1355. $txlocaltax1 = price2num($txlocaltax1);
  1356. $txlocaltax2 = price2num($txlocaltax2);
  1357. if ($price_base_type == 'HT') {
  1358. $pu = $pu_ht;
  1359. } else {
  1360. $pu = $pu_ttc;
  1361. }
  1362. $label = trim($label);
  1363. $desc = trim($desc);
  1364. // Check parameters
  1365. if ($type < 0) {
  1366. return -1;
  1367. }
  1368. if ($date_start && $date_end && $date_start > $date_end) {
  1369. $langs->load("errors");
  1370. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  1371. return -1;
  1372. }
  1373. $this->db->begin();
  1374. $product_type = $type;
  1375. if (!empty($fk_product) && $fk_product > 0) {
  1376. $product = new Product($this->db);
  1377. $result = $product->fetch($fk_product);
  1378. $product_type = $product->type;
  1379. if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_ORDER') && $product_type == 0 && $product->stock_reel < $qty) {
  1380. $langs->load("errors");
  1381. $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
  1382. $this->errors[] = $this->error;
  1383. dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
  1384. $this->db->rollback();
  1385. return self::STOCK_NOT_ENOUGH_FOR_ORDER;
  1386. }
  1387. }
  1388. // Calcul du total TTC et de la TVA pour la ligne a partir de
  1389. // qty, pu, remise_percent et txtva
  1390. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1391. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1392. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  1393. // Clean vat code
  1394. $reg = array();
  1395. $vat_src_code = '';
  1396. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  1397. $vat_src_code = $reg[1];
  1398. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  1399. }
  1400. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
  1401. /*var_dump($txlocaltax1);
  1402. var_dump($txlocaltax2);
  1403. var_dump($localtaxes_type);
  1404. var_dump($tabprice);
  1405. var_dump($tabprice[9]);
  1406. var_dump($tabprice[10]);
  1407. exit;*/
  1408. $total_ht = $tabprice[0];
  1409. $total_tva = $tabprice[1];
  1410. $total_ttc = $tabprice[2];
  1411. $total_localtax1 = $tabprice[9];
  1412. $total_localtax2 = $tabprice[10];
  1413. $pu_ht = $tabprice[3];
  1414. // MultiCurrency
  1415. $multicurrency_total_ht = $tabprice[16];
  1416. $multicurrency_total_tva = $tabprice[17];
  1417. $multicurrency_total_ttc = $tabprice[18];
  1418. $pu_ht_devise = $tabprice[19];
  1419. // Rang to use
  1420. $ranktouse = $rang;
  1421. if ($ranktouse == -1) {
  1422. $rangmax = $this->line_max($fk_parent_line);
  1423. $ranktouse = $rangmax + 1;
  1424. }
  1425. // TODO A virer
  1426. // Anciens indicateurs: $price, $remise (a ne plus utiliser)
  1427. $price = $pu;
  1428. $remise = 0;
  1429. if ($remise_percent > 0) {
  1430. $remise = round(($pu * $remise_percent / 100), 2);
  1431. $price = $pu - $remise;
  1432. }
  1433. // Insert line
  1434. $this->line = new OrderLine($this->db);
  1435. $this->line->context = $this->context;
  1436. $this->line->fk_commande = $this->id;
  1437. $this->line->label = $label;
  1438. $this->line->desc = $desc;
  1439. $this->line->qty = $qty;
  1440. $this->line->ref_ext = $ref_ext;
  1441. $this->line->vat_src_code = $vat_src_code;
  1442. $this->line->tva_tx = $txtva;
  1443. $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
  1444. $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
  1445. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  1446. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  1447. $this->line->fk_product = $fk_product;
  1448. $this->line->product_type = $product_type;
  1449. $this->line->fk_remise_except = $fk_remise_except;
  1450. $this->line->remise_percent = $remise_percent;
  1451. $this->line->subprice = $pu_ht;
  1452. $this->line->rang = $ranktouse;
  1453. $this->line->info_bits = $info_bits;
  1454. $this->line->total_ht = $total_ht;
  1455. $this->line->total_tva = $total_tva;
  1456. $this->line->total_localtax1 = $total_localtax1;
  1457. $this->line->total_localtax2 = $total_localtax2;
  1458. $this->line->total_ttc = $total_ttc;
  1459. $this->line->special_code = $special_code;
  1460. $this->line->origin = $origin;
  1461. $this->line->origin_id = $origin_id;
  1462. $this->line->fk_parent_line = $fk_parent_line;
  1463. $this->line->fk_unit = $fk_unit;
  1464. $this->line->date_start = $date_start;
  1465. $this->line->date_end = $date_end;
  1466. $this->line->fk_fournprice = $fk_fournprice;
  1467. $this->line->pa_ht = $pa_ht;
  1468. // Multicurrency
  1469. $this->line->fk_multicurrency = $this->fk_multicurrency;
  1470. $this->line->multicurrency_code = $this->multicurrency_code;
  1471. $this->line->multicurrency_subprice = $pu_ht_devise;
  1472. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  1473. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  1474. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  1475. // TODO Ne plus utiliser
  1476. $this->line->price = $price;
  1477. if (is_array($array_options) && count($array_options) > 0) {
  1478. $this->line->array_options = $array_options;
  1479. }
  1480. $result = $this->line->insert($user);
  1481. if ($result > 0) {
  1482. // Reorder if child line
  1483. if (!empty($fk_parent_line)) {
  1484. $this->line_order(true, 'DESC');
  1485. } elseif ($ranktouse > 0 && $ranktouse <= count($this->lines)) { // Update all rank of all other lines
  1486. $linecount = count($this->lines);
  1487. for ($ii = $ranktouse; $ii <= $linecount; $ii++) {
  1488. $this->updateRangOfLine($this->lines[$ii - 1]->id, $ii + 1);
  1489. }
  1490. }
  1491. // Mise a jour informations denormalisees au niveau de la commande meme
  1492. if (empty($noupdateafterinsertline)) {
  1493. $result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
  1494. }
  1495. if ($result > 0) {
  1496. $this->db->commit();
  1497. return $this->line->id;
  1498. } else {
  1499. $this->db->rollback();
  1500. return -1;
  1501. }
  1502. } else {
  1503. $this->error = $this->line->error;
  1504. dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
  1505. $this->db->rollback();
  1506. return -2;
  1507. }
  1508. } else {
  1509. dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR);
  1510. return -3;
  1511. }
  1512. }
  1513. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1514. /**
  1515. * Add line into array
  1516. * $this->client must be loaded
  1517. *
  1518. * @param int $idproduct Product Id
  1519. * @param float $qty Quantity
  1520. * @param float $remise_percent Product discount relative
  1521. * @param int $date_start Start date of the line
  1522. * @param int $date_end End date of the line
  1523. * @return void
  1524. *
  1525. * TODO Remplacer les appels a cette fonction par generation objet Ligne
  1526. */
  1527. public function add_product($idproduct, $qty, $remise_percent = 0.0, $date_start = '', $date_end = '')
  1528. {
  1529. // phpcs:enable
  1530. global $conf, $mysoc;
  1531. if (!$qty) {
  1532. $qty = 1;
  1533. }
  1534. if ($idproduct > 0) {
  1535. $prod = new Product($this->db);
  1536. $prod->fetch($idproduct);
  1537. $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id);
  1538. $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id);
  1539. if (empty($tva_tx)) {
  1540. $tva_npr = 0;
  1541. }
  1542. $vat_src_code = ''; // May be defined into tva_tx
  1543. $localtax1_tx = get_localtax($tva_tx, 1, $this->thirdparty, $mysoc, $tva_npr);
  1544. $localtax2_tx = get_localtax($tva_tx, 2, $this->thirdparty, $mysoc, $tva_npr);
  1545. // multiprix
  1546. if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) {
  1547. $price = $prod->multiprices[$this->thirdparty->price_level];
  1548. } else {
  1549. $price = $prod->price;
  1550. }
  1551. $line = new OrderLine($this->db);
  1552. $line->context = $this->context;
  1553. $line->fk_product = $idproduct;
  1554. $line->desc = $prod->description;
  1555. $line->qty = $qty;
  1556. $line->subprice = $price;
  1557. $line->remise_percent = $remise_percent;
  1558. $line->vat_src_code = $vat_src_code;
  1559. $line->tva_tx = $tva_tx;
  1560. $line->localtax1_tx = $localtax1_tx;
  1561. $line->localtax2_tx = $localtax2_tx;
  1562. $line->product_ref = $prod->ref;
  1563. $line->product_label = $prod->label;
  1564. $line->product_desc = $prod->description;
  1565. $line->fk_unit = $prod->fk_unit;
  1566. // Save the start and end date of the line in the object
  1567. if ($date_start) {
  1568. $line->date_start = $date_start;
  1569. }
  1570. if ($date_end) {
  1571. $line->date_end = $date_end;
  1572. }
  1573. $this->lines[] = $line;
  1574. /** POUR AJOUTER AUTOMATIQUEMENT LES SOUSPRODUITS a LA COMMANDE
  1575. if (!empty($conf->global->PRODUIT_SOUSPRODUITS))
  1576. {
  1577. $prod = new Product($this->db);
  1578. $prod->fetch($idproduct);
  1579. $prod -> get_sousproduits_arbo();
  1580. $prods_arbo = $prod->get_arbo_each_prod();
  1581. if(count($prods_arbo) > 0)
  1582. {
  1583. foreach($prods_arbo as $key => $value)
  1584. {
  1585. // print "id : ".$value[1].' :qty: '.$value[0].'<br>';
  1586. if not in lines {
  1587. $this->add_product($value[1], $value[0]);
  1588. }
  1589. }
  1590. }
  1591. **/
  1592. }
  1593. }
  1594. /**
  1595. * Get object from database. Get also lines.
  1596. *
  1597. * @param int $id Id of object to load
  1598. * @param string $ref Ref of object
  1599. * @param string $ref_ext External reference of object
  1600. * @param string $notused Internal reference of other object
  1601. * @return int >0 if OK, <0 if KO, 0 if not found
  1602. */
  1603. public function fetch($id, $ref = '', $ref_ext = '', $notused = '')
  1604. {
  1605. // Check parameters
  1606. if (empty($id) && empty($ref) && empty($ref_ext)) {
  1607. return -1;
  1608. }
  1609. $sql = 'SELECT c.rowid, c.entity, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_user_modif, c.fk_statut';
  1610. $sql .= ', c.amount_ht, c.total_ht, c.total_ttc, c.total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.deposit_percent, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
  1611. $sql .= ', c.fk_account';
  1612. $sql .= ', c.date_commande, c.date_valid, c.tms';
  1613. $sql .= ', c.date_livraison as delivery_date';
  1614. $sql .= ', c.fk_shipping_method';
  1615. $sql .= ', c.fk_warehouse';
  1616. $sql .= ', c.fk_projet as fk_project, c.source, c.facture as billed';
  1617. $sql .= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.model_pdf, c.last_main_doc, c.fk_delivery_address, c.extraparams';
  1618. $sql .= ', c.fk_incoterms, c.location_incoterms';
  1619. $sql .= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
  1620. $sql .= ", c.module_source, c.pos_source";
  1621. $sql .= ", i.libelle as label_incoterms";
  1622. $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
  1623. $sql .= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
  1624. $sql .= ', ca.code as availability_code, ca.label as availability_label';
  1625. $sql .= ', dr.code as demand_reason_code';
  1626. $sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c';
  1627. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid';
  1628. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id';
  1629. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
  1630. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = dr.rowid';
  1631. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
  1632. if ($id) {
  1633. $sql .= " WHERE c.rowid=".((int) $id);
  1634. } else {
  1635. $sql .= " WHERE c.entity IN (".getEntity('commande').")"; // Dont't use entity if you use rowid
  1636. }
  1637. if ($ref) {
  1638. $sql .= " AND c.ref='".$this->db->escape($ref)."'";
  1639. }
  1640. if ($ref_ext) {
  1641. $sql .= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
  1642. }
  1643. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  1644. $result = $this->db->query($sql);
  1645. if ($result) {
  1646. $obj = $this->db->fetch_object($result);
  1647. if ($obj) {
  1648. $this->id = $obj->rowid;
  1649. $this->entity = $obj->entity;
  1650. $this->ref = $obj->ref;
  1651. $this->ref_client = $obj->ref_client;
  1652. $this->ref_customer = $obj->ref_client;
  1653. $this->ref_ext = $obj->ref_ext;
  1654. $this->socid = $obj->fk_soc;
  1655. $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
  1656. $this->fk_project = $obj->fk_project;
  1657. $this->project = null; // Clear if another value was already set by fetch_projet
  1658. $this->statut = $obj->fk_statut;
  1659. $this->status = $obj->fk_statut;
  1660. $this->user_author_id = $obj->fk_user_author;
  1661. $this->user_creation_id = $obj->fk_user_author;
  1662. $this->user_validation_id = $obj->fk_user_valid;
  1663. $this->user_modification_id = $obj->fk_user_modif;
  1664. $this->total_ht = $obj->total_ht;
  1665. $this->total_tva = $obj->total_tva;
  1666. $this->total_localtax1 = $obj->total_localtax1;
  1667. $this->total_localtax2 = $obj->total_localtax2;
  1668. $this->total_ttc = $obj->total_ttc;
  1669. $this->date = $this->db->jdate($obj->date_commande);
  1670. $this->date_commande = $this->db->jdate($obj->date_commande);
  1671. $this->date_creation = $this->db->jdate($obj->date_creation);
  1672. $this->date_validation = $this->db->jdate($obj->date_valid);
  1673. $this->date_modification = $this->db->jdate($obj->tms);
  1674. $this->source = $obj->source;
  1675. $this->billed = $obj->billed;
  1676. $this->note = $obj->note_private; // deprecated
  1677. $this->note_private = $obj->note_private;
  1678. $this->note_public = $obj->note_public;
  1679. $this->model_pdf = $obj->model_pdf;
  1680. $this->last_main_doc = $obj->last_main_doc;
  1681. $this->mode_reglement_id = $obj->fk_mode_reglement;
  1682. $this->mode_reglement_code = $obj->mode_reglement_code;
  1683. $this->mode_reglement = $obj->mode_reglement_libelle;
  1684. $this->cond_reglement_id = $obj->fk_cond_reglement;
  1685. $this->cond_reglement_code = $obj->cond_reglement_code;
  1686. $this->cond_reglement = $obj->cond_reglement_libelle;
  1687. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  1688. $this->deposit_percent = $obj->deposit_percent;
  1689. $this->fk_account = $obj->fk_account;
  1690. $this->availability_id = $obj->fk_availability;
  1691. $this->availability_code = $obj->availability_code;
  1692. $this->availability = $obj->availability_label;
  1693. $this->demand_reason_id = $obj->fk_input_reason;
  1694. $this->demand_reason_code = $obj->demand_reason_code;
  1695. $this->delivery_date = $this->db->jdate($obj->delivery_date);
  1696. $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
  1697. $this->warehouse_id = ($obj->fk_warehouse > 0) ? $obj->fk_warehouse : null;
  1698. $this->fk_delivery_address = $obj->fk_delivery_address;
  1699. $this->module_source = $obj->module_source;
  1700. $this->pos_source = $obj->pos_source;
  1701. //Incoterms
  1702. $this->fk_incoterms = $obj->fk_incoterms;
  1703. $this->location_incoterms = $obj->location_incoterms;
  1704. $this->label_incoterms = $obj->label_incoterms;
  1705. // Multicurrency
  1706. $this->fk_multicurrency = $obj->fk_multicurrency;
  1707. $this->multicurrency_code = $obj->multicurrency_code;
  1708. $this->multicurrency_tx = $obj->multicurrency_tx;
  1709. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  1710. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  1711. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  1712. $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
  1713. $this->lines = array();
  1714. // Retrieve all extrafield
  1715. // fetch optionals attributes and labels
  1716. $this->fetch_optionals();
  1717. $this->db->free($result);
  1718. // Lines
  1719. $result = $this->fetch_lines();
  1720. if ($result < 0) {
  1721. return -3;
  1722. }
  1723. return 1;
  1724. } else {
  1725. $this->error = 'Order with id '.$id.' not found sql='.$sql;
  1726. return 0;
  1727. }
  1728. } else {
  1729. $this->error = $this->db->error();
  1730. return -1;
  1731. }
  1732. }
  1733. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1734. /**
  1735. * Adding line of fixed discount in the order in DB
  1736. *
  1737. * @param int $idremise Id de la remise fixe
  1738. * @return int >0 si ok, <0 si ko
  1739. */
  1740. public function insert_discount($idremise)
  1741. {
  1742. // phpcs:enable
  1743. global $langs;
  1744. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1745. include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  1746. $this->db->begin();
  1747. $remise = new DiscountAbsolute($this->db);
  1748. $result = $remise->fetch($idremise);
  1749. if ($result > 0) {
  1750. if ($remise->fk_facture) { // Protection against multiple submission
  1751. $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
  1752. $this->db->rollback();
  1753. return -5;
  1754. }
  1755. $line = new OrderLine($this->db);
  1756. $line->fk_commande = $this->id;
  1757. $line->fk_remise_except = $remise->id;
  1758. $line->desc = $remise->description; // Description ligne
  1759. $line->vat_src_code = $remise->vat_src_code;
  1760. $line->tva_tx = $remise->tva_tx;
  1761. $line->subprice = -$remise->amount_ht;
  1762. $line->price = -$remise->amount_ht;
  1763. $line->fk_product = 0; // Id produit predefini
  1764. $line->qty = 1;
  1765. $line->remise_percent = 0;
  1766. $line->rang = -1;
  1767. $line->info_bits = 2;
  1768. $line->total_ht = -$remise->amount_ht;
  1769. $line->total_tva = -$remise->amount_tva;
  1770. $line->total_ttc = -$remise->amount_ttc;
  1771. $result = $line->insert();
  1772. if ($result > 0) {
  1773. $result = $this->update_price(1);
  1774. if ($result > 0) {
  1775. $this->db->commit();
  1776. return 1;
  1777. } else {
  1778. $this->db->rollback();
  1779. return -1;
  1780. }
  1781. } else {
  1782. $this->error = $line->error;
  1783. $this->errors = $line->errors;
  1784. $this->db->rollback();
  1785. return -2;
  1786. }
  1787. } else {
  1788. $this->db->rollback();
  1789. return -2;
  1790. }
  1791. }
  1792. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1793. /**
  1794. * Load array lines
  1795. *
  1796. * @param int $only_product Return only physical products, not services
  1797. * @param int $loadalsotranslation Return translation for products
  1798. * @return int <0 if KO, >0 if OK
  1799. */
  1800. public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
  1801. {
  1802. // phpcs:enable
  1803. global $langs, $conf;
  1804. $this->lines = array();
  1805. $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx, l.ref_ext,';
  1806. $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,';
  1807. $sql .= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,';
  1808. $sql .= ' l.fk_unit,';
  1809. $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
  1810. $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label, p.tosell as product_tosell, p.tobuy as product_tobuy, p.tobatch as product_tobatch, p.barcode as product_barcode,';
  1811. $sql .= ' p.weight, p.weight_units, p.volume, p.volume_units';
  1812. $sql .= ' FROM '.MAIN_DB_PREFIX.'commandedet as l';
  1813. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON (p.rowid = l.fk_product)';
  1814. $sql .= ' WHERE l.fk_commande = '.((int) $this->id);
  1815. if ($only_product) {
  1816. $sql .= ' AND p.fk_product_type = 0';
  1817. }
  1818. $sql .= ' ORDER BY l.rang, l.rowid';
  1819. dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
  1820. $result = $this->db->query($sql);
  1821. if ($result) {
  1822. $num = $this->db->num_rows($result);
  1823. $i = 0;
  1824. while ($i < $num) {
  1825. $objp = $this->db->fetch_object($result);
  1826. $line = new OrderLine($this->db);
  1827. $line->rowid = $objp->rowid;
  1828. $line->id = $objp->rowid;
  1829. $line->fk_commande = $objp->fk_commande;
  1830. $line->commande_id = $objp->fk_commande;
  1831. $line->label = $objp->custom_label;
  1832. $line->desc = $objp->description;
  1833. $line->description = $objp->description; // Description line
  1834. $line->product_type = $objp->product_type;
  1835. $line->qty = $objp->qty;
  1836. $line->ref_ext = $objp->ref_ext;
  1837. $line->vat_src_code = $objp->vat_src_code;
  1838. $line->tva_tx = $objp->tva_tx;
  1839. $line->localtax1_tx = $objp->localtax1_tx;
  1840. $line->localtax2_tx = $objp->localtax2_tx;
  1841. $line->localtax1_type = $objp->localtax1_type;
  1842. $line->localtax2_type = $objp->localtax2_type;
  1843. $line->total_ht = $objp->total_ht;
  1844. $line->total_ttc = $objp->total_ttc;
  1845. $line->total_tva = $objp->total_tva;
  1846. $line->total_localtax1 = $objp->total_localtax1;
  1847. $line->total_localtax2 = $objp->total_localtax2;
  1848. $line->subprice = $objp->subprice;
  1849. $line->fk_remise_except = $objp->fk_remise_except;
  1850. $line->remise_percent = $objp->remise_percent;
  1851. $line->price = $objp->price;
  1852. $line->fk_product = $objp->fk_product;
  1853. $line->fk_fournprice = $objp->fk_fournprice;
  1854. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
  1855. $line->pa_ht = $marginInfos[0];
  1856. $line->marge_tx = $marginInfos[1];
  1857. $line->marque_tx = $marginInfos[2];
  1858. $line->rang = $objp->rang;
  1859. $line->info_bits = $objp->info_bits;
  1860. $line->special_code = $objp->special_code;
  1861. $line->fk_parent_line = $objp->fk_parent_line;
  1862. $line->ref = $objp->product_ref;
  1863. $line->libelle = $objp->product_label;
  1864. $line->product_ref = $objp->product_ref;
  1865. $line->product_label = $objp->product_label;
  1866. $line->product_tosell = $objp->product_tosell;
  1867. $line->product_tobuy = $objp->product_tobuy;
  1868. $line->product_desc = $objp->product_desc;
  1869. $line->product_tobatch = $objp->product_tobatch;
  1870. $line->product_barcode = $objp->product_barcode;
  1871. $line->fk_product_type = $objp->fk_product_type; // Produit ou service
  1872. $line->fk_unit = $objp->fk_unit;
  1873. $line->weight = $objp->weight;
  1874. $line->weight_units = $objp->weight_units;
  1875. $line->volume = $objp->volume;
  1876. $line->volume_units = $objp->volume_units;
  1877. $line->date_start = $this->db->jdate($objp->date_start);
  1878. $line->date_end = $this->db->jdate($objp->date_end);
  1879. // Multicurrency
  1880. $line->fk_multicurrency = $objp->fk_multicurrency;
  1881. $line->multicurrency_code = $objp->multicurrency_code;
  1882. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  1883. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  1884. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  1885. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  1886. $line->fetch_optionals();
  1887. // multilangs
  1888. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
  1889. $tmpproduct = new Product($this->db);
  1890. $tmpproduct->fetch($objp->fk_product);
  1891. $tmpproduct->getMultiLangs();
  1892. $line->multilangs = $tmpproduct->multilangs;
  1893. }
  1894. $this->lines[$i] = $line;
  1895. $i++;
  1896. }
  1897. $this->db->free($result);
  1898. return 1;
  1899. } else {
  1900. $this->error = $this->db->error();
  1901. return -3;
  1902. }
  1903. }
  1904. /**
  1905. * Return number of line with type product.
  1906. *
  1907. * @return int <0 if KO, Nbr of product lines if OK
  1908. */
  1909. public function getNbOfProductsLines()
  1910. {
  1911. $nb = 0;
  1912. foreach ($this->lines as $line) {
  1913. if ($line->product_type == 0) {
  1914. $nb++;
  1915. }
  1916. }
  1917. return $nb;
  1918. }
  1919. /**
  1920. * Return number of line with type service.
  1921. *
  1922. * @return int <0 if KO, Nbr of service lines if OK
  1923. */
  1924. public function getNbOfServicesLines()
  1925. {
  1926. $nb = 0;
  1927. foreach ($this->lines as $line) {
  1928. if ($line->product_type == 1) {
  1929. $nb++;
  1930. }
  1931. }
  1932. return $nb;
  1933. }
  1934. /**
  1935. * Count number of shipments for this order
  1936. *
  1937. * @return int <0 if KO, Nb of shipment found if OK
  1938. */
  1939. public function getNbOfShipments()
  1940. {
  1941. $nb = 0;
  1942. $sql = 'SELECT COUNT(DISTINCT ed.fk_expedition) as nb';
  1943. $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
  1944. $sql .= ' '.MAIN_DB_PREFIX.'commandedet as cd';
  1945. $sql .= ' WHERE';
  1946. $sql .= ' ed.fk_origin_line = cd.rowid';
  1947. $sql .= ' AND cd.fk_commande = '.((int) $this->id);
  1948. //print $sql;
  1949. dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG);
  1950. $resql = $this->db->query($sql);
  1951. if ($resql) {
  1952. $obj = $this->db->fetch_object($resql);
  1953. if ($obj) {
  1954. $nb = $obj->nb;
  1955. }
  1956. $this->db->free($resql);
  1957. return $nb;
  1958. } else {
  1959. $this->error = $this->db->lasterror();
  1960. return -1;
  1961. }
  1962. }
  1963. /**
  1964. * Load array this->expeditions of lines of shipments with nb of products sent for each order line
  1965. * Note: For a dedicated shipment, the fetch_lines can be used to load the qty_asked and qty_shipped. This function is use to return qty_shipped cumulated for the order
  1966. *
  1967. * @param int $filtre_statut Filter on shipment status
  1968. * @param int $fk_product Add a filter on a product
  1969. * @return int <0 if KO, Nb of lines found if OK
  1970. */
  1971. public function loadExpeditions($filtre_statut = -1, $fk_product = 0)
  1972. {
  1973. $this->expeditions = array();
  1974. $sql = 'SELECT cd.rowid, cd.fk_product,';
  1975. $sql .= ' sum(ed.qty) as qty';
  1976. $sql .= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,';
  1977. if ($filtre_statut >= 0) {
  1978. $sql .= ' '.MAIN_DB_PREFIX.'expedition as e,';
  1979. }
  1980. $sql .= ' '.MAIN_DB_PREFIX.'commandedet as cd';
  1981. $sql .= ' WHERE';
  1982. if ($filtre_statut >= 0) {
  1983. $sql .= ' ed.fk_expedition = e.rowid AND';
  1984. }
  1985. $sql .= ' ed.fk_origin_line = cd.rowid';
  1986. $sql .= ' AND cd.fk_commande = '.((int) $this->id);
  1987. if ($fk_product > 0) {
  1988. $sql .= ' AND cd.fk_product = '.((int) $fk_product);
  1989. }
  1990. if ($filtre_statut >= 0) {
  1991. $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut);
  1992. }
  1993. $sql .= ' GROUP BY cd.rowid, cd.fk_product';
  1994. //print $sql;
  1995. dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG);
  1996. $resql = $this->db->query($sql);
  1997. if ($resql) {
  1998. $num = $this->db->num_rows($resql);
  1999. $i = 0;
  2000. while ($i < $num) {
  2001. $obj = $this->db->fetch_object($resql);
  2002. $this->expeditions[$obj->rowid] = $obj->qty;
  2003. $i++;
  2004. }
  2005. $this->db->free($resql);
  2006. return $num;
  2007. } else {
  2008. $this->error = $this->db->lasterror();
  2009. return -1;
  2010. }
  2011. }
  2012. /**
  2013. * Returns an array with expeditions lines number
  2014. *
  2015. * @return int Nb of shipments
  2016. */
  2017. public function countNbOfShipments()
  2018. {
  2019. $sql = 'SELECT count(*)';
  2020. $sql .= ' FROM '.MAIN_DB_PREFIX.'expedition as e';
  2021. $sql .= ', '.MAIN_DB_PREFIX.'element_element as el';
  2022. $sql .= ' WHERE el.fk_source = '.((int) $this->id);
  2023. $sql .= " AND el.sourcetype = 'commande'";
  2024. $sql .= " AND el.fk_target = e.rowid";
  2025. $sql .= " AND el.targettype = 'shipping'";
  2026. $resql = $this->db->query($sql);
  2027. if ($resql) {
  2028. $row = $this->db->fetch_row($resql);
  2029. return $row[0];
  2030. } else {
  2031. dol_print_error($this->db);
  2032. }
  2033. return 0;
  2034. }
  2035. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2036. /**
  2037. * Return a array with the pending stock by product
  2038. *
  2039. * @param int $filtre_statut Filtre sur statut
  2040. * @return int 0 si OK, <0 si KO
  2041. *
  2042. * TODO FONCTION NON FINIE A FINIR
  2043. */
  2044. /*public function stock_array($filtre_statut = self::STATUS_CANCELED)
  2045. {
  2046. // phpcs:enable
  2047. $this->stocks = array();
  2048. // Tableau des id de produit de la commande
  2049. $array_of_product = array();
  2050. // Recherche total en stock pour chaque produit
  2051. // TODO $array_of_product est défini vide juste au dessus !!
  2052. if (count($array_of_product)) {
  2053. $sql = "SELECT fk_product, sum(ps.reel) as total";
  2054. $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
  2055. $sql .= " WHERE ps.fk_product IN (".$this->db->sanitize(join(',', $array_of_product)).")";
  2056. $sql .= ' GROUP BY fk_product';
  2057. $resql = $this->db->query($sql);
  2058. if ($resql) {
  2059. $num = $this->db->num_rows($resql);
  2060. $i = 0;
  2061. while ($i < $num) {
  2062. $obj = $this->db->fetch_object($resql);
  2063. $this->stocks[$obj->fk_product] = $obj->total;
  2064. $i++;
  2065. }
  2066. $this->db->free($resql);
  2067. }
  2068. }
  2069. return 0;
  2070. }*/
  2071. /**
  2072. * Delete an order line
  2073. *
  2074. * @param User $user User object
  2075. * @param int $lineid Id of line to delete
  2076. * @param int $id Id of object (for a check)
  2077. * @return int >0 if OK, 0 if nothing to do, <0 if KO
  2078. */
  2079. public function deleteline($user = null, $lineid = 0, $id = 0)
  2080. {
  2081. if ($this->statut == self::STATUS_DRAFT) {
  2082. $this->db->begin();
  2083. // Delete line
  2084. $line = new OrderLine($this->db);
  2085. $line->context = $this->context;
  2086. // Load data
  2087. $line->fetch($lineid);
  2088. if ($id > 0 && $line->fk_commande != $id) {
  2089. $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
  2090. return -1;
  2091. }
  2092. // Memorize previous line for triggers
  2093. $staticline = clone $line;
  2094. $line->oldline = $staticline;
  2095. if ($line->delete($user) > 0) {
  2096. $result = $this->update_price(1);
  2097. if ($result > 0) {
  2098. $this->db->commit();
  2099. return 1;
  2100. } else {
  2101. $this->db->rollback();
  2102. $this->error = $this->db->lasterror();
  2103. return -1;
  2104. }
  2105. } else {
  2106. $this->db->rollback();
  2107. $this->error = $line->error;
  2108. return -1;
  2109. }
  2110. } else {
  2111. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  2112. return -1;
  2113. }
  2114. }
  2115. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2116. /**
  2117. * Applique une remise relative
  2118. *
  2119. * @deprecated
  2120. * @see setDiscount()
  2121. * @param User $user User qui positionne la remise
  2122. * @param float $remise Discount (percent)
  2123. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2124. * @return int <0 if KO, >0 if OK
  2125. */
  2126. public function set_remise($user, $remise, $notrigger = 0)
  2127. {
  2128. // phpcs:enable
  2129. dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
  2130. return $this->setDiscount($user, $remise, $notrigger);
  2131. }
  2132. /**
  2133. * Set a percentage discount
  2134. *
  2135. * @param User $user User setting the discount
  2136. * @param float $remise Discount (percent)
  2137. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2138. * @return int <0 if KO, >0 if OK
  2139. * @deprecated remise_percent is a deprecated field for object parent
  2140. */
  2141. public function setDiscount($user, $remise, $notrigger = 0)
  2142. {
  2143. $remise = trim($remise) ?trim($remise) : 0;
  2144. if ($user->hasRight('commande', 'creer')) {
  2145. $error = 0;
  2146. $this->db->begin();
  2147. $remise = price2num($remise, 2);
  2148. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
  2149. $sql .= ' SET remise_percent = '.((float) $remise);
  2150. $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.((int) self::STATUS_DRAFT);
  2151. dol_syslog(__METHOD__, LOG_DEBUG);
  2152. $resql = $this->db->query($sql);
  2153. if (!$resql) {
  2154. $this->errors[] = $this->db->error();
  2155. $error++;
  2156. }
  2157. if (!$error) {
  2158. $this->oldcopy = clone $this;
  2159. $this->remise_percent = $remise;
  2160. $this->update_price(1);
  2161. }
  2162. if (!$notrigger && empty($error)) {
  2163. // Call trigger
  2164. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2165. if ($result < 0) {
  2166. $error++;
  2167. }
  2168. // End call triggers
  2169. }
  2170. if (!$error) {
  2171. $this->db->commit();
  2172. return 1;
  2173. } else {
  2174. foreach ($this->errors as $errmsg) {
  2175. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2176. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2177. }
  2178. $this->db->rollback();
  2179. return -1 * $error;
  2180. }
  2181. }
  2182. return 0;
  2183. }
  2184. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2185. /**
  2186. * Set a fixed amount discount
  2187. *
  2188. * @param User $user User qui positionne la remise
  2189. * @param float $remise Discount
  2190. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2191. * @return int <0 if KO, >0 if OK
  2192. */
  2193. /*
  2194. public function set_remise_absolue($user, $remise, $notrigger = 0)
  2195. {
  2196. // phpcs:enable
  2197. if (empty($remise)) {
  2198. $remise = 0;
  2199. }
  2200. $remise = price2num($remise);
  2201. if ($user->hasRight('commande', 'creer')) {
  2202. $error = 0;
  2203. $this->db->begin();
  2204. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
  2205. $sql .= ' SET remise_absolue = '.((float) $remise);
  2206. $sql .= ' WHERE rowid = '.((int) $this->id).' AND fk_statut = '.self::STATUS_DRAFT;
  2207. dol_syslog(__METHOD__, LOG_DEBUG);
  2208. $resql = $this->db->query($sql);
  2209. if (!$resql) {
  2210. $this->errors[] = $this->db->error();
  2211. $error++;
  2212. }
  2213. if (!$error) {
  2214. $this->oldcopy = clone $this;
  2215. $this->remise_absolue = $remise;
  2216. $this->update_price(1);
  2217. }
  2218. if (!$notrigger && empty($error)) {
  2219. // Call trigger
  2220. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2221. if ($result < 0) {
  2222. $error++;
  2223. }
  2224. // End call triggers
  2225. }
  2226. if (!$error) {
  2227. $this->db->commit();
  2228. return 1;
  2229. } else {
  2230. foreach ($this->errors as $errmsg) {
  2231. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2232. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2233. }
  2234. $this->db->rollback();
  2235. return -1 * $error;
  2236. }
  2237. }
  2238. return 0;
  2239. }
  2240. */
  2241. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2242. /**
  2243. * Set the order date
  2244. *
  2245. * @param User $user Object user making change
  2246. * @param int $date Date
  2247. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2248. * @return int <0 if KO, >0 if OK
  2249. */
  2250. public function set_date($user, $date, $notrigger = 0)
  2251. {
  2252. // phpcs:enable
  2253. if ($user->hasRight('commande', 'creer')) {
  2254. $error = 0;
  2255. $this->db->begin();
  2256. $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
  2257. $sql .= " SET date_commande = ".($date ? "'".$this->db->idate($date)."'" : 'null');
  2258. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = ".((int) self::STATUS_DRAFT);
  2259. dol_syslog(__METHOD__, LOG_DEBUG);
  2260. $resql = $this->db->query($sql);
  2261. if (!$resql) {
  2262. $this->errors[] = $this->db->error();
  2263. $error++;
  2264. }
  2265. if (!$error) {
  2266. $this->oldcopy = clone $this;
  2267. $this->date = $date;
  2268. }
  2269. if (!$notrigger && empty($error)) {
  2270. // Call trigger
  2271. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2272. if ($result < 0) {
  2273. $error++;
  2274. }
  2275. // End call triggers
  2276. }
  2277. if (!$error) {
  2278. $this->db->commit();
  2279. return 1;
  2280. } else {
  2281. foreach ($this->errors as $errmsg) {
  2282. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2283. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2284. }
  2285. $this->db->rollback();
  2286. return -1 * $error;
  2287. }
  2288. } else {
  2289. return -2;
  2290. }
  2291. }
  2292. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2293. /**
  2294. * Set delivery date
  2295. *
  2296. * @param User $user Object user that modify
  2297. * @param int $delivery_date Delivery date
  2298. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2299. * @return int <0 if ko, >0 if ok
  2300. * @deprecated Use setDeliveryDate
  2301. */
  2302. public function set_date_livraison($user, $delivery_date, $notrigger = 0)
  2303. {
  2304. // phpcs:enable
  2305. return $this->setDeliveryDate($user, $delivery_date, $notrigger);
  2306. }
  2307. /**
  2308. * Set the planned delivery date
  2309. *
  2310. * @param User $user Objet utilisateur qui modifie
  2311. * @param int $delivery_date Delivery date
  2312. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2313. * @return int <0 si ko, >0 si ok
  2314. */
  2315. public function setDeliveryDate($user, $delivery_date, $notrigger = 0)
  2316. {
  2317. if ($user->hasRight('commande', 'creer')) {
  2318. $error = 0;
  2319. $this->db->begin();
  2320. $sql = "UPDATE ".MAIN_DB_PREFIX."commande";
  2321. $sql .= " SET date_livraison = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
  2322. $sql .= " WHERE rowid = ".((int) $this->id);
  2323. dol_syslog(__METHOD__, LOG_DEBUG);
  2324. $resql = $this->db->query($sql);
  2325. if (!$resql) {
  2326. $this->errors[] = $this->db->error();
  2327. $error++;
  2328. }
  2329. if (!$error) {
  2330. $this->oldcopy = clone $this;
  2331. $this->delivery_date = $delivery_date;
  2332. }
  2333. if (!$notrigger && empty($error)) {
  2334. // Call trigger
  2335. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2336. if ($result < 0) {
  2337. $error++;
  2338. }
  2339. // End call triggers
  2340. }
  2341. if (!$error) {
  2342. $this->db->commit();
  2343. return 1;
  2344. } else {
  2345. foreach ($this->errors as $errmsg) {
  2346. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2347. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2348. }
  2349. $this->db->rollback();
  2350. return -1 * $error;
  2351. }
  2352. } else {
  2353. return -2;
  2354. }
  2355. }
  2356. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2357. /**
  2358. * Return list of orders (eventuelly filtered on a user) into an array
  2359. *
  2360. * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
  2361. * @param int $draft 0=not draft, 1=draft
  2362. * @param User $excluser Objet user to exclude
  2363. * @param int $socid Id third pary
  2364. * @param int $limit For pagination
  2365. * @param int $offset For pagination
  2366. * @param string $sortfield Sort criteria
  2367. * @param string $sortorder Sort order
  2368. * @return int|array -1 if KO, array with result if OK
  2369. */
  2370. public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'c.date_commande', $sortorder = 'DESC')
  2371. {
  2372. // phpcs:enable
  2373. global $user;
  2374. $ga = array();
  2375. $sql = "SELECT s.rowid, s.nom as name, s.client,";
  2376. $sql .= " c.rowid as cid, c.ref";
  2377. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  2378. $sql .= ", sc.fk_soc, sc.fk_user";
  2379. }
  2380. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
  2381. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) {
  2382. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  2383. }
  2384. $sql .= " WHERE c.entity IN (".getEntity('commande').")";
  2385. $sql .= " AND c.fk_soc = s.rowid";
  2386. if (!$user->hasRight('societe', 'client', 'voir') && !$socid) { //restriction
  2387. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2388. }
  2389. if ($socid) {
  2390. $sql .= " AND s.rowid = ".((int) $socid);
  2391. }
  2392. if ($draft) {
  2393. $sql .= " AND c.fk_statut = ".self::STATUS_DRAFT;
  2394. }
  2395. if (is_object($excluser)) {
  2396. $sql .= " AND c.fk_user_author <> ".((int) $excluser->id);
  2397. }
  2398. $sql .= $this->db->order($sortfield, $sortorder);
  2399. $sql .= $this->db->plimit($limit, $offset);
  2400. $result = $this->db->query($sql);
  2401. if ($result) {
  2402. $numc = $this->db->num_rows($result);
  2403. if ($numc) {
  2404. $i = 0;
  2405. while ($i < $numc) {
  2406. $obj = $this->db->fetch_object($result);
  2407. if ($shortlist == 1) {
  2408. $ga[$obj->cid] = $obj->ref;
  2409. } elseif ($shortlist == 2) {
  2410. $ga[$obj->cid] = $obj->ref.' ('.$obj->name.')';
  2411. } else {
  2412. $ga[$i]['id'] = $obj->cid;
  2413. $ga[$i]['ref'] = $obj->ref;
  2414. $ga[$i]['name'] = $obj->name;
  2415. }
  2416. $i++;
  2417. }
  2418. }
  2419. return $ga;
  2420. } else {
  2421. dol_print_error($this->db);
  2422. return -1;
  2423. }
  2424. }
  2425. /**
  2426. * Update delivery delay
  2427. *
  2428. * @param int $availability_id Id du nouveau mode
  2429. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2430. * @return int >0 if OK, <0 if KO
  2431. */
  2432. public function availability($availability_id, $notrigger = 0)
  2433. {
  2434. global $user;
  2435. dol_syslog('Commande::availability('.$availability_id.')');
  2436. if ($this->statut >= self::STATUS_DRAFT) {
  2437. $error = 0;
  2438. $this->db->begin();
  2439. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
  2440. $sql .= ' SET fk_availability = '.((int) $availability_id);
  2441. $sql .= ' WHERE rowid='.((int) $this->id);
  2442. dol_syslog(__METHOD__, LOG_DEBUG);
  2443. $resql = $this->db->query($sql);
  2444. if (!$resql) {
  2445. $this->errors[] = $this->db->error();
  2446. $error++;
  2447. }
  2448. if (!$error) {
  2449. $this->oldcopy = clone $this;
  2450. $this->availability_id = $availability_id;
  2451. }
  2452. if (!$notrigger && empty($error)) {
  2453. // Call trigger
  2454. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2455. if ($result < 0) {
  2456. $error++;
  2457. }
  2458. // End call triggers
  2459. }
  2460. if (!$error) {
  2461. $this->db->commit();
  2462. return 1;
  2463. } else {
  2464. foreach ($this->errors as $errmsg) {
  2465. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2466. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2467. }
  2468. $this->db->rollback();
  2469. return -1 * $error;
  2470. }
  2471. } else {
  2472. $error_str = 'Command status do not meet requirement '.$this->statut;
  2473. dol_syslog(__METHOD__.$error_str, LOG_ERR);
  2474. $this->error = $error_str;
  2475. $this->errors[] = $this->error;
  2476. return -2;
  2477. }
  2478. }
  2479. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2480. /**
  2481. * Update order demand_reason
  2482. *
  2483. * @param int $demand_reason_id Id of new demand
  2484. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2485. * @return int >0 if ok, <0 if ko
  2486. */
  2487. public function demand_reason($demand_reason_id, $notrigger = 0)
  2488. {
  2489. // phpcs:enable
  2490. global $user;
  2491. dol_syslog('Commande::demand_reason('.$demand_reason_id.')');
  2492. if ($this->statut >= self::STATUS_DRAFT) {
  2493. $error = 0;
  2494. $this->db->begin();
  2495. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande';
  2496. $sql .= ' SET fk_input_reason = '.((int) $demand_reason_id);
  2497. $sql .= ' WHERE rowid='.((int) $this->id);
  2498. dol_syslog(__METHOD__, LOG_DEBUG);
  2499. $resql = $this->db->query($sql);
  2500. if (!$resql) {
  2501. $this->errors[] = $this->db->error();
  2502. $error++;
  2503. }
  2504. if (!$error) {
  2505. $this->oldcopy = clone $this;
  2506. $this->demand_reason_id = $demand_reason_id;
  2507. }
  2508. if (!$notrigger && empty($error)) {
  2509. // Call trigger
  2510. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2511. if ($result < 0) {
  2512. $error++;
  2513. }
  2514. // End call triggers
  2515. }
  2516. if (!$error) {
  2517. $this->db->commit();
  2518. return 1;
  2519. } else {
  2520. foreach ($this->errors as $errmsg) {
  2521. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2522. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2523. }
  2524. $this->db->rollback();
  2525. return -1 * $error;
  2526. }
  2527. } else {
  2528. $error_str = 'order status do not meet requirement '.$this->statut;
  2529. dol_syslog(__METHOD__.$error_str, LOG_ERR);
  2530. $this->error = $error_str;
  2531. $this->errors[] = $this->error;
  2532. return -2;
  2533. }
  2534. }
  2535. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2536. /**
  2537. * Set customer ref
  2538. *
  2539. * @param User $user User that make change
  2540. * @param string $ref_client Customer ref
  2541. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2542. * @return int <0 if KO, >0 if OK
  2543. */
  2544. public function set_ref_client($user, $ref_client, $notrigger = 0)
  2545. {
  2546. // phpcs:enable
  2547. if ($user->hasRight('commande', 'creer')) {
  2548. $error = 0;
  2549. $this->db->begin();
  2550. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET';
  2551. $sql .= ' ref_client = '.(empty($ref_client) ? 'NULL' : "'".$this->db->escape($ref_client)."'");
  2552. $sql .= ' WHERE rowid = '.((int) $this->id);
  2553. dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
  2554. $resql = $this->db->query($sql);
  2555. if (!$resql) {
  2556. $this->errors[] = $this->db->error();
  2557. $error++;
  2558. }
  2559. if (!$error) {
  2560. $this->oldcopy = clone $this;
  2561. $this->ref_client = $ref_client;
  2562. $this->ref_customer = $ref_client;
  2563. }
  2564. if (!$notrigger && empty($error)) {
  2565. // Call trigger
  2566. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2567. if ($result < 0) {
  2568. $error++;
  2569. }
  2570. // End call triggers
  2571. }
  2572. if (!$error) {
  2573. $this->db->commit();
  2574. return 1;
  2575. } else {
  2576. foreach ($this->errors as $errmsg) {
  2577. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  2578. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2579. }
  2580. $this->db->rollback();
  2581. return -1 * $error;
  2582. }
  2583. } else {
  2584. return -1;
  2585. }
  2586. }
  2587. /**
  2588. * Classify the order as invoiced
  2589. *
  2590. * @param User $user Object user making the change
  2591. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  2592. * @return int <0 if KO, 0 if already billed, >0 if OK
  2593. */
  2594. public function classifyBilled(User $user, $notrigger = 0)
  2595. {
  2596. $error = 0;
  2597. if ($this->billed) {
  2598. return 0;
  2599. }
  2600. $this->db->begin();
  2601. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 1';
  2602. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
  2603. dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
  2604. if ($this->db->query($sql)) {
  2605. if (!$error) {
  2606. $this->oldcopy = clone $this;
  2607. $this->billed = 1;
  2608. }
  2609. if (!$notrigger && empty($error)) {
  2610. // Call trigger
  2611. $result = $this->call_trigger('ORDER_CLASSIFY_BILLED', $user);
  2612. if ($result < 0) {
  2613. $error++;
  2614. }
  2615. // End call triggers
  2616. }
  2617. if (!$error) {
  2618. $this->db->commit();
  2619. return 1;
  2620. } else {
  2621. foreach ($this->errors as $errmsg) {
  2622. dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR);
  2623. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2624. }
  2625. $this->db->rollback();
  2626. return -1 * $error;
  2627. }
  2628. } else {
  2629. $this->error = $this->db->error();
  2630. $this->db->rollback();
  2631. return -1;
  2632. }
  2633. }
  2634. /**
  2635. * Classify the order as not invoiced
  2636. *
  2637. * @param User $user Object user making the change
  2638. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  2639. * @return int <0 if ko, >0 if ok
  2640. */
  2641. public function classifyUnBilled(User $user, $notrigger = 0)
  2642. {
  2643. $error = 0;
  2644. $this->db->begin();
  2645. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 0';
  2646. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > '.self::STATUS_DRAFT;
  2647. dol_syslog(get_class($this)."::classifyUnBilled", LOG_DEBUG);
  2648. if ($this->db->query($sql)) {
  2649. if (!$error) {
  2650. $this->oldcopy = clone $this;
  2651. $this->billed = 1;
  2652. }
  2653. if (!$notrigger && empty($error)) {
  2654. // Call trigger
  2655. $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user);
  2656. if ($result < 0) {
  2657. $error++;
  2658. }
  2659. // End call triggers
  2660. }
  2661. if (!$error) {
  2662. $this->billed = 0;
  2663. $this->db->commit();
  2664. return 1;
  2665. } else {
  2666. foreach ($this->errors as $errmsg) {
  2667. dol_syslog(get_class($this)."::classifyUnBilled ".$errmsg, LOG_ERR);
  2668. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2669. }
  2670. $this->db->rollback();
  2671. return -1 * $error;
  2672. }
  2673. } else {
  2674. $this->error = $this->db->error();
  2675. $this->db->rollback();
  2676. return -1;
  2677. }
  2678. }
  2679. /**
  2680. * Update a line in database
  2681. *
  2682. * @param int $rowid Id of line to update
  2683. * @param string $desc Description of line
  2684. * @param float $pu Unit price
  2685. * @param float $qty Quantity
  2686. * @param float $remise_percent Percent of discount
  2687. * @param float $txtva Taux TVA
  2688. * @param float $txlocaltax1 Local tax 1 rate
  2689. * @param float $txlocaltax2 Local tax 2 rate
  2690. * @param string $price_base_type HT or TTC
  2691. * @param int $info_bits Miscellaneous informations on line
  2692. * @param int $date_start Start date of the line
  2693. * @param int $date_end End date of the line
  2694. * @param int $type Type of line (0=product, 1=service)
  2695. * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines).
  2696. * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules)
  2697. * @param int $fk_fournprice Id of origin supplier price
  2698. * @param int $pa_ht Price (without tax) of product when it was bought
  2699. * @param string $label Label
  2700. * @param int $special_code Special code (also used by externals modules!)
  2701. * @param array $array_options extrafields array
  2702. * @param string $fk_unit Code of the unit to use. Null to use the default one
  2703. * @param double $pu_ht_devise Amount in currency
  2704. * @param int $notrigger disable line update trigger
  2705. * @param string $ref_ext external reference
  2706. * @param integer $rang line rank
  2707. * @return int < 0 if KO, > 0 if OK
  2708. */
  2709. public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $price_base_type = 'HT', $info_bits = 0, $date_start = '', $date_end = '', $type = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '', $rang = 0)
  2710. {
  2711. global $conf, $mysoc, $langs, $user;
  2712. dol_syslog(get_class($this)."::updateline id=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, date_start=$date_start, date_end=$date_end, type=$type, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, special_code=$special_code, ref_ext=$ref_ext");
  2713. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2714. if ($this->statut == Commande::STATUS_DRAFT) {
  2715. // Clean parameters
  2716. if (empty($qty)) {
  2717. $qty = 0;
  2718. }
  2719. if (empty($info_bits)) {
  2720. $info_bits = 0;
  2721. }
  2722. if (empty($txtva)) {
  2723. $txtva = 0;
  2724. }
  2725. if (empty($txlocaltax1)) {
  2726. $txlocaltax1 = 0;
  2727. }
  2728. if (empty($txlocaltax2)) {
  2729. $txlocaltax2 = 0;
  2730. }
  2731. if (empty($remise_percent)) {
  2732. $remise_percent = 0;
  2733. }
  2734. if (empty($special_code) || $special_code == 3) {
  2735. $special_code = 0;
  2736. }
  2737. if (empty($ref_ext)) {
  2738. $ref_ext = '';
  2739. }
  2740. if ($date_start && $date_end && $date_start > $date_end) {
  2741. $langs->load("errors");
  2742. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  2743. return -1;
  2744. }
  2745. $remise_percent = price2num($remise_percent);
  2746. $qty = price2num($qty);
  2747. $pu = price2num($pu);
  2748. $pa_ht = price2num($pa_ht);
  2749. $pu_ht_devise = price2num($pu_ht_devise);
  2750. if (!preg_match('/\((.*)\)/', $txtva)) {
  2751. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  2752. }
  2753. $txlocaltax1 = price2num($txlocaltax1);
  2754. $txlocaltax2 = price2num($txlocaltax2);
  2755. $this->db->begin();
  2756. // Calcul du total TTC et de la TVA pour la ligne a partir de
  2757. // qty, pu, remise_percent et txtva
  2758. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  2759. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  2760. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  2761. // Clean vat code
  2762. $vat_src_code = '';
  2763. $reg = array();
  2764. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  2765. $vat_src_code = $reg[1];
  2766. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  2767. }
  2768. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
  2769. $total_ht = $tabprice[0];
  2770. $total_tva = $tabprice[1];
  2771. $total_ttc = $tabprice[2];
  2772. $total_localtax1 = $tabprice[9];
  2773. $total_localtax2 = $tabprice[10];
  2774. $pu_ht = $tabprice[3];
  2775. $pu_tva = $tabprice[4];
  2776. $pu_ttc = $tabprice[5];
  2777. // MultiCurrency
  2778. $multicurrency_total_ht = $tabprice[16];
  2779. $multicurrency_total_tva = $tabprice[17];
  2780. $multicurrency_total_ttc = $tabprice[18];
  2781. $pu_ht_devise = $tabprice[19];
  2782. // Anciens indicateurs: $price, $subprice (a ne plus utiliser)
  2783. $price = $pu_ht;
  2784. if ($price_base_type == 'TTC') {
  2785. $subprice = $pu_ttc;
  2786. } else {
  2787. $subprice = $pu_ht;
  2788. }
  2789. $remise = 0;
  2790. if ($remise_percent > 0) {
  2791. $remise = round(($pu * $remise_percent / 100), 2);
  2792. $price = ($pu - $remise);
  2793. }
  2794. //Fetch current line from the database and then clone the object and set it in $oldline property
  2795. $line = new OrderLine($this->db);
  2796. $line->fetch($rowid);
  2797. $line->fetch_optionals();
  2798. if (!empty($line->fk_product)) {
  2799. $product = new Product($this->db);
  2800. $result = $product->fetch($line->fk_product);
  2801. $product_type = $product->type;
  2802. if (getDolGlobalString('STOCK_MUST_BE_ENOUGH_FOR_ORDER') && $product_type == 0 && $product->stock_reel < $qty) {
  2803. $langs->load("errors");
  2804. $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnOrder', $product->ref);
  2805. $this->errors[] = $this->error;
  2806. dol_syslog(get_class($this)."::addline error=Product ".$product->ref.": ".$this->error, LOG_ERR);
  2807. $this->db->rollback();
  2808. return self::STOCK_NOT_ENOUGH_FOR_ORDER;
  2809. }
  2810. }
  2811. $staticline = clone $line;
  2812. $line->oldline = $staticline;
  2813. $this->line = $line;
  2814. $this->line->context = $this->context;
  2815. $this->line->rang = $rang;
  2816. // Reorder if fk_parent_line change
  2817. if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
  2818. $rangmax = $this->line_max($fk_parent_line);
  2819. $this->line->rang = $rangmax + 1;
  2820. }
  2821. $this->line->id = $rowid;
  2822. $this->line->label = $label;
  2823. $this->line->desc = $desc;
  2824. $this->line->qty = $qty;
  2825. $this->line->ref_ext = $ref_ext;
  2826. $this->line->vat_src_code = $vat_src_code;
  2827. $this->line->tva_tx = $txtva;
  2828. $this->line->localtax1_tx = $txlocaltax1;
  2829. $this->line->localtax2_tx = $txlocaltax2;
  2830. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  2831. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  2832. $this->line->remise_percent = $remise_percent;
  2833. $this->line->subprice = $subprice;
  2834. $this->line->info_bits = $info_bits;
  2835. $this->line->special_code = $special_code;
  2836. $this->line->total_ht = $total_ht;
  2837. $this->line->total_tva = $total_tva;
  2838. $this->line->total_localtax1 = $total_localtax1;
  2839. $this->line->total_localtax2 = $total_localtax2;
  2840. $this->line->total_ttc = $total_ttc;
  2841. $this->line->date_start = $date_start;
  2842. $this->line->date_end = $date_end;
  2843. $this->line->product_type = $type;
  2844. $this->line->fk_parent_line = $fk_parent_line;
  2845. $this->line->skip_update_total = $skip_update_total;
  2846. $this->line->fk_unit = $fk_unit;
  2847. $this->line->fk_fournprice = $fk_fournprice;
  2848. $this->line->pa_ht = $pa_ht;
  2849. // Multicurrency
  2850. $this->line->multicurrency_subprice = $pu_ht_devise;
  2851. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  2852. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  2853. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  2854. // TODO deprecated
  2855. $this->line->price = $price;
  2856. if (is_array($array_options) && count($array_options) > 0) {
  2857. // We replace values in this->line->array_options only for entries defined into $array_options
  2858. foreach ($array_options as $key => $value) {
  2859. $this->line->array_options[$key] = $array_options[$key];
  2860. }
  2861. }
  2862. $result = $this->line->update($user, $notrigger);
  2863. if ($result > 0) {
  2864. // Reorder if child line
  2865. if (!empty($fk_parent_line)) {
  2866. $this->line_order(true, 'DESC');
  2867. }
  2868. // Mise a jour info denormalisees
  2869. $this->update_price(1, 'auto');
  2870. $this->db->commit();
  2871. return $result;
  2872. } else {
  2873. $this->error = $this->line->error;
  2874. $this->db->rollback();
  2875. return -1;
  2876. }
  2877. } else {
  2878. $this->error = get_class($this)."::updateline Order status makes operation forbidden";
  2879. $this->errors = array('OrderStatusMakeOperationForbidden');
  2880. return -2;
  2881. }
  2882. }
  2883. /**
  2884. * Update database
  2885. *
  2886. * @param User $user User that modify
  2887. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  2888. * @return int <0 if KO, >0 if OK
  2889. */
  2890. public function update(User $user, $notrigger = 0)
  2891. {
  2892. global $conf;
  2893. $error = 0;
  2894. // Clean parameters
  2895. if (isset($this->ref)) {
  2896. $this->ref = trim($this->ref);
  2897. }
  2898. if (isset($this->ref_client)) {
  2899. $this->ref_client = trim($this->ref_client);
  2900. }
  2901. if (isset($this->ref_customer)) {
  2902. $this->ref_customer = trim($this->ref_customer);
  2903. }
  2904. if (isset($this->note) || isset($this->note_private)) {
  2905. $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
  2906. }
  2907. if (isset($this->note_public)) {
  2908. $this->note_public = trim($this->note_public);
  2909. }
  2910. if (isset($this->model_pdf)) {
  2911. $this->model_pdf = trim($this->model_pdf);
  2912. }
  2913. if (isset($this->import_key)) {
  2914. $this->import_key = trim($this->import_key);
  2915. }
  2916. $delivery_date = $this->delivery_date;
  2917. // Check parameters
  2918. // Put here code to add control on parameters values
  2919. // Update request
  2920. $sql = "UPDATE ".MAIN_DB_PREFIX."commande SET";
  2921. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  2922. $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
  2923. $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
  2924. $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
  2925. $sql .= " date_commande=".(strval($this->date_commande) != '' ? "'".$this->db->idate($this->date_commande)."'" : 'null').",";
  2926. $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
  2927. $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
  2928. $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
  2929. $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
  2930. $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
  2931. $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
  2932. $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
  2933. $sql .= " fk_user_author=".(isset($this->user_author_id) ? $this->user_author_id : "null").",";
  2934. $sql .= " fk_user_valid=".((isset($this->user_validation_id) && $this->user_validation_id > 0) ? $this->user_validation_id : "null").",";
  2935. $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
  2936. $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
  2937. $sql .= " deposit_percent=".(!empty($this->deposit_percent) ? strval($this->deposit_percent) : "null").",";
  2938. $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->mode_reglement_id : "null").",";
  2939. $sql .= " date_livraison=".(strval($this->delivery_date) != '' ? "'".$this->db->idate($this->delivery_date)."'" : 'null').",";
  2940. $sql .= " fk_shipping_method=".(isset($this->shipping_method_id) ? $this->shipping_method_id : "null").",";
  2941. $sql .= " fk_account=".($this->fk_account > 0 ? $this->fk_account : "null").",";
  2942. $sql .= " fk_input_reason=".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null").",";
  2943. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  2944. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  2945. $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
  2946. $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
  2947. $sql .= " WHERE rowid=".((int) $this->id);
  2948. $this->db->begin();
  2949. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  2950. $resql = $this->db->query($sql);
  2951. if (!$resql) {
  2952. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  2953. }
  2954. if (!$error) {
  2955. $result = $this->insertExtraFields();
  2956. if ($result < 0) {
  2957. $error++;
  2958. }
  2959. }
  2960. if (!$error && !$notrigger) {
  2961. // Call trigger
  2962. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2963. if ($result < 0) {
  2964. $error++;
  2965. }
  2966. // End call triggers
  2967. }
  2968. // Commit or rollback
  2969. if ($error) {
  2970. foreach ($this->errors as $errmsg) {
  2971. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  2972. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2973. }
  2974. $this->db->rollback();
  2975. return -1 * $error;
  2976. } else {
  2977. $this->db->commit();
  2978. return 1;
  2979. }
  2980. }
  2981. /**
  2982. * Delete the sales order
  2983. *
  2984. * @param User $user User object
  2985. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2986. * @return int <=0 if KO, >0 if OK
  2987. */
  2988. public function delete($user, $notrigger = 0)
  2989. {
  2990. global $conf, $langs;
  2991. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2992. $error = 0;
  2993. dol_syslog(get_class($this)."::delete ".$this->id, LOG_DEBUG);
  2994. $this->db->begin();
  2995. if (!$notrigger) {
  2996. // Call trigger
  2997. $result = $this->call_trigger('ORDER_DELETE', $user);
  2998. if ($result < 0) {
  2999. $error++;
  3000. }
  3001. // End call triggers
  3002. }
  3003. // Test we can delete
  3004. if ($this->countNbOfShipments() != 0) {
  3005. $this->errors[] = $langs->trans('SomeShipmentExists');
  3006. $error++;
  3007. }
  3008. // Delete extrafields of lines and lines
  3009. if (!$error && !empty($this->table_element_line)) {
  3010. $tabletodelete = $this->table_element_line;
  3011. $sqlef = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete."_extrafields WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id).")";
  3012. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
  3013. if (!$this->db->query($sqlef) || !$this->db->query($sql)) {
  3014. $error++;
  3015. $this->error = $this->db->lasterror();
  3016. $this->errors[] = $this->error;
  3017. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  3018. }
  3019. }
  3020. if (!$error) {
  3021. // Delete linked object
  3022. $res = $this->deleteObjectLinked();
  3023. if ($res < 0) {
  3024. $error++;
  3025. }
  3026. }
  3027. if (!$error) {
  3028. // Delete linked contacts
  3029. $res = $this->delete_linked_contact();
  3030. if ($res < 0) {
  3031. $error++;
  3032. }
  3033. }
  3034. // Removed extrafields of object
  3035. if (!$error) {
  3036. $result = $this->deleteExtraFields();
  3037. if ($result < 0) {
  3038. $error++;
  3039. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  3040. }
  3041. }
  3042. // Delete main record
  3043. if (!$error) {
  3044. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
  3045. $res = $this->db->query($sql);
  3046. if (!$res) {
  3047. $error++;
  3048. $this->error = $this->db->lasterror();
  3049. $this->errors[] = $this->error;
  3050. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  3051. }
  3052. }
  3053. // Delete record into ECM index and physically
  3054. if (!$error) {
  3055. $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
  3056. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  3057. if (!$res) {
  3058. $error++;
  3059. }
  3060. }
  3061. if (!$error) {
  3062. // We remove directory
  3063. $ref = dol_sanitizeFileName($this->ref);
  3064. if ($conf->commande->multidir_output[$this->entity] && !empty($this->ref)) {
  3065. $dir = $conf->commande->multidir_output[$this->entity]."/".$ref;
  3066. $file = $dir."/".$ref.".pdf";
  3067. if (file_exists($file)) {
  3068. dol_delete_preview($this);
  3069. if (!dol_delete_file($file, 0, 0, 0, $this)) {
  3070. $this->error = 'ErrorFailToDeleteFile';
  3071. $this->errors[] = $this->error;
  3072. $this->db->rollback();
  3073. return 0;
  3074. }
  3075. }
  3076. if (file_exists($dir)) {
  3077. $res = @dol_delete_dir_recursive($dir);
  3078. if (!$res) {
  3079. $this->error = 'ErrorFailToDeleteDir';
  3080. $this->errors[] = $this->error;
  3081. $this->db->rollback();
  3082. return 0;
  3083. }
  3084. }
  3085. }
  3086. }
  3087. if (!$error) {
  3088. dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
  3089. $this->db->commit();
  3090. return 1;
  3091. } else {
  3092. $this->db->rollback();
  3093. return -1;
  3094. }
  3095. }
  3096. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3097. /**
  3098. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  3099. *
  3100. * @param User $user Object user
  3101. * @param string $mode Mode ('toship', 'tobill', 'shippedtobill')
  3102. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  3103. */
  3104. public function load_board($user, $mode)
  3105. {
  3106. // phpcs:enable
  3107. global $conf, $langs;
  3108. $clause = " WHERE";
  3109. $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut, c.total_ht";
  3110. $sql .= " FROM ".MAIN_DB_PREFIX."commande as c";
  3111. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  3112. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
  3113. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  3114. $clause = " AND";
  3115. }
  3116. $sql .= $clause." c.entity IN (".getEntity('commande').")";
  3117. //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
  3118. if ($mode == 'toship') {
  3119. // An order to ship is an open order (validated or in progress)
  3120. $sql .= " AND c.fk_statut IN (" . self::STATUS_VALIDATED . "," . self::STATUS_SHIPMENTONPROCESS . ")";
  3121. }
  3122. if ($mode == 'tobill') {
  3123. // An order to bill is an order not already billed
  3124. $sql .= " AND c.fk_statut IN (" . self::STATUS_VALIDATED . "," . self::STATUS_SHIPMENTONPROCESS . ", " . self::STATUS_CLOSED . ") AND c.facture = 0";
  3125. }
  3126. if ($mode == 'shippedtobill') {
  3127. // An order shipped and to bill is a delivered order not already billed
  3128. $sql .= " AND c.fk_statut IN (" . self::STATUS_CLOSED . ") AND c.facture = 0";
  3129. }
  3130. if ($user->socid) {
  3131. $sql .= " AND c.fk_soc = ".((int) $user->socid);
  3132. }
  3133. $resql = $this->db->query($sql);
  3134. if ($resql) {
  3135. $delay_warning = 0;
  3136. $label = $labelShort = $url = '';
  3137. if ($mode == 'toship') {
  3138. $delay_warning = $conf->commande->client->warning_delay / 60 / 60 / 24;
  3139. $url = DOL_URL_ROOT.'/commande/list.php?search_status=-2&mainmenu=commercial&leftmenu=orders';
  3140. $label = $langs->transnoentitiesnoconv("OrdersToProcess");
  3141. $labelShort = $langs->transnoentitiesnoconv("Opened");
  3142. }
  3143. if ($mode == 'tobill') {
  3144. $url = DOL_URL_ROOT.'/commande/list.php?search_status=-3&search_billed=0&mainmenu=commercial&leftmenu=orders';
  3145. $label = $langs->trans("OrdersToBill"); // We set here bill but may be billed or ordered
  3146. $labelShort = $langs->trans("ToBill");
  3147. }
  3148. if ($mode == 'shippedtobill') {
  3149. $url = DOL_URL_ROOT.'/commande/list.php?search_status=3&search_billed=0&mainmenu=commercial&leftmenu=orders';
  3150. $label = $langs->trans("OrdersToBill"); // We set here bill but may be billed or ordered
  3151. $labelShort = $langs->trans("StatusOrderDelivered").' '.$langs->trans("and").' '.$langs->trans("ToBill");
  3152. }
  3153. $response = new WorkboardResponse();
  3154. $response->warning_delay = $delay_warning;
  3155. $response->label = $label;
  3156. $response->labelShort = $labelShort;
  3157. $response->url = $url;
  3158. $response->img = img_object('', "order");
  3159. $generic_commande = new Commande($this->db);
  3160. while ($obj = $this->db->fetch_object($resql)) {
  3161. $response->nbtodo++;
  3162. $response->total += $obj->total_ht;
  3163. $generic_commande->statut = $obj->fk_statut;
  3164. $generic_commande->date_commande = $this->db->jdate($obj->date_commande);
  3165. $generic_commande->date = $this->db->jdate($obj->date_commande);
  3166. $generic_commande->delivery_date = $this->db->jdate($obj->delivery_date);
  3167. if ($mode == 'toship' && $generic_commande->hasDelay()) {
  3168. $response->nbtodolate++;
  3169. }
  3170. }
  3171. return $response;
  3172. } else {
  3173. $this->error = $this->db->error();
  3174. return -1;
  3175. }
  3176. }
  3177. /**
  3178. * Return source label of order
  3179. *
  3180. * @return string Label
  3181. */
  3182. public function getLabelSource()
  3183. {
  3184. global $langs;
  3185. $label = $langs->trans('OrderSource'.$this->source);
  3186. if ($label == 'OrderSource') {
  3187. return '';
  3188. }
  3189. return $label;
  3190. }
  3191. /**
  3192. * Return status label of Order
  3193. *
  3194. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
  3195. * @return string Label of status
  3196. */
  3197. public function getLibStatut($mode)
  3198. {
  3199. return $this->LibStatut($this->statut, $this->billed, $mode);
  3200. }
  3201. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3202. /**
  3203. * Return label of status
  3204. *
  3205. * @param int $status Id status
  3206. * @param int $billed If invoiced
  3207. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
  3208. * @param int $donotshowbilled Do not show billed status after order status
  3209. * @return string Label of status
  3210. */
  3211. public function LibStatut($status, $billed, $mode, $donotshowbilled = 0)
  3212. {
  3213. // phpcs:enable
  3214. global $langs, $hookmanager;
  3215. $billedtext = '';
  3216. if (empty($donotshowbilled)) {
  3217. $billedtext .= ($billed ? ' - '.$langs->transnoentitiesnoconv("Billed") : '');
  3218. }
  3219. $labelTooltip = '';
  3220. if ($status == self::STATUS_CANCELED) {
  3221. $labelStatus = $langs->transnoentitiesnoconv('StatusOrderCanceled');
  3222. $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderCanceledShort');
  3223. $statusType = 'status9';
  3224. } elseif ($status == self::STATUS_DRAFT) {
  3225. $labelStatus = $langs->transnoentitiesnoconv('StatusOrderDraft');
  3226. $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderDraftShort');
  3227. $statusType = 'status0';
  3228. } elseif ($status == self::STATUS_VALIDATED) {
  3229. $labelStatus = $langs->transnoentitiesnoconv('StatusOrderValidated').$billedtext;
  3230. $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderValidatedShort').$billedtext;
  3231. $statusType = 'status1';
  3232. } elseif ($status == self::STATUS_SHIPMENTONPROCESS) {
  3233. $labelStatus = $langs->transnoentitiesnoconv('StatusOrderSent').$billedtext;
  3234. $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderSentShort').$billedtext;
  3235. $labelTooltip = $langs->transnoentitiesnoconv("StatusOrderSent");
  3236. if (!empty($this->delivery_date)) {
  3237. $labelTooltip .= ' - '.$langs->transnoentitiesnoconv("DateDeliveryPlanned").dol_print_date($this->delivery_date, 'day').$billedtext;
  3238. }
  3239. $statusType = 'status4';
  3240. } elseif ($status == self::STATUS_CLOSED) {
  3241. $labelStatus = $langs->transnoentitiesnoconv('StatusOrderDelivered').$billedtext;
  3242. $labelStatusShort = $langs->transnoentitiesnoconv('StatusOrderDeliveredShort').$billedtext;
  3243. $statusType = 'status6';
  3244. } else {
  3245. $labelStatus = $langs->transnoentitiesnoconv('Unknown');
  3246. $labelStatusShort = '';
  3247. $statusType = '';
  3248. $mode = 0;
  3249. }
  3250. $parameters = array(
  3251. 'status' => $status,
  3252. 'mode' => $mode,
  3253. 'billed' => $billed,
  3254. 'donotshowbilled' => $donotshowbilled
  3255. );
  3256. $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
  3257. if ($reshook > 0) {
  3258. return $hookmanager->resPrint;
  3259. }
  3260. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', array('tooltip' => $labelTooltip));
  3261. }
  3262. /**
  3263. * getTooltipContentArray
  3264. *
  3265. * @param array $params params to construct tooltip data
  3266. * @return array
  3267. */
  3268. public function getTooltipContentArray($params)
  3269. {
  3270. global $conf, $langs, $user;
  3271. $langs->load('orders');
  3272. $datas = [];
  3273. $nofetch = !empty($params['nofetch']);
  3274. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  3275. return ['optimize' => $langs->trans("Order")];
  3276. }
  3277. if ($user->hasRight('commande', 'lire')) {
  3278. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Order").'</u>';
  3279. if (isset($this->statut)) {
  3280. $datas['status'] = ' '.$this->getLibStatut(5);
  3281. }
  3282. $datas['Ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  3283. if (!$nofetch) {
  3284. $langs->load('companies');
  3285. if (empty($this->thirdparty)) {
  3286. $this->fetch_thirdparty();
  3287. }
  3288. $datas['customer'] = '<br><b>'.$langs->trans('Customer').':</b> '.$this->thirdparty->getNomUrl(1, '', 0, 1);
  3289. }
  3290. $datas['RefCustomer'] = '<br><b>'.$langs->trans('RefCustomer').':</b> '.(empty($this->ref_customer) ? (empty($this->ref_client) ? '' : $this->ref_client) : $this->ref_customer);
  3291. if (!$nofetch) {
  3292. $langs->load('project');
  3293. if (empty($this->project)) {
  3294. $res = $this->fetch_project();
  3295. if ($res > 0) {
  3296. $datas['project'] = '<br><b>'.$langs->trans('Project').':</b> '.$this->project->getNomUrl(1, '', 0, 1);
  3297. }
  3298. }
  3299. }
  3300. if (!empty($this->total_ht)) {
  3301. $datas['AmountHT'] = '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  3302. }
  3303. if (!empty($this->total_tva)) {
  3304. $datas['VAT'] = '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  3305. }
  3306. if (!empty($this->total_ttc)) {
  3307. $datas['AmountTTC'] = '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  3308. }
  3309. if (!empty($this->date)) {
  3310. $datas['Date'] = '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
  3311. }
  3312. if (!empty($this->delivery_date)) {
  3313. $datas['DeliveryDate'] = '<br><b>'.$langs->trans('DeliveryDate').':</b> '.dol_print_date($this->delivery_date, 'dayhour');
  3314. }
  3315. }
  3316. return $datas;
  3317. }
  3318. /**
  3319. * Return clicable link of object (with eventually picto)
  3320. *
  3321. * @param int $withpicto Add picto into link
  3322. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  3323. * @param int $max Max length to show
  3324. * @param int $short ???
  3325. * @param int $notooltip 1=Disable tooltip
  3326. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  3327. * @param int $addlinktonotes Add link to notes
  3328. * @param string $target attribute target for link
  3329. * @return string String with URL
  3330. */
  3331. public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0, $target = '')
  3332. {
  3333. global $conf, $langs, $user, $hookmanager;
  3334. if (!empty($conf->dol_no_mouse_hover)) {
  3335. $notooltip = 1; // Force disable tooltips
  3336. }
  3337. $result = '';
  3338. if (isModEnabled("expedition") && ($option == '1' || $option == '2')) {
  3339. $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id;
  3340. } else {
  3341. $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id;
  3342. }
  3343. if (!$user->hasRight('commande', 'lire')) {
  3344. $option = 'nolink';
  3345. }
  3346. if ($option !== 'nolink') {
  3347. // Add param to save lastsearch_values or not
  3348. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  3349. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  3350. $add_save_lastsearch_values = 1;
  3351. }
  3352. if ($add_save_lastsearch_values) {
  3353. $url .= '&save_lastsearch_values=1';
  3354. }
  3355. }
  3356. if ($short) {
  3357. return $url;
  3358. }
  3359. $params = [
  3360. 'id' => $this->id,
  3361. 'objecttype' => $this->element,
  3362. 'option' => $option,
  3363. 'nofetch' => 1,
  3364. ];
  3365. $classfortooltip = 'classfortooltip';
  3366. $dataparams = '';
  3367. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  3368. $classfortooltip = 'classforajaxtooltip';
  3369. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  3370. $label = '';
  3371. } else {
  3372. $label = implode($this->getTooltipContentArray($params));
  3373. }
  3374. $linkclose = '';
  3375. if (empty($notooltip) && $user->hasRight('commande', 'lire')) {
  3376. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  3377. $label = $langs->trans("Order");
  3378. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  3379. }
  3380. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  3381. $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
  3382. $target_value = array('_self', '_blank', '_parent', '_top');
  3383. if (in_array($target, $target_value)) {
  3384. $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
  3385. }
  3386. }
  3387. $linkstart = '<a href="'.$url.'"';
  3388. $linkstart .= $linkclose.'>';
  3389. $linkend = '</a>';
  3390. if ($option === 'nolink') {
  3391. $linkstart = '';
  3392. $linkend = '';
  3393. }
  3394. $result .= $linkstart;
  3395. if ($withpicto) {
  3396. $result .= img_object(($notooltip ? '' : $label), $this->picto, (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
  3397. }
  3398. if ($withpicto != 2) {
  3399. $result .= $this->ref;
  3400. }
  3401. $result .= $linkend;
  3402. if ($addlinktonotes) {
  3403. $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
  3404. if ($txttoshow) {
  3405. $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
  3406. $result .= ' <span class="note inline-block">';
  3407. $result .= '<a href="'.DOL_URL_ROOT.'/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
  3408. $result .= img_picto('', 'note');
  3409. $result .= '</a>';
  3410. //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
  3411. //$result.='</a>';
  3412. $result .= '</span>';
  3413. }
  3414. }
  3415. global $action;
  3416. $hookmanager->initHooks(array($this->element . 'dao'));
  3417. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  3418. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3419. if ($reshook > 0) {
  3420. $result = $hookmanager->resPrint;
  3421. } else {
  3422. $result .= $hookmanager->resPrint;
  3423. }
  3424. return $result;
  3425. }
  3426. /**
  3427. * Charge les informations d'ordre info dans l'objet commande
  3428. *
  3429. * @param int $id Id of order
  3430. * @return void
  3431. */
  3432. public function info($id)
  3433. {
  3434. $sql = 'SELECT c.rowid, date_creation as datec, tms as datem,';
  3435. $sql .= ' date_valid as datev,';
  3436. $sql .= ' date_cloture as datecloture,';
  3437. $sql .= ' fk_user_author, fk_user_valid, fk_user_cloture';
  3438. $sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c';
  3439. $sql .= ' WHERE c.rowid = '.((int) $id);
  3440. $result = $this->db->query($sql);
  3441. if ($result) {
  3442. if ($this->db->num_rows($result)) {
  3443. $obj = $this->db->fetch_object($result);
  3444. $this->id = $obj->rowid;
  3445. if ($obj->fk_user_author) {
  3446. $this->user_creation_id = $obj->fk_user_author;
  3447. }
  3448. if ($obj->fk_user_valid) {
  3449. $this->user_validation_id = $obj->fk_user_valid;
  3450. }
  3451. if ($obj->fk_user_cloture) {
  3452. $this->user_closing_id = $obj->fk_user_cloture;
  3453. }
  3454. $this->date_creation = $this->db->jdate($obj->datec);
  3455. $this->date_modification = $this->db->jdate($obj->datem);
  3456. $this->date_validation = $this->db->jdate($obj->datev);
  3457. $this->date_cloture = $this->db->jdate($obj->datecloture);
  3458. }
  3459. $this->db->free($result);
  3460. } else {
  3461. dol_print_error($this->db);
  3462. }
  3463. }
  3464. /**
  3465. * Initialise an instance with random values.
  3466. * Used to build previews or test instances.
  3467. * id must be 0 if object instance is a specimen.
  3468. *
  3469. * @return void
  3470. */
  3471. public function initAsSpecimen()
  3472. {
  3473. global $conf, $langs;
  3474. dol_syslog(get_class($this)."::initAsSpecimen");
  3475. // Load array of products prodids
  3476. $num_prods = 0;
  3477. $prodids = array();
  3478. $sql = "SELECT rowid";
  3479. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  3480. $sql .= " WHERE entity IN (".getEntity('product').")";
  3481. $sql .= $this->db->plimit(100);
  3482. $resql = $this->db->query($sql);
  3483. if ($resql) {
  3484. $num_prods = $this->db->num_rows($resql);
  3485. $i = 0;
  3486. while ($i < $num_prods) {
  3487. $i++;
  3488. $row = $this->db->fetch_row($resql);
  3489. $prodids[$i] = $row[0];
  3490. }
  3491. }
  3492. // Initialise parametres
  3493. $this->id = 0;
  3494. $this->ref = 'SPECIMEN';
  3495. $this->specimen = 1;
  3496. $this->entity = $conf->entity;
  3497. $this->socid = 1;
  3498. $this->date = time();
  3499. $this->date_lim_reglement = $this->date + 3600 * 24 * 30;
  3500. $this->cond_reglement_code = 'RECEP';
  3501. $this->mode_reglement_code = 'CHQ';
  3502. $this->availability_code = 'DSP';
  3503. $this->demand_reason_code = 'SRC_00';
  3504. $this->note_public = 'This is a comment (public)';
  3505. $this->note_private = 'This is a comment (private)';
  3506. $this->multicurrency_tx = 1;
  3507. $this->multicurrency_code = $conf->currency;
  3508. // Lines
  3509. $nbp = 5;
  3510. $xnbp = 0;
  3511. while ($xnbp < $nbp) {
  3512. $line = new OrderLine($this->db);
  3513. $line->desc = $langs->trans("Description")." ".$xnbp;
  3514. $line->qty = 1;
  3515. $line->subprice = 100;
  3516. $line->price = 100;
  3517. $line->tva_tx = 20;
  3518. if ($xnbp == 2) {
  3519. $line->total_ht = 50;
  3520. $line->total_ttc = 60;
  3521. $line->total_tva = 10;
  3522. $line->remise_percent = 50;
  3523. } else {
  3524. $line->total_ht = 100;
  3525. $line->total_ttc = 120;
  3526. $line->total_tva = 20;
  3527. $line->remise_percent = 0;
  3528. }
  3529. if ($num_prods > 0) {
  3530. $prodid = mt_rand(1, $num_prods);
  3531. $line->fk_product = $prodids[$prodid];
  3532. $line->product_ref = 'SPECIMEN';
  3533. }
  3534. $this->lines[$xnbp] = $line;
  3535. $this->total_ht += $line->total_ht;
  3536. $this->total_tva += $line->total_tva;
  3537. $this->total_ttc += $line->total_ttc;
  3538. $xnbp++;
  3539. }
  3540. }
  3541. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3542. /**
  3543. * Charge indicateurs this->nb de tableau de bord
  3544. *
  3545. * @return int <0 si ko, >0 si ok
  3546. */
  3547. public function load_state_board()
  3548. {
  3549. // phpcs:enable
  3550. global $user;
  3551. $this->nb = array();
  3552. $clause = "WHERE";
  3553. $sql = "SELECT count(co.rowid) as nb";
  3554. $sql .= " FROM ".MAIN_DB_PREFIX."commande as co";
  3555. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
  3556. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  3557. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  3558. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  3559. $clause = "AND";
  3560. }
  3561. $sql .= " ".$clause." co.entity IN (".getEntity('commande').")";
  3562. $resql = $this->db->query($sql);
  3563. if ($resql) {
  3564. while ($obj = $this->db->fetch_object($resql)) {
  3565. $this->nb["orders"] = $obj->nb;
  3566. }
  3567. $this->db->free($resql);
  3568. return 1;
  3569. } else {
  3570. dol_print_error($this->db);
  3571. $this->error = $this->db->error();
  3572. return -1;
  3573. }
  3574. }
  3575. /**
  3576. * Create an array of order lines
  3577. *
  3578. * @return int >0 if OK, <0 if KO
  3579. */
  3580. public function getLinesArray()
  3581. {
  3582. return $this->fetch_lines();
  3583. }
  3584. /**
  3585. * Create a document onto disk according to template module.
  3586. *
  3587. * @param string $modele Force template to use ('' to not force)
  3588. * @param Translate $outputlangs objet lang a utiliser pour traduction
  3589. * @param int $hidedetails Hide details of lines
  3590. * @param int $hidedesc Hide description
  3591. * @param int $hideref Hide ref
  3592. * @param null|array $moreparams Array to provide more information
  3593. * @return int 0 if KO, 1 if OK
  3594. */
  3595. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  3596. {
  3597. global $conf, $langs;
  3598. $langs->load("orders");
  3599. $outputlangs->load("products");
  3600. if (!dol_strlen($modele)) {
  3601. $modele = 'einstein';
  3602. if (!empty($this->model_pdf)) {
  3603. $modele = $this->model_pdf;
  3604. } elseif (getDolGlobalString('COMMANDE_ADDON_PDF')) {
  3605. $modele = $conf->global->COMMANDE_ADDON_PDF;
  3606. }
  3607. }
  3608. $modelpath = "core/modules/commande/doc/";
  3609. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  3610. }
  3611. /**
  3612. * Function used to replace a thirdparty id with another one.
  3613. *
  3614. * @param DoliDB $dbs Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
  3615. * @param int $origin_id Old thirdparty id
  3616. * @param int $dest_id New thirdparty id
  3617. * @return bool
  3618. */
  3619. public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
  3620. {
  3621. $tables = array(
  3622. 'commande'
  3623. );
  3624. return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
  3625. }
  3626. /**
  3627. * Function used to replace a product id with another one.
  3628. *
  3629. * @param DoliDB $db Database handler
  3630. * @param int $origin_id Old product id
  3631. * @param int $dest_id New product id
  3632. * @return bool
  3633. */
  3634. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  3635. {
  3636. $tables = array(
  3637. 'commandedet',
  3638. );
  3639. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  3640. }
  3641. /**
  3642. * Is the sales order delayed?
  3643. *
  3644. * @return bool true if late, false if not
  3645. */
  3646. public function hasDelay()
  3647. {
  3648. global $conf;
  3649. if (!($this->statut > Commande::STATUS_DRAFT && $this->statut < Commande::STATUS_CLOSED)) {
  3650. return false; // Never late if not inside this status range
  3651. }
  3652. $now = dol_now();
  3653. return max($this->date, $this->delivery_date) < ($now - $conf->commande->client->warning_delay);
  3654. }
  3655. /**
  3656. * Show the customer delayed info
  3657. *
  3658. * @return string Show delayed information
  3659. */
  3660. public function showDelay()
  3661. {
  3662. global $conf, $langs;
  3663. if (empty($this->delivery_date)) {
  3664. $text = $langs->trans("OrderDate").' '.dol_print_date($this->date, 'day');
  3665. } else {
  3666. $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->delivery_date, 'day');
  3667. }
  3668. $text .= ' '.($conf->commande->client->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->client->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today");
  3669. return $text;
  3670. }
  3671. }
  3672. /**
  3673. * Class to manage order lines
  3674. */
  3675. class OrderLine extends CommonOrderLine
  3676. {
  3677. /**
  3678. * @var string ID to identify managed object
  3679. */
  3680. public $element = 'commandedet';
  3681. public $table_element = 'commandedet';
  3682. public $oldline;
  3683. /**
  3684. * Id of parent order
  3685. * @var int
  3686. */
  3687. public $fk_commande;
  3688. /**
  3689. * Id of parent order
  3690. * @var int
  3691. * @deprecated Use fk_commande
  3692. * @see $fk_commande
  3693. */
  3694. public $commande_id;
  3695. public $fk_parent_line;
  3696. /**
  3697. * @var int Id of invoice
  3698. */
  3699. public $fk_facture;
  3700. /**
  3701. * @var string External ref
  3702. */
  3703. public $ref_ext;
  3704. public $fk_remise_except;
  3705. /**
  3706. * @var int line rank
  3707. */
  3708. public $rang = 0;
  3709. public $fk_fournprice;
  3710. /**
  3711. * Buy price without taxes
  3712. * @var float
  3713. */
  3714. public $pa_ht;
  3715. public $marge_tx;
  3716. public $marque_tx;
  3717. /**
  3718. * @deprecated
  3719. * @see $remise_percent, $fk_remise_except
  3720. */
  3721. public $remise;
  3722. // Start and end date of the line
  3723. public $date_start;
  3724. public $date_end;
  3725. public $skip_update_total; // Skip update price total for special lines
  3726. /**
  3727. * Constructor
  3728. *
  3729. * @param DoliDB $db handler d'acces base de donnee
  3730. */
  3731. public function __construct($db)
  3732. {
  3733. $this->db = $db;
  3734. }
  3735. /**
  3736. * Load line order
  3737. *
  3738. * @param int $rowid Id line order
  3739. * @return int <0 if KO, >0 if OK
  3740. */
  3741. public function fetch($rowid)
  3742. {
  3743. $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_parent_line, cd.fk_product, cd.product_type, cd.label as custom_label, cd.description, cd.price, cd.qty, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx,';
  3744. $sql .= ' cd.remise, cd.remise_percent, cd.fk_remise_except, cd.subprice, cd.ref_ext,';
  3745. $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht, cd.rang, cd.special_code,';
  3746. $sql .= ' cd.fk_unit,';
  3747. $sql .= ' cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc,';
  3748. $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc, p.tobatch as product_tobatch,';
  3749. $sql .= ' cd.date_start, cd.date_end, cd.vat_src_code';
  3750. $sql .= ' FROM '.MAIN_DB_PREFIX.'commandedet as cd';
  3751. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid';
  3752. $sql .= ' WHERE cd.rowid = '.((int) $rowid);
  3753. $result = $this->db->query($sql);
  3754. if ($result) {
  3755. $objp = $this->db->fetch_object($result);
  3756. if (!$objp) {
  3757. $this->error = 'OrderLine with id '. $rowid .' not found sql='.$sql;
  3758. return 0;
  3759. }
  3760. $this->rowid = $objp->rowid;
  3761. $this->id = $objp->rowid;
  3762. $this->fk_commande = $objp->fk_commande;
  3763. $this->fk_parent_line = $objp->fk_parent_line;
  3764. $this->label = $objp->custom_label;
  3765. $this->desc = $objp->description;
  3766. $this->qty = $objp->qty;
  3767. $this->price = $objp->price;
  3768. $this->subprice = $objp->subprice;
  3769. $this->ref_ext = $objp->ref_ext;
  3770. $this->vat_src_code = $objp->vat_src_code;
  3771. $this->tva_tx = $objp->tva_tx;
  3772. $this->localtax1_tx = $objp->localtax1_tx;
  3773. $this->localtax2_tx = $objp->localtax2_tx;
  3774. $this->remise = $objp->remise;
  3775. $this->remise_percent = $objp->remise_percent;
  3776. $this->fk_remise_except = $objp->fk_remise_except;
  3777. $this->fk_product = $objp->fk_product;
  3778. $this->product_type = $objp->product_type;
  3779. $this->info_bits = $objp->info_bits;
  3780. $this->special_code = $objp->special_code;
  3781. $this->total_ht = $objp->total_ht;
  3782. $this->total_tva = $objp->total_tva;
  3783. $this->total_localtax1 = $objp->total_localtax1;
  3784. $this->total_localtax2 = $objp->total_localtax2;
  3785. $this->total_ttc = $objp->total_ttc;
  3786. $this->fk_fournprice = $objp->fk_fournprice;
  3787. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
  3788. $this->pa_ht = $marginInfos[0];
  3789. $this->marge_tx = $marginInfos[1];
  3790. $this->marque_tx = $marginInfos[2];
  3791. $this->special_code = $objp->special_code;
  3792. $this->rang = $objp->rang;
  3793. $this->ref = $objp->product_ref; // deprecated
  3794. $this->product_ref = $objp->product_ref;
  3795. $this->product_label = $objp->product_label;
  3796. $this->product_desc = $objp->product_desc;
  3797. $this->product_tobatch = $objp->product_tobatch;
  3798. $this->fk_unit = $objp->fk_unit;
  3799. $this->date_start = $this->db->jdate($objp->date_start);
  3800. $this->date_end = $this->db->jdate($objp->date_end);
  3801. $this->fk_multicurrency = $objp->fk_multicurrency;
  3802. $this->multicurrency_code = $objp->multicurrency_code;
  3803. $this->multicurrency_subprice = $objp->multicurrency_subprice;
  3804. $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
  3805. $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
  3806. $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  3807. $this->db->free($result);
  3808. return 1;
  3809. } else {
  3810. $this->error = $this->db->lasterror();
  3811. return -1;
  3812. }
  3813. }
  3814. /**
  3815. * Delete line in database
  3816. *
  3817. * @param User $user User that modify
  3818. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  3819. * @return int <0 si ko, >0 si ok
  3820. */
  3821. public function delete(User $user, $notrigger = 0)
  3822. {
  3823. global $conf, $langs;
  3824. $error = 0;
  3825. if (empty($this->id) && !empty($this->rowid)) { // For backward compatibility
  3826. $this->id = $this->rowid;
  3827. }
  3828. // check if order line is not in a shipment line before deleting
  3829. $sqlCheckShipmentLine = "SELECT";
  3830. $sqlCheckShipmentLine .= " ed.rowid";
  3831. $sqlCheckShipmentLine .= " FROM ".MAIN_DB_PREFIX."expeditiondet ed";
  3832. $sqlCheckShipmentLine .= " WHERE ed.fk_origin_line = ".((int) $this->id);
  3833. $resqlCheckShipmentLine = $this->db->query($sqlCheckShipmentLine);
  3834. if (!$resqlCheckShipmentLine) {
  3835. $error++;
  3836. $this->error = $this->db->lasterror();
  3837. $this->errors[] = $this->error;
  3838. } else {
  3839. $langs->load('errors');
  3840. $num = $this->db->num_rows($resqlCheckShipmentLine);
  3841. if ($num > 0) {
  3842. $error++;
  3843. $objCheckShipmentLine = $this->db->fetch_object($resqlCheckShipmentLine);
  3844. $this->error = $langs->trans('ErrorRecordAlreadyExists').' : '.$langs->trans('ShipmentLine').' '.$objCheckShipmentLine->rowid;
  3845. $this->errors[] = $this->error;
  3846. }
  3847. $this->db->free($resqlCheckShipmentLine);
  3848. }
  3849. if ($error) {
  3850. dol_syslog(__METHOD__.'Error ; '.$this->error, LOG_ERR);
  3851. return -1;
  3852. }
  3853. $this->db->begin();
  3854. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE rowid = ".((int) $this->id);
  3855. dol_syslog("OrderLine::delete", LOG_DEBUG);
  3856. $resql = $this->db->query($sql);
  3857. if ($resql) {
  3858. if (!$error && !$notrigger) {
  3859. // Call trigger
  3860. $result = $this->call_trigger('LINEORDER_DELETE', $user);
  3861. if ($result < 0) {
  3862. $error++;
  3863. }
  3864. // End call triggers
  3865. }
  3866. // Remove extrafields
  3867. if (!$error) {
  3868. $result = $this->deleteExtraFields();
  3869. if ($result < 0) {
  3870. $error++;
  3871. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  3872. }
  3873. }
  3874. if (!$error) {
  3875. $this->db->commit();
  3876. return 1;
  3877. }
  3878. foreach ($this->errors as $errmsg) {
  3879. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  3880. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  3881. }
  3882. $this->db->rollback();
  3883. return -1 * $error;
  3884. } else {
  3885. $this->error = $this->db->lasterror();
  3886. return -1;
  3887. }
  3888. }
  3889. /**
  3890. * Insert line into database
  3891. *
  3892. * @param User $user User that modify
  3893. * @param int $notrigger 1 = disable triggers
  3894. * @return int <0 if KO, >0 if OK
  3895. */
  3896. public function insert($user = null, $notrigger = 0)
  3897. {
  3898. $error = 0;
  3899. $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
  3900. dol_syslog(get_class($this)."::insert rang=".$this->rang);
  3901. // Clean parameters
  3902. if (empty($this->tva_tx)) {
  3903. $this->tva_tx = 0;
  3904. }
  3905. if (empty($this->localtax1_tx)) {
  3906. $this->localtax1_tx = 0;
  3907. }
  3908. if (empty($this->localtax2_tx)) {
  3909. $this->localtax2_tx = 0;
  3910. }
  3911. if (empty($this->localtax1_type)) {
  3912. $this->localtax1_type = 0;
  3913. }
  3914. if (empty($this->localtax2_type)) {
  3915. $this->localtax2_type = 0;
  3916. }
  3917. if (empty($this->total_localtax1)) {
  3918. $this->total_localtax1 = 0;
  3919. }
  3920. if (empty($this->total_localtax2)) {
  3921. $this->total_localtax2 = 0;
  3922. }
  3923. if (empty($this->rang)) {
  3924. $this->rang = 0;
  3925. }
  3926. if (empty($this->remise_percent)) {
  3927. $this->remise_percent = 0;
  3928. }
  3929. if (empty($this->info_bits)) {
  3930. $this->info_bits = 0;
  3931. }
  3932. if (empty($this->special_code)) {
  3933. $this->special_code = 0;
  3934. }
  3935. if (empty($this->fk_parent_line)) {
  3936. $this->fk_parent_line = 0;
  3937. }
  3938. if (empty($this->pa_ht)) {
  3939. $this->pa_ht = 0;
  3940. }
  3941. if (empty($this->ref_ext)) {
  3942. $this->ref_ext = '';
  3943. }
  3944. // if buy price not defined, define buyprice as configured in margin admin
  3945. if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
  3946. $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
  3947. if ($result < 0) {
  3948. return $result;
  3949. } else {
  3950. $this->pa_ht = $result;
  3951. }
  3952. }
  3953. // Check parameters
  3954. if ($this->product_type < 0) {
  3955. return -1;
  3956. }
  3957. $this->db->begin();
  3958. // Insertion dans base de la ligne
  3959. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'commandedet';
  3960. $sql .= ' (fk_commande, fk_parent_line, label, description, qty, ref_ext,';
  3961. $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
  3962. $sql .= ' fk_product, product_type, remise_percent, subprice, price, fk_remise_except,';
  3963. $sql .= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,';
  3964. $sql .= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,';
  3965. $sql .= ' fk_unit,';
  3966. $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3967. $sql .= ')';
  3968. $sql .= " VALUES (".$this->fk_commande.",";
  3969. $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").",";
  3970. $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
  3971. $sql .= " '".$this->db->escape($this->desc)."',";
  3972. $sql .= " '".price2num($this->qty)."',";
  3973. $sql .= " '".$this->db->escape($this->ref_ext)."',";
  3974. $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
  3975. $sql .= " '".price2num($this->tva_tx)."',";
  3976. $sql .= " '".price2num($this->localtax1_tx)."',";
  3977. $sql .= " '".price2num($this->localtax2_tx)."',";
  3978. $sql .= " '".$this->db->escape($this->localtax1_type)."',";
  3979. $sql .= " '".$this->db->escape($this->localtax2_type)."',";
  3980. $sql .= ' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product : "null").',';
  3981. $sql .= " '".$this->db->escape($this->product_type)."',";
  3982. $sql .= " '".price2num($this->remise_percent)."',";
  3983. $sql .= " ".(price2num($this->subprice) !== '' ?price2num($this->subprice) : "null").",";
  3984. $sql .= " ".($this->price != '' ? "'".price2num($this->price)."'" : "null").",";
  3985. $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
  3986. $sql .= ' '.((int) $this->special_code).',';
  3987. $sql .= ' '.((int) $this->rang).',';
  3988. $sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
  3989. $sql .= ' '.price2num($this->pa_ht).',';
  3990. $sql .= " ".((int) $this->info_bits).",";
  3991. $sql .= " ".price2num($this->total_ht, 'MT').",";
  3992. $sql .= " ".price2num($this->total_tva, 'MT').",";
  3993. $sql .= " ".price2num($this->total_localtax1, 'MT').",";
  3994. $sql .= " ".price2num($this->total_localtax2, 'MT').",";
  3995. $sql .= " ".price2num($this->total_ttc, 'MT').",";
  3996. $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").',';
  3997. $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").',';
  3998. $sql .= ' '.(!$this->fk_unit ? 'NULL' : ((int) $this->fk_unit));
  3999. $sql .= ", ".(!empty($this->fk_multicurrency) ? ((int) $this->fk_multicurrency) : 'NULL');
  4000. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  4001. $sql .= ", ".price2num($this->multicurrency_subprice, 'CU');
  4002. $sql .= ", ".price2num($this->multicurrency_total_ht, 'CT');
  4003. $sql .= ", ".price2num($this->multicurrency_total_tva, 'CT');
  4004. $sql .= ", ".price2num($this->multicurrency_total_ttc, 'CT');
  4005. $sql .= ')';
  4006. dol_syslog(get_class($this)."::insert", LOG_DEBUG);
  4007. $resql = $this->db->query($sql);
  4008. if ($resql) {
  4009. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
  4010. $this->rowid = $this->id;
  4011. if (!$error) {
  4012. $result = $this->insertExtraFields();
  4013. if ($result < 0) {
  4014. $error++;
  4015. }
  4016. }
  4017. if (!$error && !$notrigger) {
  4018. // Call trigger
  4019. $result = $this->call_trigger('LINEORDER_INSERT', $user);
  4020. if ($result < 0) {
  4021. $error++;
  4022. }
  4023. // End call triggers
  4024. }
  4025. if (!$error) {
  4026. $this->db->commit();
  4027. return 1;
  4028. }
  4029. foreach ($this->errors as $errmsg) {
  4030. dol_syslog(get_class($this)."::insert ".$errmsg, LOG_ERR);
  4031. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  4032. }
  4033. $this->db->rollback();
  4034. return -1 * $error;
  4035. } else {
  4036. $this->error = $this->db->error();
  4037. $this->db->rollback();
  4038. return -2;
  4039. }
  4040. }
  4041. /**
  4042. * Update the line object into db
  4043. *
  4044. * @param User $user User that modify
  4045. * @param int $notrigger 1 = disable triggers
  4046. * @return int <0 si ko, >0 si ok
  4047. */
  4048. public function update(User $user, $notrigger = 0)
  4049. {
  4050. $error = 0;
  4051. $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
  4052. // Clean parameters
  4053. if (empty($this->tva_tx)) {
  4054. $this->tva_tx = 0;
  4055. }
  4056. if (empty($this->localtax1_tx)) {
  4057. $this->localtax1_tx = 0;
  4058. }
  4059. if (empty($this->localtax2_tx)) {
  4060. $this->localtax2_tx = 0;
  4061. }
  4062. if (empty($this->localtax1_type)) {
  4063. $this->localtax1_type = 0;
  4064. }
  4065. if (empty($this->localtax2_type)) {
  4066. $this->localtax2_type = 0;
  4067. }
  4068. if (empty($this->qty)) {
  4069. $this->qty = 0;
  4070. }
  4071. if (empty($this->total_localtax1)) {
  4072. $this->total_localtax1 = 0;
  4073. }
  4074. if (empty($this->total_localtax2)) {
  4075. $this->total_localtax2 = 0;
  4076. }
  4077. if (empty($this->marque_tx)) {
  4078. $this->marque_tx = 0;
  4079. }
  4080. if (empty($this->marge_tx)) {
  4081. $this->marge_tx = 0;
  4082. }
  4083. if (empty($this->remise_percent)) {
  4084. $this->remise_percent = 0;
  4085. }
  4086. if (empty($this->remise)) {
  4087. $this->remise = 0;
  4088. }
  4089. if (empty($this->info_bits)) {
  4090. $this->info_bits = 0;
  4091. }
  4092. if (empty($this->special_code)) {
  4093. $this->special_code = 0;
  4094. }
  4095. if (empty($this->product_type)) {
  4096. $this->product_type = 0;
  4097. }
  4098. if (empty($this->fk_parent_line)) {
  4099. $this->fk_parent_line = 0;
  4100. }
  4101. if (empty($this->pa_ht)) {
  4102. $this->pa_ht = 0;
  4103. }
  4104. if (empty($this->ref_ext)) {
  4105. $this->ref_ext = '';
  4106. }
  4107. // if buy price not defined, define buyprice as configured in margin admin
  4108. if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
  4109. $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
  4110. if ($result < 0) {
  4111. return $result;
  4112. } else {
  4113. $this->pa_ht = $result;
  4114. }
  4115. }
  4116. $this->db->begin();
  4117. // Mise a jour ligne en base
  4118. $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
  4119. $sql .= " description='".$this->db->escape($this->desc)."'";
  4120. $sql .= " , label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
  4121. $sql .= " , vat_src_code=".(!empty($this->vat_src_code) ? "'".$this->db->escape($this->vat_src_code)."'" : "''");
  4122. $sql .= " , tva_tx=".price2num($this->tva_tx);
  4123. $sql .= " , localtax1_tx=".price2num($this->localtax1_tx);
  4124. $sql .= " , localtax2_tx=".price2num($this->localtax2_tx);
  4125. $sql .= " , localtax1_type='".$this->db->escape($this->localtax1_type)."'";
  4126. $sql .= " , localtax2_type='".$this->db->escape($this->localtax2_type)."'";
  4127. $sql .= " , qty=".price2num($this->qty);
  4128. $sql .= " , ref_ext='".$this->db->escape($this->ref_ext)."'";
  4129. $sql .= " , subprice=".price2num($this->subprice);
  4130. $sql .= " , remise_percent=".price2num($this->remise_percent);
  4131. $sql .= " , price=".price2num($this->price); // TODO A virer
  4132. $sql .= " , remise=".price2num($this->remise); // TODO A virer
  4133. if (empty($this->skip_update_total)) {
  4134. $sql .= " , total_ht=".price2num($this->total_ht);
  4135. $sql .= " , total_tva=".price2num($this->total_tva);
  4136. $sql .= " , total_ttc=".price2num($this->total_ttc);
  4137. $sql .= " , total_localtax1=".price2num($this->total_localtax1);
  4138. $sql .= " , total_localtax2=".price2num($this->total_localtax2);
  4139. }
  4140. $sql .= " , fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null");
  4141. $sql .= " , buy_price_ht='".price2num($this->pa_ht)."'";
  4142. $sql .= " , info_bits=".((int) $this->info_bits);
  4143. $sql .= " , special_code=".((int) $this->special_code);
  4144. $sql .= " , date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
  4145. $sql .= " , date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
  4146. $sql .= " , product_type=".$this->product_type;
  4147. $sql .= " , fk_parent_line=".(!empty($this->fk_parent_line) ? $this->fk_parent_line : "null");
  4148. if (!empty($this->rang)) {
  4149. $sql .= ", rang=".((int) $this->rang);
  4150. }
  4151. $sql .= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  4152. // Multicurrency
  4153. $sql .= " , multicurrency_subprice=".price2num($this->multicurrency_subprice);
  4154. $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht);
  4155. $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva);
  4156. $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc);
  4157. $sql .= " WHERE rowid = ".((int) $this->rowid);
  4158. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  4159. $resql = $this->db->query($sql);
  4160. if ($resql) {
  4161. if (!$error) {
  4162. $this->id = $this->rowid;
  4163. $result = $this->insertExtraFields();
  4164. if ($result < 0) {
  4165. $error++;
  4166. }
  4167. }
  4168. if (!$error && !$notrigger) {
  4169. // Call trigger
  4170. $result = $this->call_trigger('LINEORDER_MODIFY', $user);
  4171. if ($result < 0) {
  4172. $error++;
  4173. }
  4174. // End call triggers
  4175. }
  4176. if (!$error) {
  4177. $this->db->commit();
  4178. return 1;
  4179. }
  4180. foreach ($this->errors as $errmsg) {
  4181. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  4182. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  4183. }
  4184. $this->db->rollback();
  4185. return -1 * $error;
  4186. } else {
  4187. $this->error = $this->db->error();
  4188. $this->db->rollback();
  4189. return -2;
  4190. }
  4191. }
  4192. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4193. /**
  4194. * Update DB line fields total_xxx
  4195. * Used by migration
  4196. *
  4197. * @return int <0 if KO, >0 if OK
  4198. */
  4199. public function update_total()
  4200. {
  4201. // phpcs:enable
  4202. $this->db->begin();
  4203. // Clean parameters
  4204. if (empty($this->total_localtax1)) {
  4205. $this->total_localtax1 = 0;
  4206. }
  4207. if (empty($this->total_localtax2)) {
  4208. $this->total_localtax2 = 0;
  4209. }
  4210. // Mise a jour ligne en base
  4211. $sql = "UPDATE ".MAIN_DB_PREFIX."commandedet SET";
  4212. $sql .= " total_ht='".price2num($this->total_ht)."'";
  4213. $sql .= ",total_tva='".price2num($this->total_tva)."'";
  4214. $sql .= ",total_localtax1='".price2num($this->total_localtax1)."'";
  4215. $sql .= ",total_localtax2='".price2num($this->total_localtax2)."'";
  4216. $sql .= ",total_ttc='".price2num($this->total_ttc)."'";
  4217. $sql .= " WHERE rowid = ".((int) $this->rowid);
  4218. dol_syslog("OrderLine::update_total", LOG_DEBUG);
  4219. $resql = $this->db->query($sql);
  4220. if ($resql) {
  4221. $this->db->commit();
  4222. return 1;
  4223. } else {
  4224. $this->error = $this->db->error();
  4225. $this->db->rollback();
  4226. return -2;
  4227. }
  4228. }
  4229. }