commande.class.php 144 KB

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