commande.class.php 159 KB

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