commande.class.php 150 KB

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