commande.class.php 154 KB

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