commande.class.php 158 KB

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