commande.class.php 136 KB

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