expensereport.class.php 90 KB

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