commande.class.php 152 KB

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