commande.class.php 158 KB

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