fournisseur.facture.class.php 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  1. <?php
  2. /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  5. * Copyright (C) 2005 Marc Barilley <marc@ocebo.com>
  6. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
  7. * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2013 Philippe Grand <philippe.grand@atoo-net.com>
  9. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  10. * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2015 Bahfir Abbes <bafbes@gmail.com>
  12. * Copyright (C) 2015 Ferran Marcet <fmarcet@2byte.es>
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  26. */
  27. /**
  28. * \file htdocs/fourn/class/fournisseur.facture.class.php
  29. * \ingroup fournisseur,facture
  30. * \brief File of class to manage suppliers invoices
  31. */
  32. include_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
  33. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  34. /**
  35. * Class to manage suppliers invoices
  36. */
  37. class FactureFournisseur extends CommonInvoice
  38. {
  39. public $element='invoice_supplier';
  40. public $table_element='facture_fourn';
  41. public $table_element_line='facture_fourn_det';
  42. public $fk_element='fk_facture_fourn';
  43. protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  44. /**
  45. * {@inheritdoc}
  46. */
  47. protected $table_ref_field = 'ref';
  48. var $rowid;
  49. var $ref;
  50. var $product_ref;
  51. var $ref_supplier;
  52. var $socid;
  53. //Check constants for types
  54. var $type = self::TYPE_STANDARD;
  55. /**
  56. * Supplier invoice status
  57. * @var int
  58. * @see FactureFournisseur::STATUS_DRAFT, FactureFournisseur::STATUS_VALIDATED, FactureFournisseur::STATUS_PAID, FactureFournisseur::STATUS_ABANDONED
  59. */
  60. var $statut;
  61. /**
  62. * Set to 1 if the invoice is completely paid, otherwise is 0
  63. * @var int
  64. * @deprecated Use statuses stored in self::statut
  65. */
  66. var $paye;
  67. var $author;
  68. var $libelle;
  69. var $datec; // Creation date
  70. var $tms; // Last update date
  71. var $date; // Invoice date
  72. var $date_echeance; // Max payment date
  73. var $amount;
  74. var $remise;
  75. var $tva;
  76. var $localtax1;
  77. var $localtax2;
  78. var $total_ht;
  79. var $total_tva;
  80. var $total_localtax1;
  81. var $total_localtax2;
  82. var $total_ttc;
  83. /**
  84. * @deprecated
  85. * @see note_private, note_public
  86. */
  87. var $note;
  88. var $note_private;
  89. var $note_public;
  90. var $propalid;
  91. var $cond_reglement_id;
  92. var $cond_reglement_code;
  93. var $fk_account;
  94. var $mode_reglement_id;
  95. var $mode_reglement_code;
  96. /**
  97. * Invoice lines
  98. * @var SupplierInvoiceLine[]
  99. */
  100. public $lines = array();
  101. /**
  102. * @deprecated
  103. */
  104. var $fournisseur;
  105. //Incorterms
  106. var $fk_incoterms;
  107. var $location_incoterms;
  108. var $libelle_incoterms; //Used into tooltip
  109. var $extraparams=array();
  110. // Multicurrency
  111. var $fk_multicurrency;
  112. var $multicurrency_code;
  113. var $multicurrency_tx;
  114. var $multicurrency_total_ht;
  115. var $multicurrency_total_tva;
  116. var $multicurrency_total_ttc;
  117. /**
  118. * Constructor
  119. *
  120. * @param DoliDB $db Database handler
  121. */
  122. function __construct($db)
  123. {
  124. $this->db = $db;
  125. $this->amount = 0;
  126. $this->remise = 0;
  127. $this->tva = 0;
  128. $this->total_localtax1 = 0;
  129. $this->total_localtax2 = 0;
  130. $this->total_ht = 0;
  131. $this->total_tva = 0;
  132. $this->total_ttc = 0;
  133. $this->propalid = 0;
  134. $this->products = array();
  135. }
  136. /**
  137. * Create supplier invoice into database
  138. *
  139. * @param User $user object utilisateur qui cree
  140. * @return int id facture si ok, < 0 si erreur
  141. */
  142. function create($user)
  143. {
  144. global $langs,$conf,$hookmanager;
  145. $error=0;
  146. $now=dol_now();
  147. // Clean parameters
  148. if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
  149. if (empty($this->date)) $this->date=$now;
  150. $socid = $this->socid;
  151. $ref_supplier = $this->ref_supplier;
  152. $amount = $this->amount;
  153. $remise = $this->remise;
  154. // Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate)
  155. if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code);
  156. else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  157. if (empty($this->fk_multicurrency))
  158. {
  159. $this->multicurrency_code = $conf->currency;
  160. $this->fk_multicurrency = 0;
  161. $this->multicurrency_tx = 1;
  162. }
  163. $this->db->begin();
  164. if (! $remise) $remise = 0 ;
  165. $totalht = ($amount - $remise);
  166. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
  167. $sql.= "ref";
  168. $sql.= ", ref_supplier";
  169. $sql.= ", entity";
  170. $sql.= ", libelle";
  171. $sql.= ", fk_soc";
  172. $sql.= ", datec";
  173. $sql.= ", datef";
  174. $sql.= ", fk_projet";
  175. $sql.= ", fk_cond_reglement";
  176. $sql.= ", fk_mode_reglement";
  177. $sql.= ", fk_account";
  178. $sql.= ", note_private";
  179. $sql.= ", note_public";
  180. $sql.= ", fk_user_author";
  181. $sql.= ", date_lim_reglement";
  182. $sql.= ", fk_incoterms, location_incoterms";
  183. $sql.= ", fk_multicurrency";
  184. $sql.= ", multicurrency_code";
  185. $sql.= ", multicurrency_tx";
  186. $sql.= ")";
  187. $sql.= " VALUES (";
  188. $sql.= "'(PROV)'";
  189. $sql.= ", '".$this->db->escape($this->ref_supplier)."'";
  190. $sql.= ", ".$conf->entity;
  191. $sql.= ", '".$this->db->escape($this->libelle)."'";
  192. $sql.= ", ".$this->socid;
  193. $sql.= ", '".$this->db->idate($now)."'";
  194. $sql.= ", '".$this->db->idate($this->date)."'";
  195. $sql.= ", ".(isset($this->fk_project)?$this->fk_project:"null");
  196. $sql.= ", ".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null");
  197. $sql.= ", ".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null");
  198. $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
  199. $sql.= ", '".$this->db->escape($this->note_private)."'";
  200. $sql.= ", '".$this->db->escape($this->note_public)."'";
  201. $sql.= ", ".$user->id.",";
  202. $sql.= $this->date_echeance!=''?"'".$this->db->idate($this->date_echeance)."'":"null";
  203. $sql.= ", ".(int) $this->fk_incoterms;
  204. $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
  205. $sql.= ", ".(int) $this->fk_multicurrency;
  206. $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
  207. $sql.= ", ".(double) $this->multicurrency_tx;
  208. $sql.= ")";
  209. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  210. $resql=$this->db->query($sql);
  211. if ($resql)
  212. {
  213. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
  214. // Update ref with new one
  215. $this->ref='(PROV'.$this->id.')';
  216. $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->ref."' WHERE rowid=".$this->id;
  217. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  218. $resql=$this->db->query($sql);
  219. if (! $resql) $error++;
  220. // Add object linked
  221. if (! $error && $this->id && ! empty($this->origin) && ! empty($this->origin_id))
  222. {
  223. $ret = $this->add_object_linked();
  224. if (! $ret)
  225. {
  226. dol_print_error($this->db);
  227. $error++;
  228. }
  229. }
  230. foreach ($this->lines as $i => $val)
  231. {
  232. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
  233. $sql .= ' VALUES ('.$this->id.');';
  234. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  235. $resql_insert=$this->db->query($sql);
  236. if ($resql_insert)
  237. {
  238. $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
  239. $this->updateline(
  240. $idligne,
  241. $this->lines[$i]->description,
  242. $this->lines[$i]->pu_ht,
  243. $this->lines[$i]->tva_tx,
  244. $this->lines[$i]->localtax1_tx,
  245. $this->lines[$i]->localtax2_tx,
  246. $this->lines[$i]->qty,
  247. $this->lines[$i]->fk_product,
  248. 'HT',
  249. (! empty($this->lines[$i]->info_bits)?$this->lines[$i]->info_bits:''),
  250. $this->lines[$i]->product_type
  251. );
  252. }
  253. }
  254. // Update total price
  255. $result=$this->update_price();
  256. if ($result > 0)
  257. {
  258. $action='create';
  259. // Actions on extra fields (by external module or standard code)
  260. // TODO le hook fait double emploi avec le trigger !!
  261. $hookmanager->initHooks(array('supplierinvoicedao'));
  262. $parameters=array('socid'=>$this->id);
  263. $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  264. if (empty($reshook))
  265. {
  266. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  267. {
  268. $result=$this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found
  269. if ($result < 0)
  270. {
  271. $error++;
  272. }
  273. }
  274. }
  275. else if ($reshook < 0) $error++;
  276. if (! $error)
  277. {
  278. // Call trigger
  279. $result=$this->call_trigger('BILL_SUPPLIER_CREATE',$user);
  280. if ($result < 0) $error++;
  281. // End call triggers
  282. }
  283. if (! $error)
  284. {
  285. $this->db->commit();
  286. return $this->id;
  287. }
  288. else
  289. {
  290. $this->db->rollback();
  291. return -4;
  292. }
  293. }
  294. else
  295. {
  296. $this->error=$langs->trans('FailedToUpdatePrice');
  297. $this->db->rollback();
  298. return -3;
  299. }
  300. }
  301. else
  302. {
  303. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  304. {
  305. $this->error=$langs->trans('ErrorRefAlreadyExists');
  306. $this->db->rollback();
  307. return -1;
  308. }
  309. else
  310. {
  311. $this->error=$this->db->lasterror();
  312. $this->db->rollback();
  313. return -2;
  314. }
  315. }
  316. }
  317. /**
  318. * Load object in memory from database
  319. *
  320. * @param int $id Id supplier invoice
  321. * @param string $ref Ref supplier invoice
  322. * @return int <0 if KO, >0 if OK, 0 if not found
  323. */
  324. function fetch($id='',$ref='')
  325. {
  326. global $langs;
  327. $sql = "SELECT";
  328. $sql.= " t.rowid,";
  329. $sql.= " t.ref,";
  330. $sql.= " t.ref_supplier,";
  331. $sql.= " t.entity,";
  332. $sql.= " t.type,";
  333. $sql.= " t.fk_soc,";
  334. $sql.= " t.datec,";
  335. $sql.= " t.datef,";
  336. $sql.= " t.tms,";
  337. $sql.= " t.libelle,";
  338. $sql.= " t.paye,";
  339. $sql.= " t.amount,";
  340. $sql.= " t.remise,";
  341. $sql.= " t.close_code,";
  342. $sql.= " t.close_note,";
  343. $sql.= " t.tva,";
  344. $sql.= " t.localtax1,";
  345. $sql.= " t.localtax2,";
  346. $sql.= " t.total,";
  347. $sql.= " t.total_ht,";
  348. $sql.= " t.total_tva,";
  349. $sql.= " t.total_ttc,";
  350. $sql.= " t.fk_statut,";
  351. $sql.= " t.fk_user_author,";
  352. $sql.= " t.fk_user_valid,";
  353. $sql.= " t.fk_facture_source,";
  354. $sql.= " t.fk_projet,";
  355. $sql.= " t.fk_cond_reglement,";
  356. $sql.= " t.fk_account,";
  357. $sql.= " t.fk_mode_reglement,";
  358. $sql.= " t.date_lim_reglement,";
  359. $sql.= " t.note_private,";
  360. $sql.= " t.note_public,";
  361. $sql.= " t.model_pdf,";
  362. $sql.= " t.import_key,";
  363. $sql.= " t.extraparams,";
  364. $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
  365. $sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle,";
  366. $sql.= ' s.nom as socnom, s.rowid as socid,';
  367. $sql.= ' t.fk_incoterms, t.location_incoterms,';
  368. $sql.= " i.libelle as libelle_incoterms,";
  369. $sql.= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
  370. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
  371. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
  372. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (t.fk_cond_reglement = cr.rowid)";
  373. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (t.fk_mode_reglement = p.id)";
  374. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
  375. if ($id) $sql.= " WHERE t.rowid=".$id;
  376. if ($ref) $sql.= " WHERE t.ref='".$this->db->escape($ref)."'";
  377. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  378. $resql=$this->db->query($sql);
  379. if ($resql)
  380. {
  381. if ($this->db->num_rows($resql))
  382. {
  383. $obj = $this->db->fetch_object($resql);
  384. $this->id = $obj->rowid;
  385. $this->ref = $obj->ref?$obj->ref:$obj->rowid; // We take rowid if ref is empty for backward compatibility
  386. $this->ref_supplier = $obj->ref_supplier;
  387. $this->entity = $obj->entity;
  388. $this->type = empty($obj->type)? self::TYPE_STANDARD:$obj->type;
  389. $this->fk_soc = $obj->fk_soc;
  390. $this->datec = $this->db->jdate($obj->datec);
  391. $this->date = $this->db->jdate($obj->datef);
  392. $this->datep = $this->db->jdate($obj->datef);
  393. $this->tms = $this->db->jdate($obj->tms);
  394. $this->libelle = $obj->libelle;
  395. $this->label = $obj->libelle;
  396. $this->paye = $obj->paye;
  397. $this->amount = $obj->amount;
  398. $this->remise = $obj->remise;
  399. $this->close_code = $obj->close_code;
  400. $this->close_note = $obj->close_note;
  401. $this->tva = $obj->tva;
  402. $this->total_localtax1 = $obj->localtax1;
  403. $this->total_localtax2 = $obj->localtax2;
  404. $this->total = $obj->total;
  405. $this->total_ht = $obj->total_ht;
  406. $this->total_tva = $obj->total_tva;
  407. $this->total_ttc = $obj->total_ttc;
  408. $this->fk_statut = $obj->fk_statut;
  409. $this->statut = $obj->fk_statut;
  410. $this->fk_user_author = $obj->fk_user_author;
  411. $this->author = $obj->fk_user_author;
  412. $this->fk_user_valid = $obj->fk_user_valid;
  413. $this->fk_facture_source = $obj->fk_facture_source;
  414. $this->fk_project = $obj->fk_projet;
  415. $this->cond_reglement_id = $obj->fk_cond_reglement;
  416. $this->cond_reglement_code = $obj->cond_reglement_code;
  417. $this->cond_reglement = $obj->cond_reglement_libelle;
  418. $this->cond_reglement_doc = $obj->cond_reglement_libelle;
  419. $this->fk_account = $obj->fk_account;
  420. $this->mode_reglement_id = $obj->fk_mode_reglement;
  421. $this->mode_reglement_code = $obj->mode_reglement_code;
  422. $this->mode_reglement = $obj->mode_reglement_libelle;
  423. $this->date_echeance = $this->db->jdate($obj->date_lim_reglement);
  424. $this->note = $obj->note_private; // deprecated
  425. $this->note_private = $obj->note_private;
  426. $this->note_public = $obj->note_public;
  427. $this->model_pdf = $obj->model_pdf;
  428. $this->modelpdf = $obj->model_pdf;
  429. $this->import_key = $obj->import_key;
  430. //Incoterms
  431. $this->fk_incoterms = $obj->fk_incoterms;
  432. $this->location_incoterms = $obj->location_incoterms;
  433. $this->libelle_incoterms = $obj->libelle_incoterms;
  434. // Multicurrency
  435. $this->fk_multicurrency = $obj->fk_multicurrency;
  436. $this->multicurrency_code = $obj->multicurrency_code;
  437. $this->multicurrency_tx = $obj->multicurrency_tx;
  438. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  439. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  440. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  441. $this->extraparams = (array) json_decode($obj->extraparams, true);
  442. $this->socid = $obj->socid;
  443. $this->socnom = $obj->socnom;
  444. // Retreive all extrafield
  445. // fetch optionals attributes and labels
  446. require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
  447. $extrafields=new ExtraFields($this->db);
  448. $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
  449. $this->fetch_optionals($this->id,$extralabels);
  450. if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
  451. $result=$this->fetch_lines();
  452. if ($result < 0)
  453. {
  454. $this->error=$this->db->lasterror();
  455. return -3;
  456. }
  457. }
  458. else
  459. {
  460. $this->error='Bill with id '.$id.' not found';
  461. dol_syslog(get_class($this).'::fetch '.$this->error);
  462. return 0;
  463. }
  464. $this->db->free($resql);
  465. return 1;
  466. }
  467. else
  468. {
  469. $this->error="Error ".$this->db->lasterror();
  470. return -1;
  471. }
  472. }
  473. /**
  474. * Load this->lines
  475. *
  476. * @return int 1 si ok, < 0 si erreur
  477. */
  478. function fetch_lines()
  479. {
  480. $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.tva_tx';
  481. $sql.= ', f.localtax1_tx, f.localtax2_tx, f.total_localtax1, f.total_localtax2 ';
  482. $sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
  483. $sql.= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
  484. $sql.= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc';
  485. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
  486. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
  487. $sql.= ' WHERE fk_facture_fourn='.$this->id;
  488. $sql.= ' ORDER BY f.rang, f.rowid';
  489. dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
  490. $resql_rows = $this->db->query($sql);
  491. if ($resql_rows)
  492. {
  493. $num_rows = $this->db->num_rows($resql_rows);
  494. if ($num_rows)
  495. {
  496. $i = 0;
  497. while ($i < $num_rows)
  498. {
  499. $obj = $this->db->fetch_object($resql_rows);
  500. $line = new SupplierInvoiceLine($this->db);
  501. $line->id = $obj->rowid;
  502. $line->rowid = $obj->rowid;
  503. $line->description = $obj->description;
  504. $line->product_ref = $obj->product_ref;
  505. $line->ref = $obj->product_ref;
  506. $line->ref_supplier = $obj->ref_supplier;
  507. $line->libelle = $obj->label;
  508. $line->label = $obj->label;
  509. $line->product_desc = $obj->product_desc;
  510. $line->subprice = $obj->pu_ht;
  511. $line->pu_ht = $obj->pu_ht;
  512. $line->pu_ttc = $obj->pu_ttc;
  513. $line->tva_tx = $obj->tva_tx;
  514. $line->localtax1_tx = $obj->localtax1_tx;
  515. $line->localtax2_tx = $obj->localtax2_tx;
  516. $line->qty = $obj->qty;
  517. $line->remise_percent = $obj->remise_percent;
  518. $line->tva = $obj->total_tva;
  519. $line->total_ht = $obj->total_ht;
  520. $line->total_tva = $obj->total_tva;
  521. $line->total_localtax1 = $obj->total_localtax1;
  522. $line->total_localtax2 = $obj->total_localtax2;
  523. $line->total_ttc = $obj->total_ttc;
  524. $line->fk_product = $obj->fk_product;
  525. $line->product_type = $obj->product_type;
  526. $line->product_label = $obj->label;
  527. $line->info_bits = $obj->info_bits;
  528. $line->fk_parent_line = $obj->fk_parent_line;
  529. $line->special_code = $obj->special_code;
  530. $line->rang = $obj->rang;
  531. $line->fk_unit = $obj->fk_unit;
  532. // Multicurrency
  533. $line->fk_multicurrency = $obj->fk_multicurrency;
  534. $line->multicurrency_code = $obj->multicurrency_code;
  535. $line->multicurrency_subprice = $obj->multicurrency_subprice;
  536. $line->multicurrency_total_ht = $obj->multicurrency_total_ht;
  537. $line->multicurrency_total_tva = $obj->multicurrency_total_tva;
  538. $line->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  539. $this->lines[$i] = $line;
  540. $i++;
  541. }
  542. }
  543. $this->db->free($resql_rows);
  544. return 1;
  545. }
  546. else
  547. {
  548. $this->error=$this->db->error();
  549. return -3;
  550. }
  551. }
  552. /**
  553. * Update database
  554. *
  555. * @param User $user User that modify
  556. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  557. * @return int <0 if KO, >0 if OK
  558. */
  559. function update($user=null, $notrigger=0)
  560. {
  561. global $conf, $langs;
  562. $error=0;
  563. // Clean parameters
  564. if (isset($this->ref)) $this->ref=trim($this->ref);
  565. if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
  566. if (isset($this->entity)) $this->entity=trim($this->entity);
  567. if (isset($this->type)) $this->type=trim($this->type);
  568. if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
  569. if (isset($this->libelle)) $this->libelle=trim($this->libelle);
  570. if (isset($this->paye)) $this->paye=trim($this->paye);
  571. if (isset($this->amount)) $this->amount=trim($this->amount);
  572. if (isset($this->remise)) $this->remise=trim($this->remise);
  573. if (isset($this->close_code)) $this->close_code=trim($this->close_code);
  574. if (isset($this->close_note)) $this->close_note=trim($this->close_note);
  575. if (isset($this->tva)) $this->tva=trim($this->tva);
  576. if (isset($this->localtax1)) $this->localtax1=trim($this->localtax1);
  577. if (isset($this->localtax2)) $this->localtax2=trim($this->localtax2);
  578. if (empty($this->total)) $this->total=0;
  579. if (empty($this->total_ht)) $this->total_ht=0;
  580. if (empty($this->total_tva)) $this->total_tva=0;
  581. // if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1);
  582. // if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2);
  583. if (isset($this->total_ttc)) $this->total_ttc=trim($this->total_ttc);
  584. if (isset($this->statut)) $this->statut=(int) $this->statut;
  585. if (isset($this->author)) $this->author=trim($this->author);
  586. if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
  587. if (isset($this->fk_facture_source)) $this->fk_facture_source=trim($this->fk_facture_source);
  588. if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
  589. if (isset($this->cond_reglement_id)) $this->cond_reglement_id=trim($this->cond_reglement_id);
  590. if (isset($this->note_private)) $this->note=trim($this->note_private);
  591. if (isset($this->note_public)) $this->note_public=trim($this->note_public);
  592. if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf);
  593. if (isset($this->import_key)) $this->import_key=trim($this->import_key);
  594. // Check parameters
  595. // Put here code to add control on parameters values
  596. // Update request
  597. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
  598. $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
  599. $sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").",";
  600. $sql.= " entity=".(isset($this->entity)?$this->entity:"null").",";
  601. $sql.= " type=".(isset($this->type)?$this->type:"null").",";
  602. $sql.= " fk_soc=".(isset($this->fk_soc)?$this->fk_soc:"null").",";
  603. $sql.= " datec=".(dol_strlen($this->datec)!=0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
  604. $sql.= " datef=".(dol_strlen($this->date)!=0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
  605. if (dol_strlen($this->tms) != 0) $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
  606. $sql.= " libelle=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
  607. $sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
  608. $sql.= " amount=".(isset($this->amount)?$this->amount:"null").",";
  609. $sql.= " remise=".(isset($this->remise)?$this->remise:"null").",";
  610. $sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").",";
  611. $sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").",";
  612. $sql.= " tva=".(isset($this->tva)?$this->tva:"null").",";
  613. $sql.= " localtax1=".(isset($this->localtax1)?$this->localtax1:"null").",";
  614. $sql.= " localtax2=".(isset($this->localtax2)?$this->localtax2:"null").",";
  615. $sql.= " total=".(isset($this->total)?$this->total:"null").",";
  616. $sql.= " total_ht=".(isset($this->total_ht)?$this->total_ht:"null").",";
  617. $sql.= " total_tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
  618. $sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
  619. $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
  620. $sql.= " fk_user_author=".(isset($this->author)?$this->author:"null").",";
  621. $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
  622. $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").",";
  623. $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
  624. $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
  625. $sql.= " date_lim_reglement=".(dol_strlen($this->date_echeance)!=0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
  626. $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
  627. $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
  628. $sql.= " model_pdf=".(isset($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null").",";
  629. $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
  630. $sql.= " WHERE rowid=".$this->id;
  631. $this->db->begin();
  632. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  633. $resql = $this->db->query($sql);
  634. if (!$resql) {
  635. $error++;
  636. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  637. $this->errors[] = $langs->trans('ErrorRefAlreadyExists');
  638. } else {
  639. $this->errors[] = "Error ".$this->db->lasterror();
  640. }
  641. }
  642. if (! $error)
  643. {
  644. if (! $notrigger)
  645. {
  646. // Call trigger
  647. $result=$this->call_trigger('BILL_SUPPLIER_UPDATE',$user);
  648. if ($result < 0) $error++;
  649. // End call triggers
  650. }
  651. }
  652. // Commit or rollback
  653. if ($error)
  654. {
  655. foreach($this->errors as $errmsg)
  656. {
  657. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  658. $this->error.=($this->error?', '.$errmsg:$errmsg);
  659. }
  660. $this->db->rollback();
  661. return -1*$error;
  662. }
  663. else
  664. {
  665. $this->db->commit();
  666. return 1;
  667. }
  668. }
  669. /**
  670. * Delete invoice from database
  671. *
  672. * @param int $rowid Id of invoice to delete
  673. * @return int <0 if KO, >0 if OK
  674. */
  675. function delete($rowid)
  676. {
  677. global $user,$langs,$conf;
  678. if (! $rowid) $rowid=$this->id;
  679. dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
  680. // TODO Test if there is at least on payment. If yes, refuse to delete.
  681. $error=0;
  682. $this->db->begin();
  683. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';';
  684. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  685. $resql = $this->db->query($sql);
  686. if ($resql)
  687. {
  688. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid;
  689. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  690. $resql2 = $this->db->query($sql);
  691. if (! $resql2) {
  692. $error++;
  693. }
  694. }
  695. else {
  696. $error++;
  697. }
  698. if (! $error)
  699. {
  700. // Delete linked object
  701. $res = $this->deleteObjectLinked();
  702. if ($res < 0) $error++;
  703. }
  704. if (! $error)
  705. {
  706. // Call trigger
  707. $result=$this->call_trigger('BILL_SUPPLIER_DELETE',$user);
  708. if ($result < 0)
  709. {
  710. $this->db->rollback();
  711. return -1;
  712. }
  713. // Fin appel triggers
  714. }
  715. if (! $error)
  716. {
  717. // Delete linked object
  718. $res = $this->deleteObjectLinked();
  719. if ($res < 0) $error++;
  720. }
  721. if (! $error)
  722. {
  723. // We remove directory
  724. if ($conf->fournisseur->facture->dir_output)
  725. {
  726. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  727. $ref = dol_sanitizeFileName($this->ref);
  728. $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref;
  729. $file = $dir . "/" . $ref . ".pdf";
  730. if (file_exists($file))
  731. {
  732. if (! dol_delete_file($file,0,0,0,$this)) // For triggers
  733. {
  734. $this->error='ErrorFailToDeleteFile';
  735. $error++;
  736. }
  737. }
  738. if (file_exists($dir))
  739. {
  740. $res=@dol_delete_dir_recursive($dir);
  741. if (! $res)
  742. {
  743. $this->error='ErrorFailToDeleteDir';
  744. $error++;
  745. }
  746. }
  747. }
  748. }
  749. // Remove extrafields
  750. if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
  751. {
  752. $result=$this->deleteExtraFields();
  753. if ($result < 0)
  754. {
  755. $error++;
  756. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  757. }
  758. }
  759. if (! $error)
  760. {
  761. dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
  762. $this->db->commit();
  763. return 1;
  764. }
  765. else
  766. {
  767. $this->error=$this->db->lasterror();
  768. $this->db->rollback();
  769. return -$error;
  770. }
  771. }
  772. /**
  773. * Tag invoice as a payed invoice
  774. *
  775. * @param User $user Object user
  776. * @return int <0 si ko, >0 si ok
  777. */
  778. function set_paid($user)
  779. {
  780. global $conf,$langs;
  781. $error=0;
  782. $this->db->begin();
  783. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
  784. $sql.= ' SET paye = 1, fk_statut=2';
  785. $sql.= ' WHERE rowid = '.$this->id;
  786. dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG);
  787. $resql = $this->db->query($sql);
  788. if ($resql)
  789. {
  790. // Call trigger
  791. $result=$this->call_trigger('BILL_SUPPLIER_PAYED',$user);
  792. if ($result < 0) $error++;
  793. // End call triggers
  794. }
  795. else
  796. {
  797. $error++;
  798. $this->error=$this->db->error();
  799. dol_print_error($this->db);
  800. }
  801. if (! $error)
  802. {
  803. $this->db->commit();
  804. return 1;
  805. }
  806. else
  807. {
  808. $this->db->rollback();
  809. return -1;
  810. }
  811. }
  812. /**
  813. * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
  814. * Fonction utilisee quand un paiement prelevement est refuse,
  815. * ou quand une facture annulee et reouverte.
  816. *
  817. * @param User $user Object user that change status
  818. * @return int <0 si ok, >0 si ok
  819. */
  820. function set_unpaid($user)
  821. {
  822. global $conf,$langs;
  823. $error=0;
  824. $this->db->begin();
  825. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
  826. $sql.= ' SET paye=0, fk_statut=1, close_code=null, close_note=null';
  827. $sql.= ' WHERE rowid = '.$this->id;
  828. dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG);
  829. $resql = $this->db->query($sql);
  830. if ($resql)
  831. {
  832. // Call trigger
  833. $result=$this->call_trigger('BILL_SUPPLIER_UNPAYED',$user);
  834. if ($result < 0) $error++;
  835. // End call triggers
  836. }
  837. else
  838. {
  839. $error++;
  840. $this->error=$this->db->lasterror();
  841. dol_syslog("FactureFournisseur::set_unpaid ".$this->error);
  842. }
  843. if (! $error)
  844. {
  845. $this->db->commit();
  846. return 1;
  847. }
  848. else
  849. {
  850. $this->db->rollback();
  851. return -1;
  852. }
  853. }
  854. /**
  855. * Tag invoice as validated + call trigger BILL_VALIDATE
  856. *
  857. * @param User $user Object user that validate
  858. * @param string $force_number Reference to force on invoice
  859. * @param int $idwarehouse Id of warehouse for stock change
  860. * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers
  861. * @return int <0 if KO, =0 if nothing to do, >0 if OK
  862. */
  863. function validate($user, $force_number='', $idwarehouse=0, $notrigger=0)
  864. {
  865. global $conf,$langs;
  866. $error=0;
  867. // Protection
  868. if ($this->statut > self::STATUS_DRAFT) // This is to avoid to validate twice (avoid errors on logs and stock management)
  869. {
  870. dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
  871. return 0;
  872. }
  873. // Check parameters
  874. if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier))
  875. {
  876. $this->error=$langs->trans("ErrorFieldFormat",$langs->transnoentities("RefSupplier"));
  877. return -1;
  878. }
  879. $this->db->begin();
  880. // Define new ref
  881. if ($force_number)
  882. {
  883. $num = $force_number;
  884. }
  885. else if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
  886. {
  887. $num = $this->getNextNumRef($this->thirdparty);
  888. }
  889. else
  890. {
  891. $num = $this->ref;
  892. }
  893. $this->newref = $num;
  894. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
  895. $sql.= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id;
  896. $sql.= " WHERE rowid = ".$this->id;
  897. dol_syslog(get_class($this)."::validate", LOG_DEBUG);
  898. $resql = $this->db->query($sql);
  899. if ($resql)
  900. {
  901. // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur
  902. if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
  903. {
  904. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  905. $langs->load("agenda");
  906. $cpt=count($this->lines);
  907. for ($i = 0; $i < $cpt; $i++)
  908. {
  909. if ($this->lines[$i]->fk_product > 0)
  910. {
  911. $mouvP = new MouvementStock($this->db);
  912. $mouvP->origin = &$this;
  913. // We increase stock for product
  914. $up_ht_disc=$this->lines[$i]->pu_ht;
  915. if (! empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc=price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
  916. $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr",$num));
  917. if ($result < 0) { $error++; }
  918. }
  919. }
  920. }
  921. // Triggers call
  922. if (! $error && empty($notrigger))
  923. {
  924. // Call trigger
  925. $result=$this->call_trigger('BILL_SUPPLIER_VALIDATE',$user);
  926. if ($result < 0) $error++;
  927. // End call triggers
  928. }
  929. if (! $error)
  930. {
  931. $this->oldref = $this->ref;
  932. // Rename directory if dir was a temporary ref
  933. if (preg_match('/^[\(]?PROV/i', $this->ref))
  934. {
  935. // On renomme repertoire facture ($this->ref = ancienne ref, $num = nouvelle ref)
  936. // in order not to lose the attached files
  937. $oldref = dol_sanitizeFileName($this->ref);
  938. $newref = dol_sanitizeFileName($num);
  939. $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$oldref;
  940. $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$newref;
  941. if (file_exists($dirsource))
  942. {
  943. dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
  944. if (@rename($dirsource, $dirdest))
  945. {
  946. dol_syslog("Rename ok");
  947. // Rename docs starting with $oldref with $newref
  948. $listoffiles=dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoice_supplier').$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
  949. foreach($listoffiles as $fileentry)
  950. {
  951. $dirsource=$fileentry['name'];
  952. $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
  953. $dirsource=$fileentry['path'].'/'.$dirsource;
  954. $dirdest=$fileentry['path'].'/'.$dirdest;
  955. @rename($dirsource, $dirdest);
  956. }
  957. }
  958. }
  959. }
  960. }
  961. // Set new ref and define current statut
  962. if (! $error)
  963. {
  964. $this->ref = $num;
  965. $this->statut=self::STATUS_VALIDATED;
  966. //$this->date_validation=$now; this is stored into log table
  967. }
  968. if (! $error)
  969. {
  970. $this->db->commit();
  971. return 1;
  972. }
  973. else
  974. {
  975. $this->db->rollback();
  976. return -1;
  977. }
  978. }
  979. else
  980. {
  981. $this->error=$this->db->error();
  982. $this->db->rollback();
  983. return -1;
  984. }
  985. }
  986. /**
  987. * Set draft status
  988. *
  989. * @param User $user Object user that modify
  990. * @param int $idwarehouse Id warehouse to use for stock change.
  991. * @return int <0 if KO, >0 if OK
  992. */
  993. function set_draft($user, $idwarehouse=-1)
  994. {
  995. global $conf,$langs;
  996. $error=0;
  997. if ($this->statut == self::STATUS_DRAFT)
  998. {
  999. dol_syslog(get_class($this)."::set_draft already draft status", LOG_WARNING);
  1000. return 0;
  1001. }
  1002. $this->db->begin();
  1003. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
  1004. $sql.= " SET fk_statut = 0";
  1005. $sql.= " WHERE rowid = ".$this->id;
  1006. dol_syslog(get_class($this)."::set_draft", LOG_DEBUG);
  1007. $result=$this->db->query($sql);
  1008. if ($result)
  1009. {
  1010. // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente
  1011. if ($result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
  1012. {
  1013. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1014. $langs->load("agenda");
  1015. $cpt=count($this->lines);
  1016. for ($i = 0; $i < $cpt; $i++)
  1017. {
  1018. if ($this->lines[$i]->fk_product > 0)
  1019. {
  1020. $mouvP = new MouvementStock($this->db);
  1021. // We increase stock for product
  1022. $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
  1023. }
  1024. }
  1025. }
  1026. // Triggers call
  1027. if (! $error && empty($notrigger))
  1028. {
  1029. // Call trigger
  1030. $result=$this->call_trigger('BILL_SUPPLIER_VALIDATE',$user);
  1031. if ($result < 0) $error++;
  1032. // End call triggers
  1033. }
  1034. if ($error == 0)
  1035. {
  1036. $this->db->commit();
  1037. return 1;
  1038. }
  1039. else
  1040. {
  1041. $this->db->rollback();
  1042. return -1;
  1043. }
  1044. }
  1045. else
  1046. {
  1047. $this->error=$this->db->error();
  1048. $this->db->rollback();
  1049. return -1;
  1050. }
  1051. }
  1052. /**
  1053. * Ajoute une ligne de facture (associe a aucun produit/service predefini)
  1054. * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
  1055. * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
  1056. * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,idprod)
  1057. * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue).
  1058. *
  1059. * @param string $desc Description de la ligne
  1060. * @param double $pu Prix unitaire (HT ou TTC selon price_base_type, > 0 even for credit note)
  1061. * @param double $txtva Taux de tva force, sinon -1
  1062. * @param double $txlocaltax1 LocalTax1 Rate
  1063. * @param double $txlocaltax2 LocalTax2 Rate
  1064. * @param double $qty Quantite
  1065. * @param int $fk_product Id du produit/service predefini
  1066. * @param double $remise_percent Pourcentage de remise de la ligne
  1067. * @param date $date_start Date de debut de validite du service
  1068. * @param date $date_end Date de fin de validite du service
  1069. * @param string $ventil Code de ventilation comptable
  1070. * @param int $info_bits Bits de type de lines
  1071. * @param string $price_base_type HT ou TTC
  1072. * @param int $type Type of line (0=product, 1=service)
  1073. * @param int $rang Position of line
  1074. * @param int $notrigger Disable triggers
  1075. * @param array $array_options extrafields array
  1076. * @param string $fk_unit Code of the unit to use. Null to use the default one
  1077. * @return int >0 if OK, <0 if KO
  1078. *
  1079. * FIXME Add field ref (that should be named ref_supplier) and label into update. For example can be filled when product line created from order.
  1080. */
  1081. function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0, $rang=-1, $notrigger=false, $array_options=0, $fk_unit=null)
  1082. {
  1083. dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit", LOG_DEBUG);
  1084. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1085. // Clean parameters
  1086. if (empty($remise_percent)) $remise_percent=0;
  1087. if (empty($qty)) $qty=0;
  1088. if (empty($info_bits)) $info_bits=0;
  1089. if (empty($rang)) $rang=0;
  1090. if (empty($ventil)) $ventil=0;
  1091. if (empty($txtva)) $txtva=0;
  1092. if (empty($txlocaltax1)) $txlocaltax1=0;
  1093. if (empty($txlocaltax2)) $txlocaltax2=0;
  1094. $remise_percent=price2num($remise_percent);
  1095. $qty=price2num($qty);
  1096. $pu=price2num($pu);
  1097. $txtva=price2num($txtva);
  1098. $txlocaltax1=price2num($txlocaltax1);
  1099. $txlocaltax2=price2num($txlocaltax2);
  1100. // Check parameters
  1101. if ($type < 0) return -1;
  1102. $this->db->begin();
  1103. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)';
  1104. $sql.= ' VALUES ('.$this->id.')';
  1105. dol_syslog(get_class($this)."::addline", LOG_DEBUG);
  1106. $resql = $this->db->query($sql);
  1107. if ($resql)
  1108. {
  1109. $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
  1110. $result=$this->updateline($idligne, $desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product, $price_base_type, $info_bits, $type, $remise_percent, true, '', '', $array_options, $fk_unit);
  1111. if ($result > 0)
  1112. {
  1113. $this->rowid = $idligne;
  1114. if (! $notrigger)
  1115. {
  1116. global $conf, $langs, $user;
  1117. // Call trigger
  1118. $result=$this->call_trigger('LINEBILL_SUPPLIER_CREATE',$user);
  1119. if ($result < 0)
  1120. {
  1121. $this->db->rollback();
  1122. return -1;
  1123. }
  1124. // End call triggers
  1125. }
  1126. $this->db->commit();
  1127. return 1;
  1128. }
  1129. else
  1130. {
  1131. dol_syslog("Error after updateline error=".$this->error, LOG_ERR);
  1132. $this->db->rollback();
  1133. return -1;
  1134. }
  1135. }
  1136. else
  1137. {
  1138. $this->error=$this->db->lasterror();
  1139. $this->db->rollback();
  1140. return -2;
  1141. }
  1142. }
  1143. /**
  1144. * Update a line detail into database
  1145. *
  1146. * @param int $id Id of line invoice
  1147. * @param string $desc Description of line
  1148. * @param double $pu Prix unitaire (HT ou TTC selon price_base_type)
  1149. * @param double $vatrate VAT Rate
  1150. * @param double $txlocaltax1 LocalTax1 Rate
  1151. * @param double $txlocaltax2 LocalTax2 Rate
  1152. * @param double $qty Quantity
  1153. * @param int $idproduct Id produit
  1154. * @param double $price_base_type HT or TTC
  1155. * @param int $info_bits Miscellaneous informations of line
  1156. * @param int $type Type of line (0=product, 1=service)
  1157. * @param double $remise_percent Pourcentage de remise de la ligne
  1158. * @param int $notrigger Disable triggers
  1159. * @param timestamp $date_start Date start of service
  1160. * @param timestamp $date_end Date end of service
  1161. * @param array $array_options extrafields array
  1162. * @param string $fk_unit Code of the unit to use. Null to use the default one
  1163. * @return int <0 if KO, >0 if OK
  1164. */
  1165. function updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=false, $date_start='', $date_end='', $array_options=0, $fk_unit = null)
  1166. {
  1167. global $mysoc;
  1168. dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent,$fk_unit", LOG_DEBUG);
  1169. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1170. $pu = price2num($pu);
  1171. $qty = price2num($qty);
  1172. $remise_percent=price2num($remise_percent);
  1173. // Check parameters
  1174. if (! is_numeric($pu) || ! is_numeric($qty)) return -1;
  1175. if ($type < 0) return -1;
  1176. // Clean parameters
  1177. if (empty($vatrate)) $vatrate=0;
  1178. if (empty($txlocaltax1)) $txlocaltax1=0;
  1179. if (empty($txlocaltax2)) $txlocaltax2=0;
  1180. $txlocaltax1=price2num($txlocaltax1);
  1181. $txlocaltax2=price2num($txlocaltax2);
  1182. // Calcul du total TTC et de la TVA pour la ligne a partir de
  1183. // qty, pu, remise_percent et txtva
  1184. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1185. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1186. $localtaxes_type=getLocalTaxesFromRate($vatrate,0,$mysoc, $this->thirdparty);
  1187. $vatrate = preg_replace('/\s*\(.*\)/','',$vatrate); // Remove code into vatrate.
  1188. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx);
  1189. $total_ht = $tabprice[0];
  1190. $total_tva = $tabprice[1];
  1191. $total_ttc = $tabprice[2];
  1192. $pu_ht = $tabprice[3];
  1193. $pu_tva = $tabprice[4];
  1194. $pu_ttc = $tabprice[5];
  1195. $total_localtax1 = $tabprice[9];
  1196. $total_localtax2 = $tabprice[10];
  1197. // MultiCurrency
  1198. $multicurrency_total_ht = $tabprice[16];
  1199. $multicurrency_total_tva = $tabprice[17];
  1200. $multicurrency_total_ttc = $tabprice[18];
  1201. if (empty($info_bits)) $info_bits=0;
  1202. if ($idproduct)
  1203. {
  1204. $product=new Product($this->db);
  1205. $result=$product->fetch($idproduct);
  1206. $product_type = $product->type;
  1207. }
  1208. else
  1209. {
  1210. $product_type = $type;
  1211. }
  1212. $line = new SupplierInvoiceLine($this->db);
  1213. if ($line->fetch($id) < 1) {
  1214. return -1;
  1215. }
  1216. $line->description = $desc;
  1217. $line->subprice = $pu_ht;
  1218. $line->pu_ht = $pu_ht;
  1219. $line->pu_ttc = $pu_ttc;
  1220. $line->qty = $qty;
  1221. $line->remise_percent = $remise_percent;
  1222. $line->tva_tx = $vatrate;
  1223. $line->localtax1_tx = $txlocaltax1;
  1224. $line->localtax2_tx = $txlocaltax2;
  1225. $line->localtax1_type = $localtaxes_type[0];
  1226. $line->localtax2_type = $localtaxes_type[2];
  1227. $line->total_ht = $total_ht;
  1228. $line->total_tva = $total_tva;
  1229. $line->total_localtax1 = $total_localtax1;
  1230. $line->total_localtax2 = $total_localtax2;
  1231. $line->total_ttc = $total_ttc;
  1232. $line->fk_product = $idproduct;
  1233. $line->product_type = $product_type;
  1234. $line->info_bits = $info_bits;
  1235. $line->fk_unit = $fk_unit;
  1236. $line->array_options = $array_options;
  1237. // Multicurrency
  1238. $line->multicurrency_subprice = price2num($line->subprice * $this->multicurrency_tx);
  1239. $line->multicurrency_total_ht = $multicurrency_total_ht;
  1240. $line->multicurrency_total_tva = $multicurrency_total_tva;
  1241. $line->multicurrency_total_ttc = $multicurrency_total_ttc;
  1242. $res = $line->update($notrigger);
  1243. if ($res < 1) {
  1244. $this->errors[] = $line->error;
  1245. } else {
  1246. // Update total price into invoice record
  1247. $res = $this->update_price('','auto');
  1248. }
  1249. return $res;
  1250. }
  1251. /**
  1252. * Delete a detail line from database
  1253. *
  1254. * @param int $rowid Id of line to delete
  1255. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1256. * @return int <0 if KO, >0 if OK
  1257. */
  1258. function deleteline($rowid, $notrigger=0)
  1259. {
  1260. if (!$rowid) {
  1261. $rowid = $this->id;
  1262. }
  1263. $line = new SupplierInvoiceLine($this->db);
  1264. if ($line->fetch($rowid) < 1) {
  1265. return -1;
  1266. }
  1267. $res = $line->delete($notrigger);
  1268. if ($res < 1) {
  1269. $this->errors[] = $line->error;
  1270. } else {
  1271. $res = $this->update_price();
  1272. }
  1273. return $res;
  1274. }
  1275. /**
  1276. * Charge les informations d'ordre info dans l'objet facture
  1277. *
  1278. * @param int $id Id de la facture a charger
  1279. * @return void
  1280. */
  1281. function info($id)
  1282. {
  1283. $sql = 'SELECT c.rowid, datec, tms as datem, ';
  1284. $sql.= ' fk_user_author, fk_user_modif, fk_user_valid';
  1285. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as c';
  1286. $sql.= ' WHERE c.rowid = '.$id;
  1287. $result=$this->db->query($sql);
  1288. if ($result)
  1289. {
  1290. if ($this->db->num_rows($result))
  1291. {
  1292. $obj = $this->db->fetch_object($result);
  1293. $this->id = $obj->rowid;
  1294. if ($obj->fk_user_author)
  1295. {
  1296. $cuser = new User($this->db);
  1297. $cuser->fetch($obj->fk_user_author);
  1298. $this->user_creation = $cuser;
  1299. }
  1300. if ($obj->fk_user_valid)
  1301. {
  1302. $vuser = new User($this->db);
  1303. $vuser->fetch($obj->fk_user_valid);
  1304. $this->user_validation = $vuser;
  1305. }
  1306. if ($obj->fk_user_modif)
  1307. {
  1308. $muser = new User($this->db);
  1309. $muser->fetch($obj->fk_user_modif);
  1310. $this->user_modification = $muser;
  1311. }
  1312. $this->date_creation = $this->db->idate($obj->datec);
  1313. $this->date_modification = $this->db->idate($obj->datem);
  1314. //$this->date_validation = $obj->datev; // This field is not available. Should be store into log table and using this function should be replaced with showing content of log (like for supplier orders)
  1315. }
  1316. $this->db->free($result);
  1317. }
  1318. else
  1319. {
  1320. dol_print_error($this->db);
  1321. }
  1322. }
  1323. /**
  1324. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1325. *
  1326. * @param User $user Object user
  1327. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  1328. */
  1329. function load_board($user)
  1330. {
  1331. global $conf, $langs;
  1332. $sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut';
  1333. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff';
  1334. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1335. $sql.= ' WHERE ff.paye=0';
  1336. $sql.= ' AND ff.fk_statut > 0';
  1337. $sql.= " AND ff.entity = ".$conf->entity;
  1338. if ($user->societe_id) $sql.=' AND ff.fk_soc = '.$user->societe_id;
  1339. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
  1340. $resql=$this->db->query($sql);
  1341. if ($resql)
  1342. {
  1343. $langs->load("bills");
  1344. $now=dol_now();
  1345. $response = new WorkboardResponse();
  1346. $response->warning_delay=$conf->facture->fournisseur->warning_delay/60/60/24;
  1347. $response->label=$langs->trans("SupplierBillsToPay");
  1348. $response->url=DOL_URL_ROOT.'/fourn/facture/list.php?filtre=fac.fk_statut:1,paye:0&mainmenu=accountancy&leftmenu=suppliers_bills';
  1349. $response->img=img_object($langs->trans("Bills"),"bill");
  1350. $facturestatic = new FactureFournisseur($this->db);
  1351. while ($obj=$this->db->fetch_object($resql))
  1352. {
  1353. $response->nbtodo++;
  1354. $facturestatic->date_echeance = $this->db->jdate($obj->datefin);
  1355. $facturestatic->statut = $obj->fk_statut;
  1356. if ($facturestatic->hasDelay()) {
  1357. $response->nbtodolate++;
  1358. }
  1359. }
  1360. $this->db->free($resql);
  1361. return $response;
  1362. }
  1363. else
  1364. {
  1365. dol_print_error($this->db);
  1366. $this->error=$this->db->error();
  1367. return -1;
  1368. }
  1369. }
  1370. /**
  1371. * Return clicable name (with picto eventually)
  1372. *
  1373. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1374. * @param string $option Sur quoi pointe le lien
  1375. * @param int $max Max length of shown ref
  1376. * @return string Chaine avec URL
  1377. */
  1378. function getNomUrl($withpicto=0,$option='',$max=0)
  1379. {
  1380. global $langs;
  1381. $result='';
  1382. $label = '<u>' . $langs->trans("ShowSupplierInvoice") . '</u>';
  1383. if (! empty($this->ref))
  1384. $label .= '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
  1385. if (! empty($this->ref_supplier))
  1386. $label.= '<br><b>' . $langs->trans('RefSupplier') . ':</b> ' . $this->ref_supplier;
  1387. if (! empty($this->total_ht))
  1388. $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  1389. if (! empty($this->total_tva))
  1390. $label.= '<br><b>' . $langs->trans('VAT') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  1391. if (! empty($this->total_ttc))
  1392. $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  1393. if ($option == 'document')
  1394. {
  1395. $link = '<a href="'.DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  1396. $linkend='</a>';
  1397. }
  1398. else
  1399. {
  1400. $link = '<a href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  1401. $linkend='</a>';
  1402. }
  1403. $ref=$this->ref;
  1404. if (empty($ref)) $ref=$this->id;
  1405. if ($withpicto) $result.=($link.img_object($label, 'bill', 'class="classfortooltip"').$linkend.' ');
  1406. $result.=$link.($max?dol_trunc($ref,$max):$ref).$linkend;
  1407. return $result;
  1408. }
  1409. /**
  1410. * Return next reference of supplier invoice not already used (or last reference)
  1411. * according to numbering module defined into constant INVOICE_SUPPLIER_ADDON_NUMBER
  1412. *
  1413. * @param Societe $soc Thirdparty object
  1414. * @param string $mode 'next' for next value or 'last' for last value
  1415. * @return string free ref or last ref
  1416. */
  1417. function getNextNumRef($soc,$mode='next')
  1418. {
  1419. global $db, $langs, $conf;
  1420. $langs->load("orders");
  1421. // Clean parameters (if not defined or using deprecated value)
  1422. if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER='mod_facture_fournisseur_cactus';
  1423. $mybool=false;
  1424. $file = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER.".php";
  1425. $classname = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER;
  1426. // Include file with class
  1427. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  1428. foreach ($dirmodels as $reldir) {
  1429. $dir = dol_buildpath($reldir."core/modules/supplier_invoice/");
  1430. // Load file with numbering class (if found)
  1431. $mybool|=@include_once $dir.$file;
  1432. }
  1433. if (! $mybool)
  1434. {
  1435. dol_print_error('',"Failed to include file ".$file);
  1436. return '';
  1437. }
  1438. $obj = new $classname();
  1439. $numref = "";
  1440. $numref = $obj->getNumRef($soc,$this,$mode);
  1441. if ($numref != "")
  1442. {
  1443. return $numref;
  1444. }
  1445. else
  1446. {
  1447. //dol_print_error($db,get_class($this)."::getNextNumRef ".$obj->error);
  1448. return false;
  1449. }
  1450. }
  1451. /**
  1452. * Initialise an instance with random values.
  1453. * Used to build previews or test instances.
  1454. * id must be 0 if object instance is a specimen.
  1455. *
  1456. * @return void
  1457. */
  1458. function initAsSpecimen()
  1459. {
  1460. global $langs,$conf;
  1461. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1462. $now = dol_now();
  1463. // Load array of products prodids
  1464. $num_prods = 0;
  1465. $prodids = array();
  1466. $sql = "SELECT rowid";
  1467. $sql.= " FROM ".MAIN_DB_PREFIX."product";
  1468. $sql.= " WHERE entity IN (".getEntity('product', 1).")";
  1469. $resql = $this->db->query($sql);
  1470. if ($resql)
  1471. {
  1472. $num_prods = $this->db->num_rows($resql);
  1473. $i = 0;
  1474. while ($i < $num_prods)
  1475. {
  1476. $i++;
  1477. $row = $this->db->fetch_row($resql);
  1478. $prodids[$i] = $row[0];
  1479. }
  1480. }
  1481. // Initialise parametres
  1482. $this->id=0;
  1483. $this->ref = 'SPECIMEN';
  1484. $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN';
  1485. $this->specimen=1;
  1486. $this->socid = 1;
  1487. $this->date = $now;
  1488. $this->date_lim_reglement=$this->date+3600*24*30;
  1489. $this->cond_reglement_code = 'RECEP';
  1490. $this->mode_reglement_code = 'CHQ';
  1491. $this->note_public='This is a comment (public)';
  1492. $this->note_private='This is a comment (private)';
  1493. // Lines
  1494. $nbp = 5;
  1495. $xnbp = 0;
  1496. while ($xnbp < $nbp)
  1497. {
  1498. $line=new FactureLigne($this->db);
  1499. $line->desc=$langs->trans("Description")." ".$xnbp;
  1500. $line->qty=1;
  1501. $line->subprice=100;
  1502. $line->pu_ht=100; // the canelle template use pu_ht and not subprice
  1503. $line->price=100;
  1504. $line->tva_tx=19.6;
  1505. $line->localtax1_tx=0;
  1506. $line->localtax2_tx=0;
  1507. if ($xnbp == 2)
  1508. {
  1509. $line->total_ht=50;
  1510. $line->total_ttc=59.8;
  1511. $line->total_tva=9.8;
  1512. $line->remise_percent=50;
  1513. }
  1514. else
  1515. {
  1516. $line->total_ht=100;
  1517. $line->total_ttc=119.6;
  1518. $line->total_tva=19.6;
  1519. $line->remise_percent=0;
  1520. }
  1521. if ($num_prods > 0)
  1522. {
  1523. $prodid = mt_rand(1, $num_prods);
  1524. $line->fk_product=$prodids[$prodid];
  1525. }
  1526. $line->product_type=0;
  1527. $this->lines[$xnbp]=$line;
  1528. $this->total_ht += $line->total_ht;
  1529. $this->total_tva += $line->total_tva;
  1530. $this->total_ttc += $line->total_ttc;
  1531. $xnbp++;
  1532. }
  1533. $this->amount_ht = $xnbp*100;
  1534. $this->total_ht = $xnbp*100;
  1535. $this->total_tva = $xnbp*19.6;
  1536. $this->total_ttc = $xnbp*119.6;
  1537. }
  1538. /**
  1539. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1540. *
  1541. * @return int <0 if KO, >0 if OK
  1542. */
  1543. function load_state_board()
  1544. {
  1545. global $conf, $user;
  1546. $this->nb=array();
  1547. $clause = "WHERE";
  1548. $sql = "SELECT count(f.rowid) as nb";
  1549. $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
  1550. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
  1551. if (!$user->rights->societe->client->voir && !$user->societe_id)
  1552. {
  1553. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  1554. $sql.= " WHERE sc.fk_user = " .$user->id;
  1555. $clause = "AND";
  1556. }
  1557. $sql.= " ".$clause." f.entity = ".$conf->entity;
  1558. $resql=$this->db->query($sql);
  1559. if ($resql)
  1560. {
  1561. while ($obj=$this->db->fetch_object($resql))
  1562. {
  1563. $this->nb["supplier_invoices"]=$obj->nb;
  1564. }
  1565. $this->db->free($resql);
  1566. return 1;
  1567. }
  1568. else
  1569. {
  1570. dol_print_error($this->db);
  1571. $this->error=$this->db->error();
  1572. return -1;
  1573. }
  1574. }
  1575. /**
  1576. * Load an object from its id and create a new one in database
  1577. *
  1578. * @param int $fromid Id of object to clone
  1579. * @param int $invertdetail Reverse sign of amounts for lines
  1580. * @return int New id of clone
  1581. */
  1582. function createFromClone($fromid,$invertdetail=0)
  1583. {
  1584. global $user,$langs;
  1585. $error=0;
  1586. $object=new FactureFournisseur($this->db);
  1587. $object->context['createfromclone'] = 'createfromclone';
  1588. $this->db->begin();
  1589. // Load source object
  1590. $object->fetch($fromid);
  1591. $object->id=0;
  1592. $object->statut=self::STATUS_DRAFT;
  1593. // Clear fields
  1594. $object->ref_supplier=$langs->trans("CopyOf").' '.$object->ref_supplier;
  1595. $object->author = $user->id;
  1596. $object->user_valid = '';
  1597. $object->fk_facture_source = 0;
  1598. $object->date_creation = '';
  1599. $object->date_validation = '';
  1600. $object->date = '';
  1601. $object->date_echeance = '';
  1602. $object->ref_client = '';
  1603. $object->close_code = '';
  1604. $object->close_note = '';
  1605. // Loop on each line of new invoice
  1606. foreach($object->lines as $i => $line)
  1607. {
  1608. if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts
  1609. {
  1610. unset($object->lines[$i]);
  1611. }
  1612. }
  1613. // Create clone
  1614. $result=$object->create($user);
  1615. // Other options
  1616. if ($result < 0)
  1617. {
  1618. $this->error=$object->error;
  1619. $error++;
  1620. }
  1621. if (! $error)
  1622. {
  1623. }
  1624. unset($object->context['createfromclone']);
  1625. // End
  1626. if (! $error)
  1627. {
  1628. $this->db->commit();
  1629. return $object->id;
  1630. }
  1631. else
  1632. {
  1633. $this->db->rollback();
  1634. return -1;
  1635. }
  1636. }
  1637. /**
  1638. * Create a document onto disk according to template model.
  1639. *
  1640. * @param string $modele Force template to use ('' to not force)
  1641. * @param Translate $outputlangs Object lang a utiliser pour traduction
  1642. * @param int $hidedetails Hide details of lines
  1643. * @param int $hidedesc Hide description
  1644. * @param int $hideref Hide ref
  1645. * @return int 0 if KO, 1 if OK
  1646. */
  1647. public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
  1648. {
  1649. global $conf, $user, $langs;
  1650. $langs->load("suppliers");
  1651. // Set the model on the model name to use
  1652. if (! dol_strlen($modele))
  1653. {
  1654. if (! empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF))
  1655. {
  1656. $modele = $conf->global->INVOICE_SUPPLIER_ADDON_PDF;
  1657. }
  1658. else
  1659. {
  1660. $modele = 'canelle';
  1661. }
  1662. }
  1663. $modelpath = "core/modules/supplier_invoice/pdf/";
  1664. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1665. }
  1666. /**
  1667. * Returns the rights used for this class
  1668. * @return stdClass
  1669. */
  1670. public function getRights()
  1671. {
  1672. global $user;
  1673. return $user->rights->fournisseur->facture;
  1674. }
  1675. /**
  1676. * Function used to replace a thirdparty id with another one.
  1677. *
  1678. * @param DoliDB $db Database handler
  1679. * @param int $origin_id Old thirdparty id
  1680. * @param int $dest_id New thirdparty id
  1681. * @return bool
  1682. */
  1683. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1684. {
  1685. $tables = array(
  1686. 'facture_fourn'
  1687. );
  1688. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1689. }
  1690. /**
  1691. * Is the payment of the supplier invoice having a delay?
  1692. *
  1693. * @return bool
  1694. */
  1695. public function hasDelay()
  1696. {
  1697. global $conf;
  1698. $now = dol_now();
  1699. if (!$this->date_echeance) {
  1700. return false;
  1701. }
  1702. return ($this->statut == self::STATUS_VALIDATED) && ($this->date_echeance < ($now - $conf->facture->fournisseur->warning_delay));
  1703. }
  1704. }
  1705. /**
  1706. * Class to manage line invoices
  1707. */
  1708. class SupplierInvoiceLine extends CommonObjectLine
  1709. {
  1710. public $element='facture_fourn_det';
  1711. public $table_element='facture_fourn_det';
  1712. var $oldline;
  1713. /**
  1714. * @deprecated
  1715. * @see product_ref
  1716. */
  1717. public $ref;
  1718. /**
  1719. * Internal ref
  1720. * @var string
  1721. */
  1722. public $product_ref;
  1723. /**
  1724. * Reference product supplier
  1725. * TODO Rename field ref to ref_supplier into table llx_facture_fourn_det and llx_commande_fournisseurdet and update fields it into updateline
  1726. * @var string
  1727. */
  1728. public $ref_supplier;
  1729. /**
  1730. * @deprecated
  1731. * @see label
  1732. */
  1733. public $libelle;
  1734. /**
  1735. * Product description
  1736. * @var string
  1737. */
  1738. public $product_desc;
  1739. /**
  1740. * Unit price before taxes
  1741. * @var float
  1742. * @deprecated Use $subprice
  1743. * @see subprice
  1744. */
  1745. public $pu_ht;
  1746. public $subprice;
  1747. /**
  1748. * Unit price included taxes
  1749. * @var float
  1750. */
  1751. public $pu_ttc;
  1752. /**
  1753. * Total VAT amount
  1754. * @var float
  1755. * @deprecated Use $total_tva instead
  1756. * @see total_tva
  1757. */
  1758. public $tva;
  1759. public $total_tva;
  1760. /**
  1761. * Id of the corresponding supplier invoice
  1762. * @var int
  1763. */
  1764. var $fk_facture_fourn;
  1765. /**
  1766. * Product label
  1767. * This field may contains label of product (when invoice create from order)
  1768. * @var string
  1769. */
  1770. var $label;
  1771. /**
  1772. * Description of the line
  1773. * @var string
  1774. */
  1775. var $description;
  1776. var $skip_update_total; // Skip update price total for special lines
  1777. /**
  1778. * @var int Situation advance percentage
  1779. */
  1780. public $situation_percent;
  1781. /**
  1782. * @var int Previous situation line id reference
  1783. */
  1784. public $fk_prev_id;
  1785. public $tva_tx;
  1786. public $localtax1_tx;
  1787. public $localtax2_tx;
  1788. public $qty;
  1789. public $remise_percent;
  1790. public $total_ht;
  1791. public $total_ttc;
  1792. public $total_localtax1;
  1793. public $total_localtax2;
  1794. public $fk_product;
  1795. public $product_type;
  1796. public $product_label;
  1797. public $info_bits;
  1798. public $fk_parent_line;
  1799. public $special_code;
  1800. public $rang;
  1801. public $localtax1_type;
  1802. public $localtax2_type;
  1803. // Multicurrency
  1804. var $fk_multicurrency;
  1805. var $multicurrency_code;
  1806. var $multicurrency_subprice;
  1807. var $multicurrency_total_ht;
  1808. var $multicurrency_total_tva;
  1809. var $multicurrency_total_ttc;
  1810. /**
  1811. * Constructor
  1812. *
  1813. * @param DoliDB $db Database handler
  1814. */
  1815. function __construct($db)
  1816. {
  1817. $this->db= $db;
  1818. }
  1819. /**
  1820. * Retrieves a supplier invoice line
  1821. *
  1822. * @param int $rowid Line id
  1823. * @return int <0 KO; 0 NOT FOUND; 1 OK
  1824. */
  1825. public function fetch($rowid)
  1826. {
  1827. $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.tva_tx';
  1828. $sql.= ', f.localtax1_type, f.localtax2_type, f.localtax1_tx, f.localtax2_tx, f.total_localtax1, f.total_localtax2 ';
  1829. $sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
  1830. $sql.= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
  1831. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
  1832. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
  1833. $sql.= ' WHERE f.rowid = '.$rowid;
  1834. $sql.= ' ORDER BY f.rang, f.rowid';
  1835. $query = $this->db->query($sql);
  1836. if (!$query) {
  1837. $this->errors[] = $this->db->error();
  1838. return -1;
  1839. }
  1840. if (!$this->db->num_rows($query)) {
  1841. return 0;
  1842. }
  1843. $obj = $this->db->fetch_object($query);
  1844. $this->id = $obj->rowid;
  1845. $this->rowid = $obj->rowid;
  1846. $this->description = $obj->description;
  1847. $this->product_ref = $obj->product_ref;
  1848. $this->ref = $obj->product_ref;
  1849. $this->ref_supplier = $obj->ref_supplier;
  1850. $this->libelle = $obj->label;
  1851. $this->label = $obj->label;
  1852. $this->product_desc = $obj->product_desc;
  1853. $this->subprice = $obj->pu_ht;
  1854. $this->pu_ht = $obj->pu_ht;
  1855. $this->pu_ttc = $obj->pu_ttc;
  1856. $this->tva_tx = $obj->tva_tx;
  1857. $this->localtax1_tx = $obj->localtax1_tx;
  1858. $this->localtax2_tx = $obj->localtax2_tx;
  1859. $this->localtax1_type = $obj->localtax1_type;
  1860. $this->localtax2_type = $obj->localtax2_type;
  1861. $this->qty = $obj->qty;
  1862. $this->remise_percent = $obj->remise_percent;
  1863. $this->tva = $obj->total_tva;
  1864. $this->total_ht = $obj->total_ht;
  1865. $this->total_tva = $obj->total_tva;
  1866. $this->total_localtax1 = $obj->total_localtax1;
  1867. $this->total_localtax2 = $obj->total_localtax2;
  1868. $this->total_ttc = $obj->total_ttc;
  1869. $this->fk_product = $obj->fk_product;
  1870. $this->product_type = $obj->product_type;
  1871. $this->product_label = $obj->label;
  1872. $this->info_bits = $obj->info_bits;
  1873. $this->fk_parent_line = $obj->fk_parent_line;
  1874. $this->special_code = $obj->special_code;
  1875. $this->rang = $obj->rang;
  1876. $this->fk_unit = $obj->fk_unit;
  1877. return 1;
  1878. }
  1879. /**
  1880. * Deletes a line
  1881. *
  1882. * @param bool|int $notrigger 1=Does not execute triggers, 0= execute triggers
  1883. * @return int 0 if KO, 1 if OK
  1884. */
  1885. public function delete($notrigger = 0)
  1886. {
  1887. global $user;
  1888. dol_syslog(get_class($this)."::deleteline rowid=".$this->id, LOG_DEBUG);
  1889. $error = 0;
  1890. $this->db->begin();
  1891. if (!$notrigger) {
  1892. if ($this->call_trigger('LINEBILL_SUPPLIER_DELETE',$user) < 0) {
  1893. $error++;
  1894. }
  1895. }
  1896. if (!$error) {
  1897. // Supprime ligne
  1898. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det ';
  1899. $sql .= ' WHERE rowid = '.$this->id;
  1900. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1901. $resql = $this->db->query($sql);
  1902. if (!$resql) {
  1903. $error++;
  1904. $this->error = $this->db->lasterror();
  1905. }
  1906. }
  1907. if (! $error)
  1908. {
  1909. $this->db->commit();
  1910. return 1;
  1911. }
  1912. else
  1913. {
  1914. $this->db->rollback();
  1915. return -1;
  1916. }
  1917. }
  1918. /**
  1919. * Update a supplier invoice line
  1920. *
  1921. * @param int $notrigger Disable triggers
  1922. * @return int <0 if KO, >0 if OK
  1923. */
  1924. public function update($notrigger = 0)
  1925. {
  1926. global $conf;
  1927. $pu = price2num($this->pu_ht);
  1928. $qty = price2num($this->qty);
  1929. // Check parameters
  1930. if (! is_numeric($pu) || ! is_numeric($qty)) {
  1931. return -1;
  1932. }
  1933. if ($this->product_type < 0) {
  1934. return -1;
  1935. }
  1936. // Clean parameters
  1937. if (empty($this->tva_tx)) {
  1938. $this->tva_tx = 0;
  1939. }
  1940. if (empty($this->localtax1_tx)) {
  1941. $this->localtax1_tx = 0;
  1942. }
  1943. if (empty($this->localtax2_tx)) {
  1944. $this->localtax2_tx = 0;
  1945. }
  1946. $this->db->begin();
  1947. if (empty($this->fk_product))
  1948. {
  1949. $fk_product = "null";
  1950. } else {
  1951. $fk_product = $this->fk_product;
  1952. }
  1953. if (empty($this->fk_unit)) {
  1954. $fk_unit = "null";
  1955. } else {
  1956. $fk_unit = "'".$this->db->escape($this->fk_unit)."'";
  1957. }
  1958. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET";
  1959. $sql.= " description ='".$this->db->escape($this->description)."'";
  1960. $sql.= ", pu_ht = ".price2num($this->pu_ht);
  1961. $sql.= ", pu_ttc = ".price2num($this->pu_ttc);
  1962. $sql.= ", qty = ".price2num($this->qty);
  1963. $sql.= ", remise_percent = ".price2num($this->remise_percent);
  1964. $sql.= ", tva_tx = ".price2num($this->tva_tx);
  1965. $sql.= ", localtax1_tx = ".price2num($this->localtax1_tx);
  1966. $sql.= ", localtax2_tx = ".price2num($this->localtax2_tx);
  1967. $sql.= ", localtax1_type = '".$this->localtax1_type."'";
  1968. $sql.= ", localtax2_type = '".$this->localtax2_type."'";
  1969. $sql.= ", total_ht = ".price2num($this->total_ht);
  1970. $sql.= ", tva= ".price2num($this->total_tva);
  1971. $sql.= ", total_localtax1= ".price2num($this->total_localtax1);
  1972. $sql.= ", total_localtax2= ".price2num($this->total_localtax2);
  1973. $sql.= ", total_ttc = ".price2num($this->total_ttc);
  1974. $sql.= ", fk_product = ".$fk_product;
  1975. $sql.= ", product_type = ".$this->product_type;
  1976. $sql.= ", info_bits = ".$this->info_bits;
  1977. $sql.= ", fk_unit = ".$fk_unit;
  1978. // Multicurrency
  1979. $sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
  1980. $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
  1981. $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
  1982. $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
  1983. $sql.= " WHERE rowid = ".$this->id;
  1984. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1985. $resql = $this->db->query($sql);
  1986. if (!$resql) {
  1987. $this->db->rollback();
  1988. $this->error = $this->db->lasterror();
  1989. return -1;
  1990. }
  1991. $this->rowid = $this->id;
  1992. $error = 0;
  1993. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  1994. {
  1995. if ($this->insertExtraFields() < 0) {
  1996. $error++;
  1997. }
  1998. }
  1999. if (! $error && ! $notrigger)
  2000. {
  2001. global $langs, $user;
  2002. // Call trigger
  2003. if ($this->call_trigger('LINEBILL_SUPPLIER_UPDATE',$user) < 0) {
  2004. $this->db->rollback();
  2005. return -1;
  2006. }
  2007. // End call triggers
  2008. }
  2009. if ($error) {
  2010. $this->db->rollback();
  2011. return -1;
  2012. }
  2013. $this->db->commit();
  2014. return 1;
  2015. }
  2016. }