expensereport.class.php 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843
  1. <?php
  2. /* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
  3. * Copyright (C) 2015 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
  5. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  6. * Copyright (c) 2018 Frédéric France <frederic.france@netlogic.fr>
  7. * Copyright (C) 2016-2020 Ferran Marcet <fmarcet@2byte.es>
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  21. */
  22. /**
  23. * \file htdocs/expensereport/class/expensereport.class.php
  24. * \ingroup expensereport
  25. * \brief File to manage Expense Reports
  26. */
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  28. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php';
  29. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.php';
  30. /**
  31. * Class to manage Trips and Expenses
  32. */
  33. class ExpenseReport extends CommonObject
  34. {
  35. /**
  36. * @var string ID to identify managed object
  37. */
  38. public $element = 'expensereport';
  39. /**
  40. * @var string Name of table without prefix where object is stored
  41. */
  42. public $table_element = 'expensereport';
  43. /**
  44. * @var string table element line name
  45. */
  46. public $table_element_line = 'expensereport_det';
  47. /**
  48. * @var string Fieldname with ID of parent key if this field has a parent
  49. */
  50. public $fk_element = 'fk_expensereport';
  51. /**
  52. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  53. */
  54. public $picto = 'trip';
  55. public $lines = array();
  56. public $date_debut;
  57. public $date_fin;
  58. /**
  59. * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied
  60. *
  61. * @var int Status
  62. */
  63. public $status;
  64. /**
  65. * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied
  66. *
  67. * @var int Status
  68. * @deprecated
  69. */
  70. public $fk_statut;
  71. public $vat_src_code;
  72. public $fk_c_paiement;
  73. public $paid;
  74. public $user_author_infos;
  75. public $user_validator_infos;
  76. public $rule_warning_message;
  77. // ACTIONS
  78. // Create
  79. public $date_create;
  80. public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
  81. // Update
  82. public $date_modif;
  83. public $fk_user_modif;
  84. // Refus
  85. public $date_refuse;
  86. public $detail_refuse;
  87. public $fk_user_refuse;
  88. // Annulation
  89. public $date_cancel;
  90. public $detail_cancel;
  91. public $fk_user_cancel;
  92. public $fk_user_validator; // User that is defined to approve
  93. // Validation
  94. public $date_valid; // User making validation
  95. public $fk_user_valid;
  96. public $user_valid_infos;
  97. // Approve
  98. public $date_approve;
  99. public $fk_user_approve; // User that has approved
  100. // Paiement
  101. public $user_paid_infos;
  102. /**
  103. * Draft status
  104. */
  105. const STATUS_DRAFT = 0;
  106. /**
  107. * Validated (need to be paid)
  108. */
  109. const STATUS_VALIDATED = 2;
  110. /**
  111. * Classified canceled
  112. */
  113. const STATUS_CANCELED = 4;
  114. /**
  115. * Classified approved
  116. */
  117. const STATUS_APPROVED = 5;
  118. /**
  119. * Classified refused
  120. */
  121. const STATUS_REFUSED = 99;
  122. /**
  123. * Classified paid.
  124. */
  125. const STATUS_CLOSED = 6;
  126. public $fields = array(
  127. 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  128. 'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15),
  129. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20),
  130. 'ref_number_int' =>array('type'=>'integer', 'label'=>'Ref number int', 'enabled'=>1, 'visible'=>-1, 'position'=>25),
  131. 'ref_ext' =>array('type'=>'integer', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
  132. 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'Total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>35),
  133. 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'Total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
  134. 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  135. 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
  136. 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
  137. 'date_debut' =>array('type'=>'date', 'label'=>'Date debut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>60),
  138. 'date_fin' =>array('type'=>'date', 'label'=>'Date fin', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>65),
  139. 'date_valid' =>array('type'=>'datetime', 'label'=>'Date valid', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
  140. 'date_approve' =>array('type'=>'datetime', 'label'=>'Date approve', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  141. 'date_refuse' =>array('type'=>'datetime', 'label'=>'Date refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
  142. 'date_cancel' =>array('type'=>'datetime', 'label'=>'Date cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  143. 'fk_user_author' =>array('type'=>'integer', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>100),
  144. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'Fk user modif', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
  145. 'fk_user_valid' =>array('type'=>'integer', 'label'=>'Fk user valid', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
  146. 'fk_user_validator' =>array('type'=>'integer', 'label'=>'Fk user validator', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
  147. 'fk_user_approve' =>array('type'=>'integer', 'label'=>'Fk user approve', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
  148. 'fk_user_refuse' =>array('type'=>'integer', 'label'=>'Fk user refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
  149. 'fk_user_cancel' =>array('type'=>'integer', 'label'=>'Fk user cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
  150. 'fk_c_paiement' =>array('type'=>'integer', 'label'=>'Fk c paiement', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  151. 'paid' =>array('type'=>'integer', 'label'=>'Paid', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>145),
  152. 'note_public' =>array('type'=>'text', 'label'=>'Note public', 'enabled'=>1, 'visible'=>0, 'position'=>150),
  153. 'note_private' =>array('type'=>'text', 'label'=>'Note private', 'enabled'=>1, 'visible'=>0, 'position'=>155),
  154. 'detail_refuse' =>array('type'=>'varchar(255)', 'label'=>'Detail refuse', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
  155. 'detail_cancel' =>array('type'=>'varchar(255)', 'label'=>'Detail cancel', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
  156. 'integration_compta' =>array('type'=>'integer', 'label'=>'Integration compta', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
  157. 'fk_bank_account' =>array('type'=>'integer', 'label'=>'Fk bank account', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
  158. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  159. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
  160. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency tx', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
  161. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
  162. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
  163. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
  164. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>220),
  165. 'date_create' =>array('type'=>'datetime', 'label'=>'Date create', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>300),
  166. 'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>305),
  167. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>1000),
  168. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
  169. 'fk_statut' =>array('type'=>'integer', 'label'=>'Fk statut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
  170. );
  171. /**
  172. * Constructor
  173. *
  174. * @param DoliDB $db Handler acces base de donnees
  175. */
  176. public function __construct($db)
  177. {
  178. $this->db = $db;
  179. $this->total_ht = 0;
  180. $this->total_ttc = 0;
  181. $this->total_tva = 0;
  182. $this->modepaymentid = 0;
  183. // List of language codes for status
  184. $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
  185. $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
  186. $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5');
  187. }
  188. /**
  189. * Create object in database
  190. *
  191. * @param User $user User that create
  192. * @param int $notrigger Disable triggers
  193. * @return int <0 if KO, >0 if OK
  194. */
  195. public function create($user, $notrigger = 0)
  196. {
  197. global $conf, $langs;
  198. $now = dol_now();
  199. $error = 0;
  200. // Check parameters
  201. if (empty($this->date_debut) || empty($this->date_fin))
  202. {
  203. $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date'));
  204. return -1;
  205. }
  206. $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
  207. if (empty($fuserid)) $fuserid = $user->id;
  208. $this->db->begin();
  209. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
  210. $sql .= "ref";
  211. $sql .= ",total_ht";
  212. $sql .= ",total_ttc";
  213. $sql .= ",total_tva";
  214. $sql .= ",date_debut";
  215. $sql .= ",date_fin";
  216. $sql .= ",date_create";
  217. $sql .= ",fk_user_author";
  218. $sql .= ",fk_user_validator";
  219. $sql .= ",fk_user_approve";
  220. $sql .= ",fk_user_modif";
  221. $sql .= ",fk_statut";
  222. $sql .= ",fk_c_paiement";
  223. $sql .= ",paid";
  224. $sql .= ",note_public";
  225. $sql .= ",note_private";
  226. $sql .= ",entity";
  227. $sql .= ") VALUES(";
  228. $sql .= "'(PROV)'";
  229. $sql .= ", ".$this->total_ht;
  230. $sql .= ", ".$this->total_ttc;
  231. $sql .= ", ".$this->total_tva;
  232. $sql .= ", '".$this->db->idate($this->date_debut)."'";
  233. $sql .= ", '".$this->db->idate($this->date_fin)."'";
  234. $sql .= ", '".$this->db->idate($now)."'";
  235. $sql .= ", ".$fuserid;
  236. $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
  237. $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
  238. $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null");
  239. $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0);
  240. $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null");
  241. $sql .= ", 0";
  242. $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
  243. $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
  244. $sql .= ", ".$conf->entity;
  245. $sql .= ")";
  246. $result = $this->db->query($sql);
  247. if ($result)
  248. {
  249. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  250. $this->ref = '(PROV'.$this->id.')';
  251. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
  252. $resql = $this->db->query($sql);
  253. if (!$resql)
  254. {
  255. $this->error = $this->db->lasterror();
  256. $error++;
  257. }
  258. if (!$error)
  259. {
  260. if (is_array($this->lines) && count($this->lines) > 0)
  261. {
  262. foreach ($this->lines as $line)
  263. {
  264. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  265. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  266. if (!is_object($line)) {
  267. $line = (object) $line;
  268. $newndfline = new ExpenseReportLine($this->db);
  269. $newndfline->fk_expensereport = $line->fk_expensereport;
  270. $newndfline->fk_c_type_fees = $line->fk_c_type_fees;
  271. $newndfline->fk_project = $line->fk_project;
  272. $newndfline->vatrate = $line->vatrate;
  273. $newndfline->vat_src_code = $line->vat_src_code;
  274. $newndfline->comments = $line->comments;
  275. $newndfline->qty = $line->qty;
  276. $newndfline->value_unit = $line->value_unit;
  277. $newndfline->total_ht = $line->total_ht;
  278. $newndfline->total_ttc = $line->total_ttc;
  279. $newndfline->total_tva = $line->total_tva;
  280. $newndfline->date = $line->date;
  281. $newndfline->rule_warning_message = $line->rule_warning_message;
  282. $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat;
  283. $newndfline->fk_ecm_files = $line->fk_ecm_files;
  284. } else {
  285. $newndfline = $line;
  286. }
  287. //$newndfline=new ExpenseReportLine($this->db);
  288. $newndfline->fk_expensereport = $this->id;
  289. $result = $newndfline->insert();
  290. if ($result < 0)
  291. {
  292. $this->error = $newndfline->error;
  293. $error++;
  294. break;
  295. }
  296. }
  297. }
  298. }
  299. if (!$error)
  300. {
  301. $result = $this->insertExtraFields();
  302. if ($result < 0) $error++;
  303. }
  304. if (!$error)
  305. {
  306. $result = $this->update_price();
  307. if ($result > 0)
  308. {
  309. if (!$notrigger)
  310. {
  311. // Call trigger
  312. $result = $this->call_trigger('EXPENSE_REPORT_CREATE', $user);
  313. if ($result < 0) {
  314. $error++;
  315. }
  316. // End call triggers
  317. }
  318. if (empty($error))
  319. {
  320. $this->db->commit();
  321. return $this->id;
  322. } else {
  323. $this->db->rollback();
  324. return -4;
  325. }
  326. } else {
  327. $this->db->rollback();
  328. return -3;
  329. }
  330. } else {
  331. dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
  332. $this->db->rollback();
  333. return -2;
  334. }
  335. } else {
  336. $this->error = $this->db->lasterror()." sql=".$sql;
  337. $this->db->rollback();
  338. return -1;
  339. }
  340. }
  341. /**
  342. * Load an object from its id and create a new one in database
  343. *
  344. * @param User $user User making the clone
  345. * @param int $fk_user_author Id of new user
  346. * @return int New id of clone
  347. */
  348. public function createFromClone(User $user, $fk_user_author)
  349. {
  350. global $hookmanager;
  351. $error = 0;
  352. if (empty($fk_user_author)) $fk_user_author = $user->id;
  353. $this->db->begin();
  354. // get extrafields so they will be clone
  355. //foreach($this->lines as $line)
  356. //$line->fetch_optionals();
  357. // Load source object
  358. $objFrom = clone $this;
  359. $this->id = 0;
  360. $this->ref = '';
  361. $this->status = 0;
  362. $this->fk_statut = 0; // deprecated
  363. // Clear fields
  364. $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
  365. $this->fk_user_valid = '';
  366. $this->date_create = '';
  367. $this->date_creation = '';
  368. $this->date_validation = '';
  369. // Remove link on lines to a joined file
  370. if (is_array($this->lines) && count($this->lines) > 0)
  371. {
  372. foreach ($this->lines as $key => $line)
  373. {
  374. $this->lines[$key]->fk_ecm_files = 0;
  375. }
  376. }
  377. // Create clone
  378. $this->context['createfromclone'] = 'createfromclone';
  379. $result = $this->create($user);
  380. if ($result < 0) $error++;
  381. if (!$error)
  382. {
  383. // Hook of thirdparty module
  384. if (is_object($hookmanager))
  385. {
  386. $parameters = array('objFrom'=>$objFrom);
  387. $action = '';
  388. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  389. if ($reshook < 0) $error++;
  390. }
  391. }
  392. unset($this->context['createfromclone']);
  393. // End
  394. if (!$error)
  395. {
  396. $this->db->commit();
  397. return $this->id;
  398. } else {
  399. $this->db->rollback();
  400. return -1;
  401. }
  402. }
  403. /**
  404. * update
  405. *
  406. * @param User $user User making change
  407. * @param int $notrigger Disable triggers
  408. * @param User $userofexpensereport New user we want to have the expense report on.
  409. * @return int <0 if KO, >0 if OK
  410. */
  411. public function update($user, $notrigger = 0, $userofexpensereport = null)
  412. {
  413. global $langs;
  414. $error = 0;
  415. $this->db->begin();
  416. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
  417. $sql .= " total_ht = ".$this->total_ht;
  418. $sql .= " , total_ttc = ".$this->total_ttc;
  419. $sql .= " , total_tva = ".$this->total_tva;
  420. $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'";
  421. $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'";
  422. if ($userofexpensereport && is_object($userofexpensereport))
  423. {
  424. $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? $userofexpensereport->id : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for.
  425. }
  426. $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
  427. $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null");
  428. $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
  429. $sql .= " , fk_user_modif = ".$user->id;
  430. $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0');
  431. $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null");
  432. $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''");
  433. $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''");
  434. $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''");
  435. $sql .= " WHERE rowid = ".$this->id;
  436. dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
  437. $result = $this->db->query($sql);
  438. if ($result)
  439. {
  440. if (!$notrigger)
  441. {
  442. // Call trigger
  443. $result = $this->call_trigger('EXPENSE_REPORT_UPDATE', $user);
  444. if ($result < 0) {
  445. $error++;
  446. }
  447. // End call triggers
  448. }
  449. if (empty($error))
  450. {
  451. $this->db->commit();
  452. return 1;
  453. } else {
  454. $this->db->rollback();
  455. $this->error = $this->db->error();
  456. return -2;
  457. }
  458. } else {
  459. $this->db->rollback();
  460. $this->error = $this->db->error();
  461. return -1;
  462. }
  463. }
  464. /**
  465. * Load an object from database
  466. *
  467. * @param int $id Id {@min 1}
  468. * @param string $ref Ref {@name ref}
  469. * @return int <0 if KO, >0 if OK
  470. */
  471. public function fetch($id, $ref = '')
  472. {
  473. global $conf;
  474. $sql = "SELECT d.rowid, d.entity, d.ref, d.note_public, d.note_private,"; // DEFAULT
  475. $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS
  476. $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS
  477. $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int)
  478. $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime)
  479. $sql .= " d.fk_user_author, d.fk_user_modif, d.fk_user_validator,";
  480. $sql .= " d.fk_user_valid, d.fk_user_approve,";
  481. $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid";
  482. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d";
  483. if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'";
  484. else $sql .= " WHERE d.rowid = ".$id;
  485. //$sql.= $restrict;
  486. dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
  487. $resql = $this->db->query($sql);
  488. if ($resql)
  489. {
  490. $obj = $this->db->fetch_object($resql);
  491. if ($obj)
  492. {
  493. $this->id = $obj->rowid;
  494. $this->ref = $obj->ref;
  495. $this->entity = $obj->entity;
  496. $this->total_ht = $obj->total_ht;
  497. $this->total_tva = $obj->total_tva;
  498. $this->total_ttc = $obj->total_ttc;
  499. $this->note_public = $obj->note_public;
  500. $this->note_private = $obj->note_private;
  501. $this->detail_refuse = $obj->detail_refuse;
  502. $this->detail_cancel = $obj->detail_cancel;
  503. $this->date_debut = $this->db->jdate($obj->date_debut);
  504. $this->date_fin = $this->db->jdate($obj->date_fin);
  505. $this->date_valid = $this->db->jdate($obj->date_valid);
  506. $this->date_approve = $this->db->jdate($obj->date_approve);
  507. $this->date_create = $this->db->jdate($obj->date_create);
  508. $this->date_modif = $this->db->jdate($obj->date_modif);
  509. $this->date_refuse = $this->db->jdate($obj->date_refuse);
  510. $this->date_cancel = $this->db->jdate($obj->date_cancel);
  511. $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
  512. $this->fk_user_modif = $obj->fk_user_modif;
  513. $this->fk_user_validator = $obj->fk_user_validator;
  514. $this->fk_user_valid = $obj->fk_user_valid;
  515. $this->fk_user_refuse = $obj->fk_user_refuse;
  516. $this->fk_user_cancel = $obj->fk_user_cancel;
  517. $this->fk_user_approve = $obj->fk_user_approve;
  518. $user_author = new User($this->db);
  519. if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author);
  520. $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname);
  521. $user_approver = new User($this->db);
  522. if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve);
  523. elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility
  524. $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname);
  525. $this->fk_statut = $obj->status; // deprecated
  526. $this->status = $obj->status;
  527. $this->fk_c_paiement = $obj->fk_c_paiement;
  528. $this->paid = $obj->paid;
  529. if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED)
  530. {
  531. $user_valid = new User($this->db);
  532. if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid);
  533. $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname);
  534. }
  535. $this->fetch_optionals();
  536. $result = $this->fetch_lines();
  537. return $result;
  538. } else {
  539. return 0;
  540. }
  541. } else {
  542. $this->error = $this->db->lasterror();
  543. return -1;
  544. }
  545. }
  546. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  547. /**
  548. * Classify the expense report as paid
  549. *
  550. * @param int $id Id of expense report
  551. * @param user $fuser User making change
  552. * @param int $notrigger Disable triggers
  553. * @return int <0 if KO, >0 if OK
  554. */
  555. public function set_paid($id, $fuser, $notrigger = 0)
  556. {
  557. // phpcs:enable
  558. $error = 0;
  559. $this->db->begin();
  560. $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport";
  561. $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1";
  562. $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED;
  563. dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG);
  564. $resql = $this->db->query($sql);
  565. if ($resql)
  566. {
  567. if ($this->db->affected_rows($resql))
  568. {
  569. if (!$notrigger)
  570. {
  571. // Call trigger
  572. $result = $this->call_trigger('EXPENSE_REPORT_PAID', $fuser);
  573. if ($result < 0) {
  574. $error++;
  575. }
  576. // End call triggers
  577. }
  578. if (empty($error))
  579. {
  580. $this->db->commit();
  581. return 1;
  582. } else {
  583. $this->db->rollback();
  584. $this->error = $this->db->error();
  585. return -2;
  586. }
  587. } else {
  588. $this->db->commit();
  589. return 0;
  590. }
  591. } else {
  592. $this->db->rollback();
  593. dol_print_error($this->db);
  594. return -1;
  595. }
  596. }
  597. /**
  598. * Returns the label status
  599. *
  600. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  601. * @return string Label
  602. */
  603. public function getLibStatut($mode = 0)
  604. {
  605. return $this->LibStatut($this->status, $mode);
  606. }
  607. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  608. /**
  609. * Returns the label of a status
  610. *
  611. * @param int $status ID status
  612. * @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
  613. * @return string Label
  614. */
  615. public function LibStatut($status, $mode = 0)
  616. {
  617. // phpcs:enable
  618. global $langs;
  619. $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]);
  620. $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]);
  621. $statusType = $this->statuts_logo[$status];
  622. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  623. }
  624. /**
  625. * Load information on object
  626. *
  627. * @param int $id Id of object
  628. * @return void
  629. */
  630. public function info($id)
  631. {
  632. global $conf;
  633. $sql = "SELECT f.rowid,";
  634. $sql .= " f.date_create as datec,";
  635. $sql .= " f.tms as date_modification,";
  636. $sql .= " f.date_valid as datev,";
  637. $sql .= " f.date_approve as datea,";
  638. //$sql.= " f.fk_user_author as fk_user_creation,"; // This is not user of creation but user the expense is for.
  639. $sql .= " f.fk_user_modif as fk_user_modification,";
  640. $sql .= " f.fk_user_valid,";
  641. $sql .= " f.fk_user_approve";
  642. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f";
  643. $sql .= " WHERE f.rowid = ".$id;
  644. $sql .= " AND f.entity = ".$conf->entity;
  645. $resql = $this->db->query($sql);
  646. if ($resql)
  647. {
  648. if ($this->db->num_rows($resql))
  649. {
  650. $obj = $this->db->fetch_object($resql);
  651. $this->id = $obj->rowid;
  652. $this->date_creation = $this->db->jdate($obj->datec);
  653. $this->date_modification = $this->db->jdate($obj->date_modification);
  654. $this->date_validation = $this->db->jdate($obj->datev);
  655. $this->date_approbation = $this->db->jdate($obj->datea);
  656. $cuser = new User($this->db);
  657. $cuser->fetch($obj->fk_user_author);
  658. $this->user_creation = $cuser;
  659. if ($obj->fk_user_creation)
  660. {
  661. $cuser = new User($this->db);
  662. $cuser->fetch($obj->fk_user_creation);
  663. $this->user_creation = $cuser;
  664. }
  665. if ($obj->fk_user_valid)
  666. {
  667. $vuser = new User($this->db);
  668. $vuser->fetch($obj->fk_user_valid);
  669. $this->user_validation = $vuser;
  670. }
  671. if ($obj->fk_user_modification)
  672. {
  673. $muser = new User($this->db);
  674. $muser->fetch($obj->fk_user_modification);
  675. $this->user_modification = $muser;
  676. }
  677. if ($obj->fk_user_approve)
  678. {
  679. $auser = new User($this->db);
  680. $auser->fetch($obj->fk_user_approve);
  681. $this->user_approve = $auser;
  682. }
  683. }
  684. $this->db->free($resql);
  685. } else {
  686. dol_print_error($this->db);
  687. }
  688. }
  689. /**
  690. * Initialise an instance with random values.
  691. * Used to build previews or test instances.
  692. * id must be 0 if object instance is a specimen.
  693. *
  694. * @return void
  695. */
  696. public function initAsSpecimen()
  697. {
  698. global $user, $langs, $conf;
  699. $now = dol_now();
  700. // Initialise parametres
  701. $this->id = 0;
  702. $this->ref = 'SPECIMEN';
  703. $this->specimen = 1;
  704. $this->entity = 1;
  705. $this->date_create = $now;
  706. $this->date_debut = $now;
  707. $this->date_fin = $now;
  708. $this->date_valid = $now;
  709. $this->date_approve = $now;
  710. $type_fees_id = 2; // TF_TRIP
  711. $this->status = 5;
  712. $this->fk_statut = 5;
  713. $this->fk_user_author = $user->id;
  714. $this->fk_user_validator = $user->id;
  715. $this->fk_user_valid = $user->id;
  716. $this->fk_user_approve = $user->id;
  717. $this->note_private = 'Private note';
  718. $this->note_public = 'SPECIMEN';
  719. $nbp = 5;
  720. $xnbp = 0;
  721. while ($xnbp < $nbp) {
  722. $line = new ExpenseReportLine($this->db);
  723. $line->comments = $langs->trans("Comment")." ".$xnbp;
  724. $line->date = ($now - 3600 * (1 + $xnbp));
  725. $line->total_ht = 100;
  726. $line->total_tva = 20;
  727. $line->total_ttc = 120;
  728. $line->qty = 1;
  729. $line->vatrate = 20;
  730. $line->value_unit = 120;
  731. $line->fk_expensereport = 0;
  732. $line->type_fees_code = 'TRA';
  733. $line->fk_c_type_fees = $type_fees_id;
  734. $line->projet_ref = 'ABC';
  735. $this->lines[$xnbp] = $line;
  736. $xnbp++;
  737. $this->total_ht += $line->total_ht;
  738. $this->total_tva += $line->total_tva;
  739. $this->total_ttc += $line->total_ttc;
  740. }
  741. }
  742. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  743. /**
  744. * fetch_line_by_project
  745. *
  746. * @param int $projectid Project id
  747. * @param User $user User
  748. * @return int <0 if KO, >0 if OK
  749. */
  750. public function fetch_line_by_project($projectid, $user = '')
  751. {
  752. // phpcs:enable
  753. global $conf, $db, $langs;
  754. $langs->load('trips');
  755. if ($user->rights->expensereport->lire) {
  756. $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc";
  757. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de";
  758. $sql .= " WHERE de.fk_projet = ".$projectid;
  759. dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
  760. $result = $this->db->query($sql);
  761. if ($result)
  762. {
  763. $num = $this->db->num_rows($result);
  764. $i = 0;
  765. $total_HT = 0;
  766. $total_TTC = 0;
  767. while ($i < $num)
  768. {
  769. $objp = $this->db->fetch_object($result);
  770. $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status";
  771. $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d";
  772. $sql2 .= " WHERE d.rowid = ".((int) $objp->fk_expensereport);
  773. $result2 = $this->db->query($sql2);
  774. $obj = $this->db->fetch_object($result2);
  775. $objp->fk_user_author = $obj->fk_user_author;
  776. $objp->ref = $obj->ref;
  777. $objp->fk_c_expensereport_status = $obj->status;
  778. $objp->rowid = $obj->rowid;
  779. $total_HT = $total_HT + $objp->total_ht;
  780. $total_TTC = $total_TTC + $objp->total_ttc;
  781. $author = new User($this->db);
  782. $author->fetch($objp->fk_user_author);
  783. print '<tr>';
  784. print '<td><a href="'.DOL_URL_ROOT.'/expensereport/card.php?id='.$objp->rowid.'">'.$objp->ref_num.'</a></td>';
  785. print '<td class="center">'.dol_print_date($objp->date, 'day').'</td>';
  786. print '<td>'.$author->getNomUrl(1).'</td>';
  787. print '<td>'.$objp->comments.'</td>';
  788. print '<td class="right">'.price($objp->total_ht).'</td>';
  789. print '<td class="right">'.price($objp->total_ttc).'</td>';
  790. print '<td class="right">';
  791. switch ($objp->fk_c_expensereport_status) {
  792. case 4:
  793. print img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
  794. break;
  795. case 1:
  796. print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0');
  797. break;
  798. case 2:
  799. print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3');
  800. break;
  801. case 5:
  802. print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3');
  803. break;
  804. case 6:
  805. print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4');
  806. break;
  807. }
  808. /*
  809. if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
  810. if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
  811. if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1');
  812. if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3');
  813. if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
  814. if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6');
  815. */
  816. print '</td>';
  817. print '</tr>';
  818. $i++;
  819. }
  820. print '<tr class="liste_total"><td colspan="4">'.$langs->trans("Number").': '.$i.'</td>';
  821. print '<td class="right" width="100">'.$langs->trans("TotalHT").' : '.price($total_HT).'</td>';
  822. print '<td class="right" width="100">'.$langs->trans("TotalTTC").' : '.price($total_TTC).'</td>';
  823. print '<td>&nbsp;</td>';
  824. print '</tr>';
  825. } else {
  826. $this->error = $this->db->lasterror();
  827. return -1;
  828. }
  829. }
  830. }
  831. /**
  832. * recalculer
  833. * TODO Replace this with call to update_price if not already done
  834. *
  835. * @param int $id Id of expense report
  836. * @return int <0 if KO, >0 if OK
  837. */
  838. public function recalculer($id)
  839. {
  840. $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva';
  841. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt';
  842. $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id;
  843. $total_ht = 0; $total_tva = 0; $total_ttc = 0;
  844. $result = $this->db->query($sql);
  845. if ($result)
  846. {
  847. $num = $this->db->num_rows($result);
  848. $i = 0;
  849. while ($i < $num):
  850. $objp = $this->db->fetch_object($result);
  851. $total_ht += $objp->total_ht;
  852. $total_tva += $objp->total_tva;
  853. $i++;
  854. endwhile;
  855. $total_ttc = $total_ht + $total_tva;
  856. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
  857. $sql .= " total_ht = ".$total_ht;
  858. $sql .= " , total_ttc = ".$total_ttc;
  859. $sql .= " , total_tva = ".$total_tva;
  860. $sql .= " WHERE rowid = ".$id;
  861. $result = $this->db->query($sql);
  862. if ($result):
  863. $this->db->free($result);
  864. return 1;
  865. else :
  866. $this->error = $this->db->lasterror();
  867. dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR);
  868. return -3;
  869. endif;
  870. } else {
  871. $this->error = $this->db->lasterror();
  872. dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR);
  873. return -3;
  874. }
  875. }
  876. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  877. /**
  878. * fetch_lines
  879. *
  880. * @return int <0 if OK, >0 if KO
  881. */
  882. public function fetch_lines()
  883. {
  884. // phpcs:enable
  885. global $conf;
  886. $this->lines = array();
  887. $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,';
  888. $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,';
  889. $sql .= ' de.total_ht, de.total_tva, de.total_ttc,';
  890. $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,';
  891. $sql .= ' p.ref as ref_projet, p.title as title_projet';
  892. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de';
  893. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id';
  894. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid';
  895. $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id;
  896. if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID))
  897. {
  898. $sql .= ' ORDER BY de.rang ASC, de.rowid ASC';
  899. } else {
  900. $sql .= ' ORDER BY de.rang ASC, de.date ASC';
  901. }
  902. $resql = $this->db->query($sql);
  903. if ($resql)
  904. {
  905. $num = $this->db->num_rows($resql);
  906. $i = 0;
  907. while ($i < $num)
  908. {
  909. $objp = $this->db->fetch_object($resql);
  910. $deplig = new ExpenseReportLine($this->db);
  911. $deplig->rowid = $objp->rowid;
  912. $deplig->id = $objp->rowid;
  913. $deplig->comments = $objp->comments;
  914. $deplig->qty = $objp->qty;
  915. $deplig->value_unit = $objp->value_unit;
  916. $deplig->date = $objp->date;
  917. $deplig->dates = $this->db->jdate($objp->date);
  918. $deplig->fk_expensereport = $objp->fk_expensereport;
  919. $deplig->fk_c_type_fees = $objp->fk_c_type_fees;
  920. $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
  921. $deplig->fk_projet = $objp->fk_project; // deprecated
  922. $deplig->fk_project = $objp->fk_project;
  923. $deplig->fk_ecm_files = $objp->fk_ecm_files;
  924. $deplig->total_ht = $objp->total_ht;
  925. $deplig->total_tva = $objp->total_tva;
  926. $deplig->total_ttc = $objp->total_ttc;
  927. $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees;
  928. $deplig->type_fees_libelle = $objp->libelle_type_fees;
  929. $deplig->tva_tx = $objp->tva_tx;
  930. $deplig->vatrate = $objp->tva_tx;
  931. $deplig->projet_ref = $objp->ref_projet;
  932. $deplig->projet_title = $objp->title_projet;
  933. $deplig->rang = $objp->rang;
  934. $this->lines[$i] = $deplig;
  935. $i++;
  936. }
  937. $this->db->free($resql);
  938. return 1;
  939. } else {
  940. $this->error = $this->db->lasterror();
  941. dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR);
  942. return -3;
  943. }
  944. }
  945. /**
  946. * Delete object in database
  947. *
  948. * @param User $user User that delete
  949. * @param bool $notrigger false=launch triggers after, true=disable triggers
  950. * @return int <0 if KO, >0 if OK
  951. */
  952. public function delete(User $user = null, $notrigger = false)
  953. {
  954. global $conf;
  955. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  956. $error = 0;
  957. $this->db->begin();
  958. if (!$notrigger) {
  959. // Call trigger
  960. $result = $this->call_trigger('EXPENSEREPORT_DELETE', $user);
  961. if ($result < 0) { $error++; }
  962. // End call triggers
  963. }
  964. // Delete extrafields of lines and lines
  965. if (!$error && !empty($this->table_element_line)) {
  966. $tabletodelete = $this->table_element_line;
  967. //$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.")";
  968. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete." WHERE ".$this->fk_element." = ".$this->id;
  969. if (!$this->db->query($sql)) {
  970. $error++;
  971. $this->error = $this->db->lasterror();
  972. $this->errors[] = $this->error;
  973. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  974. }
  975. }
  976. if (!$error) {
  977. // Delete linked object
  978. $res = $this->deleteObjectLinked();
  979. if ($res < 0) $error++;
  980. }
  981. if (!$error) {
  982. // Delete linked contacts
  983. $res = $this->delete_linked_contact();
  984. if ($res < 0) $error++;
  985. }
  986. // Removed extrafields of object
  987. if (!$error) {
  988. $result = $this->deleteExtraFields();
  989. if ($result < 0) {
  990. $error++;
  991. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  992. }
  993. }
  994. // Delete main record
  995. if (!$error) {
  996. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".$this->id;
  997. $res = $this->db->query($sql);
  998. if (!$res) {
  999. $error++;
  1000. $this->error = $this->db->lasterror();
  1001. $this->errors[] = $this->error;
  1002. dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
  1003. }
  1004. }
  1005. // Delete record into ECM index and physically
  1006. if (!$error) {
  1007. $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
  1008. if (!$res) {
  1009. $error++;
  1010. }
  1011. }
  1012. if (!$error) {
  1013. // We remove directory
  1014. $ref = dol_sanitizeFileName($this->ref);
  1015. if ($conf->expensereport->multidir_output[$this->entity] && !empty($this->ref)) {
  1016. $dir = $conf->expensereport->multidir_output[$this->entity]."/".$ref;
  1017. $file = $dir."/".$ref.".pdf";
  1018. if (file_exists($file)) {
  1019. dol_delete_preview($this);
  1020. if (!dol_delete_file($file, 0, 0, 0, $this)) {
  1021. $this->error = 'ErrorFailToDeleteFile';
  1022. $this->errors[] = $this->error;
  1023. $this->db->rollback();
  1024. return 0;
  1025. }
  1026. }
  1027. if (file_exists($dir)) {
  1028. $res = @dol_delete_dir_recursive($dir);
  1029. if (!$res) {
  1030. $this->error = 'ErrorFailToDeleteDir';
  1031. $this->errors[] = $this->error;
  1032. $this->db->rollback();
  1033. return 0;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. if (!$error) {
  1039. dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
  1040. $this->db->commit();
  1041. return 1;
  1042. } else {
  1043. $this->db->rollback();
  1044. return -1;
  1045. }
  1046. }
  1047. /**
  1048. * Set to status validate
  1049. *
  1050. * @param User $fuser User
  1051. * @param int $notrigger Disable triggers
  1052. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1053. */
  1054. public function setValidate($fuser, $notrigger = 0)
  1055. {
  1056. global $conf, $langs, $user;
  1057. $error = 0;
  1058. $now = dol_now();
  1059. // Protection
  1060. if ($this->status == self::STATUS_VALIDATED)
  1061. {
  1062. dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
  1063. return 0;
  1064. }
  1065. $this->date_valid = $now; // Required for the getNextNum later.
  1066. // Define new ref
  1067. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
  1068. {
  1069. $num = $this->getNextNumRef();
  1070. } else {
  1071. $num = $this->ref;
  1072. }
  1073. if (empty($num) || $num < 0) return -1;
  1074. $this->newref = dol_sanitizeFileName($num);
  1075. $this->db->begin();
  1076. // Validate
  1077. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1078. $sql .= " SET ref = '".$this->db->escape($num)."',";
  1079. $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
  1080. $sql .= " date_valid='".$this->db->idate($this->date_valid)."',";
  1081. $sql .= " fk_user_valid = ".$user->id;
  1082. $sql .= " WHERE rowid = ".$this->id;
  1083. $resql = $this->db->query($sql);
  1084. if ($resql)
  1085. {
  1086. if (!$error && !$notrigger)
  1087. {
  1088. // Call trigger
  1089. $result = $this->call_trigger('EXPENSE_REPORT_VALIDATE', $fuser);
  1090. if ($result < 0) {
  1091. $error++;
  1092. }
  1093. // End call triggers
  1094. }
  1095. if (!$error)
  1096. {
  1097. $this->oldref = $this->ref;
  1098. // Rename directory if dir was a temporary ref
  1099. if (preg_match('/^[\(]?PROV/i', $this->ref))
  1100. {
  1101. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1102. // Now we rename also files into index
  1103. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expensereport/".$this->db->escape($this->newref)."'";
  1104. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  1105. $resql = $this->db->query($sql);
  1106. if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
  1107. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  1108. $oldref = dol_sanitizeFileName($this->ref);
  1109. $newref = dol_sanitizeFileName($num);
  1110. $dirsource = $conf->expensereport->dir_output.'/'.$oldref;
  1111. $dirdest = $conf->expensereport->dir_output.'/'.$newref;
  1112. if (!$error && file_exists($dirsource))
  1113. {
  1114. dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest);
  1115. if (@rename($dirsource, $dirdest))
  1116. {
  1117. dol_syslog("Rename ok");
  1118. // Rename docs starting with $oldref with $newref
  1119. $listoffiles = dol_dir_list($conf->expensereport->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  1120. foreach ($listoffiles as $fileentry)
  1121. {
  1122. $dirsource = $fileentry['name'];
  1123. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  1124. $dirsource = $fileentry['path'].'/'.$dirsource;
  1125. $dirdest = $fileentry['path'].'/'.$dirdest;
  1126. @rename($dirsource, $dirdest);
  1127. }
  1128. }
  1129. }
  1130. }
  1131. }
  1132. // Set new ref and current status
  1133. if (!$error)
  1134. {
  1135. $this->ref = $num;
  1136. $this->status = self::STATUS_VALIDATED;
  1137. }
  1138. if (empty($error))
  1139. {
  1140. $this->db->commit();
  1141. return 1;
  1142. } else {
  1143. $this->db->rollback();
  1144. $this->error = $this->db->error();
  1145. return -2;
  1146. }
  1147. } else {
  1148. $this->db->rollback();
  1149. $this->error = $this->db->lasterror();
  1150. return -1;
  1151. }
  1152. }
  1153. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1154. /**
  1155. * set_save_from_refuse
  1156. *
  1157. * @param User $fuser User
  1158. * @return int <0 if KO, >0 if OK
  1159. */
  1160. public function set_save_from_refuse($fuser)
  1161. {
  1162. // phpcs:enable
  1163. global $conf, $langs;
  1164. // Sélection de la date de début de la NDF
  1165. $sql = 'SELECT date_debut';
  1166. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  1167. $sql .= ' WHERE rowid = '.$this->id;
  1168. $result = $this->db->query($sql);
  1169. $objp = $this->db->fetch_object($result);
  1170. $this->date_debut = $this->db->jdate($objp->date_debut);
  1171. if ($this->status != self::STATUS_VALIDATED)
  1172. {
  1173. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1174. $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
  1175. $sql .= ' WHERE rowid = '.$this->id;
  1176. dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG);
  1177. if ($this->db->query($sql))
  1178. {
  1179. return 1;
  1180. } else {
  1181. $this->error = $this->db->lasterror();
  1182. return -1;
  1183. }
  1184. } else {
  1185. dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING);
  1186. }
  1187. }
  1188. /**
  1189. * Set status to approved
  1190. *
  1191. * @param User $fuser User
  1192. * @param int $notrigger Disable triggers
  1193. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1194. */
  1195. public function setApproved($fuser, $notrigger = 0)
  1196. {
  1197. $now = dol_now();
  1198. $error = 0;
  1199. // date approval
  1200. $this->date_approve = $now;
  1201. if ($this->status != self::STATUS_APPROVED)
  1202. {
  1203. $this->db->begin();
  1204. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1205. $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.",";
  1206. $sql .= " date_approve='".$this->db->idate($this->date_approve)."'";
  1207. $sql .= ' WHERE rowid = '.$this->id;
  1208. if ($this->db->query($sql))
  1209. {
  1210. if (!$notrigger)
  1211. {
  1212. // Call trigger
  1213. $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser);
  1214. if ($result < 0) {
  1215. $error++;
  1216. }
  1217. // End call triggers
  1218. }
  1219. if (empty($error))
  1220. {
  1221. $this->db->commit();
  1222. return 1;
  1223. } else {
  1224. $this->db->rollback();
  1225. $this->error = $this->db->error();
  1226. return -2;
  1227. }
  1228. } else {
  1229. $this->db->rollback();
  1230. $this->error = $this->db->lasterror();
  1231. return -1;
  1232. }
  1233. } else {
  1234. dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING);
  1235. }
  1236. return 0;
  1237. }
  1238. /**
  1239. * setDeny
  1240. *
  1241. * @param User $fuser User
  1242. * @param string $details Details
  1243. * @param int $notrigger Disable triggers
  1244. * @return int
  1245. */
  1246. public function setDeny($fuser, $details, $notrigger = 0)
  1247. {
  1248. $now = dol_now();
  1249. $error = 0;
  1250. // date de refus
  1251. if ($this->status != self::STATUS_REFUSED)
  1252. {
  1253. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1254. $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.",";
  1255. $sql .= " date_refuse='".$this->db->idate($now)."',";
  1256. $sql .= " detail_refuse='".$this->db->escape($details)."',";
  1257. $sql .= " fk_user_approve = NULL";
  1258. $sql .= ' WHERE rowid = '.$this->id;
  1259. if ($this->db->query($sql))
  1260. {
  1261. $this->fk_statut = 99; // deprecated
  1262. $this->status = 99;
  1263. $this->fk_user_refuse = $fuser->id;
  1264. $this->detail_refuse = $details;
  1265. $this->date_refuse = $now;
  1266. if (!$notrigger)
  1267. {
  1268. // Call trigger
  1269. $result = $this->call_trigger('EXPENSE_REPORT_DENY', $fuser);
  1270. if ($result < 0) {
  1271. $error++;
  1272. }
  1273. // End call triggers
  1274. }
  1275. if (empty($error))
  1276. {
  1277. $this->db->commit();
  1278. return 1;
  1279. } else {
  1280. $this->db->rollback();
  1281. $this->error = $this->db->error();
  1282. return -2;
  1283. }
  1284. } else {
  1285. $this->db->rollback();
  1286. $this->error = $this->db->lasterror();
  1287. return -1;
  1288. }
  1289. } else {
  1290. dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING);
  1291. }
  1292. }
  1293. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1294. /**
  1295. * set_unpaid
  1296. *
  1297. * @param User $fuser User
  1298. * @param int $notrigger Disable triggers
  1299. * @return int <0 if KO, >0 if OK
  1300. */
  1301. public function set_unpaid($fuser, $notrigger = 0)
  1302. {
  1303. // phpcs:enable
  1304. $error = 0;
  1305. if ($this->paid)
  1306. {
  1307. $this->db->begin();
  1308. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1309. $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED;
  1310. $sql .= ' WHERE rowid = '.$this->id;
  1311. dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG);
  1312. if ($this->db->query($sql))
  1313. {
  1314. if (!$notrigger)
  1315. {
  1316. // Call trigger
  1317. $result = $this->call_trigger('EXPENSE_REPORT_UNPAID', $fuser);
  1318. if ($result < 0) {
  1319. $error++;
  1320. }
  1321. // End call triggers
  1322. }
  1323. if (empty($error))
  1324. {
  1325. $this->db->commit();
  1326. return 1;
  1327. } else {
  1328. $this->db->rollback();
  1329. $this->error = $this->db->error();
  1330. return -2;
  1331. }
  1332. } else {
  1333. $this->db->rollback();
  1334. $this->error = $this->db->error();
  1335. return -1;
  1336. }
  1337. } else {
  1338. dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING);
  1339. }
  1340. }
  1341. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1342. /**
  1343. * set_cancel
  1344. *
  1345. * @param User $fuser User
  1346. * @param string $detail Detail
  1347. * @param int $notrigger Disable triggers
  1348. * @return int <0 if KO, >0 if OK
  1349. */
  1350. public function set_cancel($fuser, $detail, $notrigger = 0)
  1351. {
  1352. // phpcs:enable
  1353. $error = 0;
  1354. $this->date_cancel = $this->db->idate(dol_now());
  1355. if ($this->status != self::STATUS_CANCELED)
  1356. {
  1357. $this->db->begin();
  1358. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1359. $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id;
  1360. $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'";
  1361. $sql .= " ,detail_cancel='".$this->db->escape($detail)."'";
  1362. $sql .= ' WHERE rowid = '.$this->id;
  1363. dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG);
  1364. if ($this->db->query($sql))
  1365. {
  1366. if (!$notrigger)
  1367. {
  1368. // Call trigger
  1369. $result = $this->call_trigger('EXPENSE_REPORT_CANCEL', $fuser);
  1370. if ($result < 0) {
  1371. $error++;
  1372. }
  1373. // End call triggers
  1374. }
  1375. if (empty($error))
  1376. {
  1377. $this->db->commit();
  1378. return 1;
  1379. } else {
  1380. $this->db->rollback();
  1381. $this->error = $this->db->error();
  1382. return -2;
  1383. }
  1384. } else {
  1385. $this->db->rollback();
  1386. $this->error = $this->db->error();
  1387. return -1;
  1388. }
  1389. } else {
  1390. dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING);
  1391. }
  1392. }
  1393. /**
  1394. * Return next reference of expense report not already used
  1395. *
  1396. * @return string free ref
  1397. */
  1398. public function getNextNumRef()
  1399. {
  1400. global $langs, $conf;
  1401. $langs->load("trips");
  1402. if (!empty($conf->global->EXPENSEREPORT_ADDON))
  1403. {
  1404. $mybool = false;
  1405. $file = $conf->global->EXPENSEREPORT_ADDON.".php";
  1406. $classname = $conf->global->EXPENSEREPORT_ADDON;
  1407. // Include file with class
  1408. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  1409. foreach ($dirmodels as $reldir)
  1410. {
  1411. $dir = dol_buildpath($reldir."core/modules/expensereport/");
  1412. // Load file with numbering class (if found)
  1413. $mybool |= @include_once $dir.$file;
  1414. }
  1415. if ($mybool === false) {
  1416. dol_print_error('', "Failed to include file ".$file);
  1417. return '';
  1418. }
  1419. $obj = new $classname();
  1420. $numref = $obj->getNextValue($this);
  1421. if ($numref != "")
  1422. {
  1423. return $numref;
  1424. } else {
  1425. $this->error = $obj->error;
  1426. $this->errors = $obj->errors;
  1427. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  1428. return -1;
  1429. }
  1430. } else {
  1431. $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined";
  1432. return -2;
  1433. }
  1434. }
  1435. /**
  1436. * Return clicable name (with picto eventually)
  1437. *
  1438. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1439. * @param int $max Max length of shown ref
  1440. * @param int $short 1=Return just URL
  1441. * @param string $moretitle Add more text to title tooltip
  1442. * @param int $notooltip 1=Disable tooltip
  1443. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1444. * @return string String with URL
  1445. */
  1446. public function getNomUrl($withpicto = 0, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
  1447. {
  1448. global $langs, $conf;
  1449. $result = '';
  1450. $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id;
  1451. if ($short) return $url;
  1452. $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ExpenseReport").'</u>';
  1453. if (isset($this->status)) {
  1454. $label .= ' '.$this->getLibStatut(5);
  1455. }
  1456. if (!empty($this->ref))
  1457. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1458. if (!empty($this->total_ht))
  1459. $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  1460. if (!empty($this->total_tva))
  1461. $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  1462. if (!empty($this->total_ttc))
  1463. $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  1464. if ($moretitle) $label .= ' - '.$moretitle;
  1465. //if ($option != 'nolink')
  1466. //{
  1467. // Add param to save lastsearch_values or not
  1468. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1469. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
  1470. if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
  1471. //}
  1472. $ref = $this->ref;
  1473. if (empty($ref)) $ref = $this->id;
  1474. $linkclose = '';
  1475. if (empty($notooltip))
  1476. {
  1477. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1478. {
  1479. $label = $langs->trans("ShowExpenseReport");
  1480. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1481. }
  1482. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1483. $linkclose .= ' class="classfortooltip"';
  1484. }
  1485. $linkstart = '<a href="'.$url.'"';
  1486. $linkstart .= $linkclose.'>';
  1487. $linkend = '</a>';
  1488. $result .= $linkstart;
  1489. if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1490. if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref);
  1491. $result .= $linkend;
  1492. return $result;
  1493. }
  1494. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1495. /**
  1496. * Update total of an expense report when you add a line.
  1497. *
  1498. * @param string $ligne_total_ht Amount without taxes
  1499. * @param string $ligne_total_tva Amount of all taxes
  1500. * @return void
  1501. */
  1502. public function update_totaux_add($ligne_total_ht, $ligne_total_tva)
  1503. {
  1504. // phpcs:enable
  1505. $this->total_ht = $this->total_ht + $ligne_total_ht;
  1506. $this->total_tva = $this->total_tva + $ligne_total_tva;
  1507. $this->total_ttc = $this->total_ht + $this->total_tva;
  1508. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
  1509. $sql .= " total_ht = ".$this->total_ht;
  1510. $sql .= " , total_ttc = ".$this->total_ttc;
  1511. $sql .= " , total_tva = ".$this->total_tva;
  1512. $sql .= " WHERE rowid = ".$this->id;
  1513. $result = $this->db->query($sql);
  1514. if ($result):
  1515. return 1;
  1516. else :
  1517. $this->error = $this->db->error();
  1518. return -1;
  1519. endif;
  1520. }
  1521. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1522. /**
  1523. * Update total of an expense report when you delete a line.
  1524. *
  1525. * @param string $ligne_total_ht Amount without taxes
  1526. * @param string $ligne_total_tva Amount of all taxes
  1527. * @return void
  1528. */
  1529. public function update_totaux_del($ligne_total_ht, $ligne_total_tva)
  1530. {
  1531. // phpcs:enable
  1532. $this->total_ht = $this->total_ht - $ligne_total_ht;
  1533. $this->total_tva = $this->total_tva - $ligne_total_tva;
  1534. $this->total_ttc = $this->total_ht + $this->total_tva;
  1535. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
  1536. $sql .= " total_ht = ".$this->total_ht;
  1537. $sql .= " , total_ttc = ".$this->total_ttc;
  1538. $sql .= " , total_tva = ".$this->total_tva;
  1539. $sql .= " WHERE rowid = ".$this->id;
  1540. $result = $this->db->query($sql);
  1541. if ($result):
  1542. return 1;
  1543. else :
  1544. $this->error = $this->db->error();
  1545. return -1;
  1546. endif;
  1547. }
  1548. /**
  1549. * addline
  1550. *
  1551. * @param float $qty Qty
  1552. * @param double $up Value init
  1553. * @param int $fk_c_type_fees Type payment
  1554. * @param string $vatrate Vat rate (Can be '10' or '10 (ABC)')
  1555. * @param string $date Date
  1556. * @param string $comments Description
  1557. * @param int $fk_project Project id
  1558. * @param int $fk_c_exp_tax_cat Car category id
  1559. * @param int $type Type line
  1560. * @param int $fk_ecm_files Id of ECM file to link to this expensereport line
  1561. * @return int <0 if KO, >0 if OK
  1562. */
  1563. public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0)
  1564. {
  1565. global $conf, $langs, $mysoc;
  1566. dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG);
  1567. if ($this->status == self::STATUS_DRAFT)
  1568. {
  1569. if (empty($qty)) $qty = 0;
  1570. if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) $fk_c_type_fees = 0;
  1571. if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) $fk_c_exp_tax_cat = 0;
  1572. if (empty($vatrate) || $vatrate < 0) $vatrate = 0;
  1573. if (empty($date)) $date = '';
  1574. if (empty($fk_project)) $fk_project = 0;
  1575. $qty = price2num($qty);
  1576. if (!preg_match('/\s*\((.*)\)/', $vatrate)) {
  1577. $vatrate = price2num($vatrate); // $txtva can have format '5.0 (XXX)' or '5'
  1578. }
  1579. $up = price2num($up);
  1580. $this->db->begin();
  1581. $this->line = new ExpenseReportLine($this->db);
  1582. $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty);
  1583. $vat_src_code = '';
  1584. $reg = array();
  1585. if (preg_match('/\s*\((.*)\)/', $vatrate, $reg))
  1586. {
  1587. $vat_src_code = $reg[1];
  1588. $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
  1589. }
  1590. $vatrate = preg_replace('/\*/', '', $vatrate);
  1591. $seller = ''; // seller is unknown
  1592. $tmp = calcul_price_total($qty, $up, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
  1593. $this->line->value_unit = $up;
  1594. $this->line->vat_src_code = $vat_src_code;
  1595. $this->line->vatrate = price2num($vatrate);
  1596. $this->line->total_ttc = $tmp[2];
  1597. $this->line->total_ht = $tmp[0];
  1598. $this->line->total_tva = $tmp[1];
  1599. $this->line->fk_expensereport = $this->id;
  1600. $this->line->qty = $qty;
  1601. $this->line->date = $date;
  1602. $this->line->fk_c_type_fees = $fk_c_type_fees;
  1603. $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
  1604. $this->line->comments = $comments;
  1605. $this->line->fk_projet = $fk_project; // deprecated
  1606. $this->line->fk_project = $fk_project;
  1607. $this->line->fk_ecm_files = $fk_ecm_files;
  1608. $this->applyOffset();
  1609. $this->checkRules($type, $seller);
  1610. $result = $this->line->insert(0, true);
  1611. if ($result > 0)
  1612. {
  1613. $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
  1614. if ($result > 0)
  1615. {
  1616. $this->db->commit();
  1617. return $this->line->id;
  1618. } else {
  1619. $this->db->rollback();
  1620. return -1;
  1621. }
  1622. } else {
  1623. $this->error = $this->line->error;
  1624. dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
  1625. $this->db->rollback();
  1626. return -2;
  1627. }
  1628. } else {
  1629. dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR);
  1630. $this->error = 'ErrorExpenseNotDraft';
  1631. return -3;
  1632. }
  1633. }
  1634. /**
  1635. * Check constraint of rules and update price if needed
  1636. *
  1637. * @param int $type type of line
  1638. * @param string $seller seller, but actually he is unknown
  1639. * @return true or false
  1640. */
  1641. public function checkRules($type = 0, $seller = '')
  1642. {
  1643. global $user, $conf, $db, $langs;
  1644. $langs->load('trips');
  1645. if (empty($conf->global->MAIN_USE_EXPENSE_RULE)) return true; // if don't use rules
  1646. $rulestocheck = ExpenseReportRule::getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author);
  1647. $violation = 0;
  1648. $rule_warning_message_tab = array();
  1649. $current_total_ttc = $this->line->total_ttc;
  1650. $new_current_total_ttc = $this->line->total_ttc;
  1651. // check if one is violated
  1652. foreach ($rulestocheck as $rule)
  1653. {
  1654. if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type);
  1655. else $amount_to_test = $current_total_ttc; // EX_EXP
  1656. $amount_to_test = $amount_to_test - $current_total_ttc + $new_current_total_ttc; // if amount as been modified by a previous rule
  1657. if ($amount_to_test > $rule->amount)
  1658. {
  1659. $violation++;
  1660. if ($rule->restrictive)
  1661. {
  1662. $this->error = 'ExpenseReportConstraintViolationError';
  1663. $this->errors[] = $this->error;
  1664. $new_current_total_ttc -= $amount_to_test - $rule->amount; // ex, entered 16€, limit 12€, subtracts 4€;
  1665. $rule_warning_message_tab[] = $langs->trans('ExpenseReportConstraintViolationError', $rule->id, price($amount_to_test, 0, $langs, 1, -1, -1, $conf->currency), price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency), $langs->trans('by'.$rule->code_expense_rules_type, price($new_current_total_ttc, 0, $langs, 1, -1, -1, $conf->currency)));
  1666. } else {
  1667. $this->error = 'ExpenseReportConstraintViolationWarning';
  1668. $this->errors[] = $this->error;
  1669. $rule_warning_message_tab[] = $langs->trans('ExpenseReportConstraintViolationWarning', $rule->id, price($amount_to_test, 0, $langs, 1, -1, -1, $conf->currency), price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency), $langs->trans('nolimitby'.$rule->code_expense_rules_type));
  1670. }
  1671. // No break, we sould test if another rule is violated
  1672. }
  1673. }
  1674. $this->line->rule_warning_message = implode('\n', $rule_warning_message_tab);
  1675. if ($violation > 0)
  1676. {
  1677. $tmp = calcul_price_total($this->line->qty, $new_current_total_ttc / $this->line->qty, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
  1678. $this->line->value_unit = $tmp[5];
  1679. $this->line->total_ttc = $tmp[2];
  1680. $this->line->total_ht = $tmp[0];
  1681. $this->line->total_tva = $tmp[1];
  1682. return false;
  1683. } else return true;
  1684. }
  1685. /**
  1686. * Method to apply the offset if needed
  1687. *
  1688. * @return boolean true=applied, false=not applied
  1689. */
  1690. public function applyOffset()
  1691. {
  1692. global $conf;
  1693. if (empty($conf->global->MAIN_USE_EXPENSE_IK)) return false;
  1694. $userauthor = new User($this->db);
  1695. if ($userauthor->fetch($this->fk_user_author) <= 0)
  1696. {
  1697. $this->error = 'ErrorCantFetchUser';
  1698. $this->errors[] = 'ErrorCantFetchUser';
  1699. return false;
  1700. }
  1701. $range = ExpenseReportIk::getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat);
  1702. if (empty($range))
  1703. {
  1704. $this->error = 'ErrorNoRangeAvailable';
  1705. $this->errors[] = 'ErrorNoRangeAvailable';
  1706. return false;
  1707. }
  1708. if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) $ikoffset = $range->ikoffset;
  1709. else $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year
  1710. // Test if ikoffset has been applied for the current month
  1711. if (!$this->offsetAlreadyGiven())
  1712. {
  1713. $new_up = $range->coef + ($ikoffset / $this->line->qty);
  1714. $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller);
  1715. $this->line->value_unit = $tmp[5];
  1716. $this->line->total_ttc = $tmp[2];
  1717. $this->line->total_ht = $tmp[0];
  1718. $this->line->total_tva = $tmp[1];
  1719. return true;
  1720. }
  1721. return false;
  1722. }
  1723. /**
  1724. * If the sql find any rows then the ikoffset is already given (ikoffset is applied at the first expense report line)
  1725. *
  1726. * @return bool
  1727. */
  1728. public function offsetAlreadyGiven()
  1729. {
  1730. $sql = 'SELECT e.rowid FROM '.MAIN_DB_PREFIX.'expensereport e';
  1731. $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport_det d ON (e.rowid = d.fk_expensereport)';
  1732. $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = "EX_KME")';
  1733. $sql .= ' WHERE e.fk_user_author = '.(int) $this->fk_user_author;
  1734. $sql .= ' AND YEAR(d.date) = "'.dol_print_date($this->line->date, '%Y').'" AND MONTH(d.date) = "'.dol_print_date($this->line->date, '%m').'"';
  1735. if (!empty($this->line->id)) $sql .= ' AND d.rowid <> '.$this->line->id;
  1736. dol_syslog(get_class($this)."::offsetAlreadyGiven sql=".$sql);
  1737. $resql = $this->db->query($sql);
  1738. if ($resql)
  1739. {
  1740. $num = $this->db->num_rows($resql);
  1741. if ($num > 0) return true;
  1742. } else {
  1743. dol_print_error($this->db);
  1744. }
  1745. return false;
  1746. }
  1747. /**
  1748. * Update an expense report line
  1749. *
  1750. * @param int $rowid Line to edit
  1751. * @param int $type_fees_id Type payment
  1752. * @param int $projet_id Project id
  1753. * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)'
  1754. * @param string $comments Description
  1755. * @param float $qty Qty
  1756. * @param double $value_unit Value init
  1757. * @param int $date Date
  1758. * @param int $expensereport_id Expense report id
  1759. * @param int $fk_c_exp_tax_cat Id of category of car
  1760. * @param int $fk_ecm_files Id of ECM file to link to this expensereport line
  1761. * @return int <0 if KO, >0 if OK
  1762. */
  1763. public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0)
  1764. {
  1765. global $user, $mysoc;
  1766. if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED)
  1767. {
  1768. $this->db->begin();
  1769. $type = 0; // TODO What if type is service ?
  1770. // We don't know seller and buyer for expense reports
  1771. $seller = $mysoc;
  1772. $buyer = new Societe($this->db);
  1773. $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
  1774. // Clean vat code
  1775. $reg = array();
  1776. $vat_src_code = '';
  1777. if (preg_match('/\((.*)\)/', $vatrate, $reg))
  1778. {
  1779. $vat_src_code = $reg[1];
  1780. $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
  1781. }
  1782. $vatrate = preg_replace('/\*/', '', $vatrate);
  1783. $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
  1784. // calcul total of line
  1785. //$total_ttc = price2num($qty*$value_unit, 'MT');
  1786. $tx_tva = $vatrate / 100;
  1787. $tx_tva = $tx_tva + 1;
  1788. $this->line = new ExpenseReportLine($this->db);
  1789. $this->line->comments = $comments;
  1790. $this->line->qty = $qty;
  1791. $this->line->value_unit = $value_unit;
  1792. $this->line->date = $date;
  1793. $this->line->fk_expensereport = $expensereport_id;
  1794. $this->line->fk_c_type_fees = $type_fees_id;
  1795. $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
  1796. $this->line->fk_projet = $projet_id; // deprecated
  1797. $this->line->fk_project = $projet_id;
  1798. $this->line->vat_src_code = $vat_src_code;
  1799. $this->line->vatrate = price2num($vatrate);
  1800. $this->line->total_ttc = $tmp[2];
  1801. $this->line->total_ht = $tmp[0];
  1802. $this->line->total_tva = $tmp[1];
  1803. $this->line->localtax1_tx = $localtaxes_type[1];
  1804. $this->line->localtax2_tx = $localtaxes_type[3];
  1805. $this->line->localtax1_type = $localtaxes_type[0];
  1806. $this->line->localtax2_type = $localtaxes_type[2];
  1807. $this->line->fk_ecm_files = $fk_ecm_files;
  1808. $this->line->id = $rowid;
  1809. // Select des infos sur le type fees
  1810. $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees";
  1811. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  1812. $sql .= " WHERE c.id = ".$type_fees_id;
  1813. $resql = $this->db->query($sql);
  1814. if ($resql)
  1815. {
  1816. $objp_fees = $this->db->fetch_object($resql);
  1817. $this->line->type_fees_code = $objp_fees->code_type_fees;
  1818. $this->line->type_fees_libelle = $objp_fees->libelle_type_fees;
  1819. $this->db->free($resql);
  1820. }
  1821. // Select des informations du projet
  1822. $sql = "SELECT p.ref as ref_projet, p.title as title_projet";
  1823. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  1824. $sql .= " WHERE p.rowid = ".$projet_id;
  1825. $resql = $this->db->query($sql);
  1826. if ($resql) {
  1827. $objp_projet = $this->db->fetch_object($resql);
  1828. $this->line->projet_ref = $objp_projet->ref_projet;
  1829. $this->line->projet_title = $objp_projet->title_projet;
  1830. $this->db->free($resql);
  1831. }
  1832. $this->applyOffset();
  1833. $this->checkRules();
  1834. $result = $this->line->update($user);
  1835. if ($result > 0)
  1836. {
  1837. $this->db->commit();
  1838. return 1;
  1839. } else {
  1840. $this->error = $this->line->error;
  1841. $this->errors = $this->line->errors;
  1842. $this->db->rollback();
  1843. return -2;
  1844. }
  1845. }
  1846. }
  1847. /**
  1848. * deleteline
  1849. *
  1850. * @param int $rowid Row id
  1851. * @param User $fuser User
  1852. * @return int <0 if KO, >0 if OK
  1853. */
  1854. public function deleteline($rowid, $fuser = '')
  1855. {
  1856. $this->db->begin();
  1857. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1858. $sql .= ' WHERE rowid = '.$rowid;
  1859. dol_syslog(get_class($this)."::deleteline sql=".$sql);
  1860. $result = $this->db->query($sql);
  1861. if (!$result)
  1862. {
  1863. $this->error = $this->db->error();
  1864. dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR);
  1865. $this->db->rollback();
  1866. return -1;
  1867. }
  1868. $this->db->commit();
  1869. return 1;
  1870. }
  1871. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1872. /**
  1873. * periode_existe
  1874. *
  1875. * @param User $fuser User
  1876. * @param integer $date_debut Start date
  1877. * @param integer $date_fin End date
  1878. * @return int <0 if KO, >0 if OK
  1879. */
  1880. public function periode_existe($fuser, $date_debut, $date_fin)
  1881. {
  1882. // phpcs:enable
  1883. $sql = "SELECT rowid, date_debut, date_fin";
  1884. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  1885. $sql .= " WHERE fk_user_author = '{$fuser->id}'";
  1886. dol_syslog(get_class($this)."::periode_existe sql=".$sql);
  1887. $result = $this->db->query($sql);
  1888. if ($result) {
  1889. $num_rows = $this->db->num_rows($result); $i = 0;
  1890. if ($num_rows > 0)
  1891. {
  1892. $date_d_form = $date_debut;
  1893. $date_f_form = $date_fin;
  1894. $existe = false;
  1895. while ($i < $num_rows)
  1896. {
  1897. $objp = $this->db->fetch_object($result);
  1898. $date_d_req = $this->db->jdate($objp->date_debut); // 3
  1899. $date_f_req = $this->db->jdate($objp->date_fin); // 4
  1900. if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true;
  1901. $i++;
  1902. }
  1903. if ($existe) return 1;
  1904. else return 0;
  1905. } else {
  1906. return 0;
  1907. }
  1908. } else {
  1909. $this->error = $this->db->lasterror();
  1910. dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR);
  1911. return -1;
  1912. }
  1913. }
  1914. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1915. /**
  1916. * Return list of people with permission to validate expense reports.
  1917. * Search for permission "approve expense report"
  1918. *
  1919. * @return array Array of user ids
  1920. */
  1921. public function fetch_users_approver_expensereport()
  1922. {
  1923. // phpcs:enable
  1924. $users_validator = array();
  1925. $sql = "SELECT DISTINCT ur.fk_user";
  1926. $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
  1927. $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
  1928. $sql .= "UNION";
  1929. $sql .= " SELECT DISTINCT ugu.fk_user";
  1930. $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
  1931. $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
  1932. //print $sql;
  1933. dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql);
  1934. $result = $this->db->query($sql);
  1935. if ($result)
  1936. {
  1937. $num_rows = $this->db->num_rows($result); $i = 0;
  1938. while ($i < $num_rows)
  1939. {
  1940. $objp = $this->db->fetch_object($result);
  1941. array_push($users_validator, $objp->fk_user);
  1942. $i++;
  1943. }
  1944. return $users_validator;
  1945. } else {
  1946. $this->error = $this->db->lasterror();
  1947. dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR);
  1948. return -1;
  1949. }
  1950. }
  1951. /**
  1952. * Create a document onto disk accordign to template module.
  1953. *
  1954. * @param string $modele Force le mnodele a utiliser ('' to not force)
  1955. * @param Translate $outputlangs objet lang a utiliser pour traduction
  1956. * @param int $hidedetails Hide details of lines
  1957. * @param int $hidedesc Hide description
  1958. * @param int $hideref Hide ref
  1959. * @param null|array $moreparams Array to provide more information
  1960. * @return int 0 if KO, 1 if OK
  1961. */
  1962. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  1963. {
  1964. global $conf;
  1965. $outputlangs->load("trips");
  1966. if (!dol_strlen($modele)) {
  1967. if (!empty($this->model_pdf)) {
  1968. $modele = $this->model_pdf;
  1969. } elseif (!empty($this->modelpdf)) { // deprecated
  1970. $modele = $this->modelpdf;
  1971. } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) {
  1972. $modele = $conf->global->EXPENSEREPORT_ADDON_PDF;
  1973. }
  1974. }
  1975. if (!empty($modele)) {
  1976. $modelpath = "core/modules/expensereport/doc/";
  1977. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1978. } else {
  1979. return 0;
  1980. }
  1981. }
  1982. /**
  1983. * List of types
  1984. *
  1985. * @param int $active Active or not
  1986. * @return array
  1987. */
  1988. public function listOfTypes($active = 1)
  1989. {
  1990. global $langs;
  1991. $ret = array();
  1992. $sql = "SELECT id, code, label";
  1993. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees";
  1994. $sql .= " WHERE active = ".$active;
  1995. dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG);
  1996. $result = $this->db->query($sql);
  1997. if ($result)
  1998. {
  1999. $num = $this->db->num_rows($result);
  2000. $i = 0;
  2001. while ($i < $num)
  2002. {
  2003. $obj = $this->db->fetch_object($result);
  2004. $ret[$obj->code] = (($langs->trans($obj->code) != $obj->code) ? $langs->trans($obj->code) : $obj->label);
  2005. $i++;
  2006. }
  2007. } else {
  2008. dol_print_error($this->db);
  2009. }
  2010. return $ret;
  2011. }
  2012. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2013. /**
  2014. * Charge indicateurs this->nb pour le tableau de bord
  2015. *
  2016. * @return int <0 if KO, >0 if OK
  2017. */
  2018. public function load_state_board()
  2019. {
  2020. // phpcs:enable
  2021. global $conf, $user;
  2022. $this->nb = array();
  2023. $sql = "SELECT count(ex.rowid) as nb";
  2024. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
  2025. $sql .= " WHERE ex.fk_statut > 0";
  2026. $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
  2027. if (empty($user->rights->expensereport->readall))
  2028. {
  2029. $userchildids = $user->getAllChildIds(1);
  2030. $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")";
  2031. $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))";
  2032. }
  2033. $resql = $this->db->query($sql);
  2034. if ($resql) {
  2035. while ($obj = $this->db->fetch_object($resql)) {
  2036. $this->nb["expensereports"] = $obj->nb;
  2037. }
  2038. $this->db->free($resql);
  2039. return 1;
  2040. } else {
  2041. dol_print_error($this->db);
  2042. $this->error = $this->db->error();
  2043. return -1;
  2044. }
  2045. }
  2046. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2047. /**
  2048. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2049. *
  2050. * @param User $user Objet user
  2051. * @param string $option 'topay' or 'toapprove'
  2052. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  2053. */
  2054. public function load_board($user, $option = 'topay')
  2055. {
  2056. // phpcs:enable
  2057. global $conf, $langs;
  2058. if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe
  2059. $now = dol_now();
  2060. $sql = "SELECT ex.rowid, ex.date_valid";
  2061. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
  2062. if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED;
  2063. else $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED;
  2064. $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
  2065. if (empty($user->rights->expensereport->readall))
  2066. {
  2067. $userchildids = $user->getAllChildIds(1);
  2068. $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")";
  2069. $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))";
  2070. }
  2071. $resql = $this->db->query($sql);
  2072. if ($resql)
  2073. {
  2074. $langs->load("trips");
  2075. $response = new WorkboardResponse();
  2076. if ($option == 'toapprove')
  2077. {
  2078. $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24;
  2079. $response->label = $langs->trans("ExpenseReportsToApprove");
  2080. $response->labelShort = $langs->trans("ToApprove");
  2081. $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_VALIDATED;
  2082. } else {
  2083. $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24;
  2084. $response->label = $langs->trans("ExpenseReportsToPay");
  2085. $response->labelShort = $langs->trans("StatusToPay");
  2086. $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&amp;statut='.self::STATUS_APPROVED;
  2087. }
  2088. $response->img = img_object('', "trip");
  2089. while ($obj = $this->db->fetch_object($resql))
  2090. {
  2091. $response->nbtodo++;
  2092. if ($option == 'toapprove')
  2093. {
  2094. if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) {
  2095. $response->nbtodolate++;
  2096. }
  2097. } else {
  2098. if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) {
  2099. $response->nbtodolate++;
  2100. }
  2101. }
  2102. }
  2103. return $response;
  2104. } else {
  2105. dol_print_error($this->db);
  2106. $this->error = $this->db->error();
  2107. return -1;
  2108. }
  2109. }
  2110. /**
  2111. * Return if an expense report is late or not
  2112. *
  2113. * @param string $option 'topay' or 'toapprove'
  2114. * @return boolean True if late, False if not late
  2115. */
  2116. public function hasDelay($option)
  2117. {
  2118. global $conf;
  2119. // Only valid expenses reports
  2120. if ($option == 'toapprove' && $this->status != 2) return false;
  2121. if ($option == 'topay' && $this->status != 5) return false;
  2122. $now = dol_now();
  2123. if ($option == 'toapprove')
  2124. {
  2125. return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay);
  2126. } else return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay);
  2127. }
  2128. /**
  2129. * Return if an expensereport was dispatched into bookkeeping
  2130. *
  2131. * @return int <0 if KO, 0=no, 1=yes
  2132. */
  2133. public function getVentilExportCompta()
  2134. {
  2135. $alreadydispatched = 0;
  2136. $type = 'expense_report';
  2137. $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".$this->id;
  2138. $resql = $this->db->query($sql);
  2139. if ($resql)
  2140. {
  2141. $obj = $this->db->fetch_object($resql);
  2142. if ($obj)
  2143. {
  2144. $alreadydispatched = $obj->nb;
  2145. }
  2146. } else {
  2147. $this->error = $this->db->lasterror();
  2148. return -1;
  2149. }
  2150. if ($alreadydispatched)
  2151. {
  2152. return 1;
  2153. }
  2154. return 0;
  2155. }
  2156. /**
  2157. * Return amount of payments already done
  2158. *
  2159. * @return int Amount of payment already done, <0 if KO
  2160. */
  2161. public function getSumPayments()
  2162. {
  2163. $table = 'payment_expensereport';
  2164. $field = 'fk_expensereport';
  2165. $sql = 'SELECT sum(amount) as amount';
  2166. $sql .= ' FROM '.MAIN_DB_PREFIX.$table;
  2167. $sql .= ' WHERE '.$field.' = '.$this->id;
  2168. dol_syslog(get_class($this)."::getSumPayments", LOG_DEBUG);
  2169. $resql = $this->db->query($sql);
  2170. if ($resql)
  2171. {
  2172. $obj = $this->db->fetch_object($resql);
  2173. $this->db->free($resql);
  2174. return (empty($obj->amount) ? 0 : $obj->amount);
  2175. } else {
  2176. $this->error = $this->db->lasterror();
  2177. return -1;
  2178. }
  2179. }
  2180. }
  2181. /**
  2182. * Class of expense report details lines
  2183. */
  2184. class ExpenseReportLine
  2185. {
  2186. /**
  2187. * @var DoliDB Database handler.
  2188. */
  2189. public $db;
  2190. /**
  2191. * @var string Error code (or message)
  2192. */
  2193. public $error = '';
  2194. /**
  2195. * @var int ID
  2196. */
  2197. public $rowid;
  2198. public $comments;
  2199. public $qty;
  2200. public $value_unit;
  2201. public $date;
  2202. /**
  2203. * @var int ID
  2204. */
  2205. public $fk_c_type_fees;
  2206. /**
  2207. * @var int ID
  2208. */
  2209. public $fk_c_exp_tax_cat;
  2210. /**
  2211. * @var int ID
  2212. */
  2213. public $fk_projet;
  2214. /**
  2215. * @var int ID
  2216. */
  2217. public $fk_expensereport;
  2218. public $type_fees_code;
  2219. public $type_fees_libelle;
  2220. public $projet_ref;
  2221. public $projet_title;
  2222. public $vatrate;
  2223. public $total_ht;
  2224. public $total_tva;
  2225. public $total_ttc;
  2226. /**
  2227. * @var int ID into llx_ecm_files table to link line to attached file
  2228. */
  2229. public $fk_ecm_files;
  2230. /**
  2231. * Constructor
  2232. *
  2233. * @param DoliDB $db Handlet database
  2234. */
  2235. public function __construct($db)
  2236. {
  2237. $this->db = $db;
  2238. }
  2239. /**
  2240. * Fetch record for expense report detailed line
  2241. *
  2242. * @param int $rowid Id of object to load
  2243. * @return int <0 if KO, >0 if OK
  2244. */
  2245. public function fetch($rowid)
  2246. {
  2247. $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,';
  2248. $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,';
  2249. $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,';
  2250. $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref';
  2251. $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde';
  2252. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here.
  2253. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid';
  2254. $sql .= ' WHERE fde.rowid = '.$rowid;
  2255. $result = $this->db->query($sql);
  2256. if ($result)
  2257. {
  2258. $objp = $this->db->fetch_object($result);
  2259. $this->rowid = $objp->rowid;
  2260. $this->id = $objp->rowid;
  2261. $this->ref = $objp->ref;
  2262. $this->fk_expensereport = $objp->fk_expensereport;
  2263. $this->comments = $objp->comments;
  2264. $this->qty = $objp->qty;
  2265. $this->date = $objp->date;
  2266. $this->dates = $this->db->jdate($objp->date);
  2267. $this->value_unit = $objp->value_unit;
  2268. $this->fk_c_type_fees = $objp->fk_c_type_fees;
  2269. $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
  2270. $this->fk_projet = $objp->fk_project; // deprecated
  2271. $this->fk_project = $objp->fk_project;
  2272. $this->type_fees_code = $objp->type_fees_code;
  2273. $this->type_fees_libelle = $objp->type_fees_libelle;
  2274. $this->projet_ref = $objp->projet_ref;
  2275. $this->projet_title = $objp->projet_title;
  2276. $this->vatrate = $objp->vatrate;
  2277. $this->vat_src_code = $objp->vat_src_code;
  2278. $this->total_ht = $objp->total_ht;
  2279. $this->total_tva = $objp->total_tva;
  2280. $this->total_ttc = $objp->total_ttc;
  2281. $this->fk_ecm_files = $objp->fk_ecm_files;
  2282. $this->db->free($result);
  2283. } else {
  2284. dol_print_error($this->db);
  2285. }
  2286. }
  2287. /**
  2288. * Insert a line of expense report
  2289. *
  2290. * @param int $notrigger 1=No trigger
  2291. * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object
  2292. * @return int <0 if KO, >0 if OK
  2293. */
  2294. public function insert($notrigger = 0, $fromaddline = false)
  2295. {
  2296. global $langs, $user, $conf;
  2297. $error = 0;
  2298. dol_syslog("ExpenseReportLine::Insert", LOG_DEBUG);
  2299. // Clean parameters
  2300. $this->comments = trim($this->comments);
  2301. if (empty($this->value_unit)) $this->value_unit = 0;
  2302. $this->qty = price2num($this->qty);
  2303. $this->vatrate = price2num($this->vatrate);
  2304. if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0;
  2305. $this->db->begin();
  2306. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det';
  2307. $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,';
  2308. $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)';
  2309. $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).",";
  2310. $sql .= " ".$this->db->escape($this->fk_c_type_fees).",";
  2311. $sql .= " ".$this->db->escape((!empty($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : ((!empty($this->fk_projet) && $this->fk_projet > 0) ? $this->fk_projet : 'null')).",";
  2312. $sql .= " ".$this->db->escape($this->vatrate).",";
  2313. $sql .= " '".$this->db->escape(empty($this->vat_src_code) ? '' : $this->vat_src_code)."',";
  2314. $sql .= " '".$this->db->escape($this->comments)."',";
  2315. $sql .= " ".$this->db->escape($this->qty).",";
  2316. $sql .= " ".$this->db->escape($this->value_unit).",";
  2317. $sql .= " ".$this->db->escape($this->total_ht).",";
  2318. $sql .= " ".$this->db->escape($this->total_tva).",";
  2319. $sql .= " ".$this->db->escape($this->total_ttc).",";
  2320. $sql .= " '".$this->db->idate($this->date)."',";
  2321. $sql .= " ".(empty($this->rule_warning_message) ? 'null' : "'".$this->db->escape($this->rule_warning_message)."'").",";
  2322. $sql .= " ".$this->db->escape($this->fk_c_exp_tax_cat).",";
  2323. $sql .= " ".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null');
  2324. $sql .= ")";
  2325. $resql = $this->db->query($sql);
  2326. if ($resql)
  2327. {
  2328. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det');
  2329. if (!$fromaddline)
  2330. {
  2331. $tmpparent = new ExpenseReport($this->db);
  2332. $tmpparent->fetch($this->fk_expensereport);
  2333. $result = $tmpparent->update_price();
  2334. if ($result < 0)
  2335. {
  2336. $error++;
  2337. $this->error = $tmpparent->error;
  2338. $this->errors = $tmpparent->errors;
  2339. }
  2340. }
  2341. } else {
  2342. $error++;
  2343. }
  2344. if (!$error)
  2345. {
  2346. $this->db->commit();
  2347. return $this->id;
  2348. } else {
  2349. $this->error = $this->db->lasterror();
  2350. dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR);
  2351. $this->db->rollback();
  2352. return -2;
  2353. }
  2354. }
  2355. /**
  2356. * Function to get total amount in expense reports for a same rule
  2357. *
  2358. * @param ExpenseReportRule $rule object rule to check
  2359. * @param int $fk_user user author id
  2360. * @param string $mode day|EX_DAY / month|EX_MON / year|EX_YEA to get amount
  2361. * @return float Amount
  2362. */
  2363. public function getExpAmount(ExpenseReportRule $rule, $fk_user, $mode = 'day')
  2364. {
  2365. $amount = 0;
  2366. $sql = 'SELECT SUM(d.total_ttc) as total_amount';
  2367. $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det d';
  2368. $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport e ON (d.fk_expensereport = e.rowid)';
  2369. $sql .= ' WHERE e.fk_user_author = '.$fk_user;
  2370. if (!empty($this->id)) $sql .= ' AND d.rowid <> '.$this->id;
  2371. $sql .= ' AND d.fk_c_type_fees = '.$rule->fk_c_type_fees;
  2372. if ($mode == 'day' || $mode == 'EX_DAY') $sql .= ' AND d.date = \''.dol_print_date($this->date, '%Y-%m-%d').'\'';
  2373. elseif ($mode == 'mon' || $mode == 'EX_MON') $sql .= ' AND DATE_FORMAT(d.date, \'%Y-%m\') = \''.dol_print_date($this->date, '%Y-%m').'\''; // @todo DATE_FORMAT is forbidden
  2374. elseif ($mode == 'year' || $mode == 'EX_YEA') $sql .= ' AND DATE_FORMAT(d.date, \'%Y\') = \''.dol_print_date($this->date, '%Y').'\''; // @todo DATE_FORMAT is forbidden
  2375. dol_syslog('ExpenseReportLine::getExpAmount');
  2376. $resql = $this->db->query($sql);
  2377. if ($resql)
  2378. {
  2379. $num = $this->db->num_rows($resql);
  2380. if ($num > 0)
  2381. {
  2382. $obj = $this->db->fetch_object($resql);
  2383. $amount = (double) $obj->total_amount;
  2384. }
  2385. } else {
  2386. dol_print_error($this->db);
  2387. }
  2388. return $amount + $this->total_ttc;
  2389. }
  2390. /**
  2391. * Update line
  2392. *
  2393. * @param User $user User
  2394. * @return int <0 if KO, >0 if OK
  2395. */
  2396. public function update(User $user)
  2397. {
  2398. global $langs, $conf;
  2399. $error = 0;
  2400. // Clean parameters
  2401. $this->comments = trim($this->comments);
  2402. $this->vatrate = price2num($this->vatrate);
  2403. $this->value_unit = price2num($this->value_unit);
  2404. if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0;
  2405. $this->db->begin();
  2406. // Update line in database
  2407. $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET";
  2408. $sql .= " comments='".$this->db->escape($this->comments)."'";
  2409. $sql .= ",value_unit=".$this->db->escape($this->value_unit);
  2410. $sql .= ",qty=".$this->db->escape($this->qty);
  2411. $sql .= ",date='".$this->db->idate($this->date)."'";
  2412. $sql .= ",total_ht=".$this->db->escape($this->total_ht)."";
  2413. $sql .= ",total_tva=".$this->db->escape($this->total_tva)."";
  2414. $sql .= ",total_ttc=".$this->db->escape($this->total_ttc)."";
  2415. $sql .= ",tva_tx=".$this->db->escape($this->vatrate);
  2416. $sql .= ",vat_src_code='".$this->db->escape($this->vat_src_code)."'";
  2417. $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'";
  2418. $sql .= ",fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat);
  2419. $sql .= ",fk_ecm_files=".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null');
  2420. if ($this->fk_c_type_fees) $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees);
  2421. else $sql .= ",fk_c_type_fees=null";
  2422. if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project);
  2423. else $sql .= ",fk_projet=null";
  2424. $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id);
  2425. dol_syslog("ExpenseReportLine::update sql=".$sql);
  2426. $resql = $this->db->query($sql);
  2427. if ($resql)
  2428. {
  2429. $tmpparent = new ExpenseReport($this->db);
  2430. $result = $tmpparent->fetch($this->fk_expensereport);
  2431. if ($result > 0)
  2432. {
  2433. $result = $tmpparent->update_price();
  2434. if ($result < 0)
  2435. {
  2436. $error++;
  2437. $this->error = $tmpparent->error;
  2438. $this->errors = $tmpparent->errors;
  2439. }
  2440. } else {
  2441. $error++;
  2442. $this->error = $tmpparent->error;
  2443. $this->errors = $tmpparent->errors;
  2444. }
  2445. } else {
  2446. $error++;
  2447. dol_print_error($this->db);
  2448. }
  2449. if (!$error)
  2450. {
  2451. $this->db->commit();
  2452. return 1;
  2453. } else {
  2454. $this->error = $this->db->lasterror();
  2455. dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR);
  2456. $this->db->rollback();
  2457. return -2;
  2458. }
  2459. }
  2460. }