commande.class.php 159 KB

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