purchasesjournal.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. <?php
  2. /* Copyright (C) 2007-2010 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2007-2010 Jean Heimburger <jean@tiaris.info>
  4. * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
  6. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  7. * Copyright (C) 2013-2016 Olivier Geffroy <jeff@jeffinfo.com>
  8. * Copyright (C) 2013-2016 Florian Henry <florian.henry@open-concept.pro>
  9. * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
  10. * Copyright (C) 2018 Eric Seigne <eric.seigne@cap-rel.fr>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/accountancy/journal/purchasesjournal.php
  27. * \ingroup Accountancy (Double entries)
  28. * \brief Page with purchases journal
  29. */
  30. require '../../main.inc.php';
  31. require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
  32. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  33. require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  34. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
  39. // Load translation files required by the page
  40. $langs->loadLangs(array("commercial", "compta", "bills", "other", "accountancy", "errors"));
  41. $id_journal = GETPOST('id_journal', 'int');
  42. $action = GETPOST('action', 'aZ09');
  43. $date_startmonth = GETPOST('date_startmonth');
  44. $date_startday = GETPOST('date_startday');
  45. $date_startyear = GETPOST('date_startyear');
  46. $date_endmonth = GETPOST('date_endmonth');
  47. $date_endday = GETPOST('date_endday');
  48. $date_endyear = GETPOST('date_endyear');
  49. $in_bookkeeping = GETPOST('in_bookkeeping');
  50. if ($in_bookkeeping == '') {
  51. $in_bookkeeping = 'notyet';
  52. }
  53. $now = dol_now();
  54. $hookmanager->initHooks(array('purchasesjournal'));
  55. $parameters = array();
  56. // Security check
  57. if (!isModEnabled('accounting')) {
  58. accessforbidden();
  59. }
  60. if ($user->socid > 0) {
  61. accessforbidden();
  62. }
  63. if (empty($user->rights->accounting->mouvements->lire)) {
  64. accessforbidden();
  65. }
  66. /*
  67. * Actions
  68. */
  69. $reshook = $hookmanager->executeHooks('doActions', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
  70. $accountingaccount = new AccountingAccount($db);
  71. // Get informations of journal
  72. $accountingjournalstatic = new AccountingJournal($db);
  73. $accountingjournalstatic->fetch($id_journal);
  74. $journal = $accountingjournalstatic->code;
  75. $journal_label = $accountingjournalstatic->label;
  76. $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
  77. $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
  78. if (empty($date_startmonth) || empty($date_endmonth)) {
  79. // Period by default on transfer
  80. $dates = getDefaultDatesForTransfer();
  81. $date_start = $dates['date_start'];
  82. $date_end = $dates['date_end'];
  83. $pastmonthyear = $dates['pastmonthyear'];
  84. $pastmonth = $dates['pastmonth'];
  85. }
  86. if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
  87. $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
  88. $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
  89. }
  90. $sql = "SELECT f.rowid, f.ref as ref, f.type, f.datef as df, f.libelle,f.ref_supplier, f.date_lim_reglement as dlr, f.close_code,";
  91. $sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.tva as total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.vat_src_code, fd.info_bits,";
  92. $sql .= " s.rowid as socid, s.nom as name, s.fournisseur, s.code_client, s.code_fournisseur,";
  93. if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  94. $sql .= " spe.accountancy_code_customer as code_compta,";
  95. $sql .= " spe.accountancy_code_supplier as code_compta_fournisseur,";
  96. } else {
  97. $sql .= " s.code_compta as code_compta,";
  98. $sql .= " s.code_compta_fournisseur,";
  99. }
  100. if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  101. $sql .= " ppe.accountancy_code_buy,";
  102. } else {
  103. $sql .= " p.accountancy_code_buy,";
  104. }
  105. $sql .= " aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte";
  106. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd";
  107. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
  108. if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  109. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
  110. }
  111. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
  112. $sql .= " JOIN ".MAIN_DB_PREFIX."facture_fourn as f ON f.rowid = fd.fk_facture_fourn";
  113. $sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
  114. if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  115. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
  116. }
  117. $sql .= " WHERE f.fk_statut > 0";
  118. $sql .= " AND fd.fk_code_ventilation > 0";
  119. $sql .= " AND f.entity IN (".getEntity('facture_fourn', 0).")"; // We don't share object for accountancy
  120. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  121. $sql .= " AND f.type IN (".FactureFournisseur::TYPE_STANDARD.",".FactureFournisseur::TYPE_REPLACEMENT.",".FactureFournisseur::TYPE_CREDIT_NOTE.",".FactureFournisseur::TYPE_SITUATION.")";
  122. } else {
  123. $sql .= " AND f.type IN (".FactureFournisseur::TYPE_STANDARD.",".FactureFournisseur::TYPE_REPLACEMENT.",".FactureFournisseur::TYPE_CREDIT_NOTE.",".FactureFournisseur::TYPE_DEPOSIT.",".FactureFournisseur::TYPE_SITUATION.")";
  124. }
  125. if ($date_start && $date_end) {
  126. $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
  127. }
  128. // Define begin binding date
  129. if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
  130. $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
  131. }
  132. // Already in bookkeeping or not
  133. if ($in_bookkeeping == 'already') {
  134. $sql .= " AND f.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='supplier_invoice')";
  135. }
  136. if ($in_bookkeeping == 'notyet') {
  137. $sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='supplier_invoice')";
  138. }
  139. $sql .= " ORDER BY f.datef";
  140. dol_syslog('accountancy/journal/purchasesjournal.php', LOG_DEBUG);
  141. $result = $db->query($sql);
  142. if ($result) {
  143. $tabfac = array();
  144. $tabht = array();
  145. $tabtva = array();
  146. $def_tva = array();
  147. $tabttc = array();
  148. $tablocaltax1 = array();
  149. $tablocaltax2 = array();
  150. $tabcompany = array();
  151. $tabother = array();
  152. $num = $db->num_rows($result);
  153. // Variables
  154. $cptfour = ($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : 'NotDefined';
  155. $cpttva = (!empty($conf->global->ACCOUNTING_VAT_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_BUY_ACCOUNT : 'NotDefined';
  156. $i = 0;
  157. while ($i < $num) {
  158. $obj = $db->fetch_object($result);
  159. // Controls
  160. $compta_soc = ($obj->code_compta_fournisseur != "") ? $obj->code_compta_fournisseur : $cptfour;
  161. $compta_prod = $obj->compte;
  162. if (empty($compta_prod)) {
  163. if ($obj->product_type == 0) {
  164. $compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : 'NotDefined';
  165. } else {
  166. $compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : 'NotDefined';
  167. }
  168. }
  169. $vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
  170. $compta_tva = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
  171. $compta_localtax1 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
  172. $compta_localtax2 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
  173. $compta_counterpart_tva_npr = (!empty($conf->global->ACCOUNTING_COUNTERPART_VAT_NPR)) ? $conf->global->ACCOUNTING_COUNTERPART_VAT_NPR : 'NotDefined';
  174. // Define array to display all VAT rates that use this accounting account $compta_tva
  175. if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
  176. $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
  177. }
  178. //$line = new SupplierInvoiceLine($db);
  179. //$line->fetch($obj->fdid);
  180. $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
  181. $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
  182. $tabfac[$obj->rowid]["ref"] = $obj->ref_supplier.' ('.$obj->ref.')';
  183. $tabfac[$obj->rowid]["refsologest"] = $obj->ref;
  184. $tabfac[$obj->rowid]["refsuppliersologest"] = $obj->ref_supplier;
  185. $tabfac[$obj->rowid]["type"] = $obj->type;
  186. $tabfac[$obj->rowid]["description"] = $obj->description;
  187. $tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
  188. //$tabfac[$obj->rowid]["fk_facturefourndet"] = $obj->fdid;
  189. // Avoid warnings
  190. if (!isset($tabttc[$obj->rowid][$compta_soc])) {
  191. $tabttc[$obj->rowid][$compta_soc] = 0;
  192. }
  193. if (!isset($tabht[$obj->rowid][$compta_prod])) {
  194. $tabht[$obj->rowid][$compta_prod] = 0;
  195. }
  196. if (!isset($tabtva[$obj->rowid][$compta_tva])) {
  197. $tabtva[$obj->rowid][$compta_tva] = 0;
  198. }
  199. if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
  200. $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
  201. }
  202. if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
  203. $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
  204. }
  205. $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc;
  206. $tabht[$obj->rowid][$compta_prod] += $obj->total_ht;
  207. $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
  208. $tva_npr = (($obj->info_bits & 1 == 1) ? 1 : 0);
  209. if ($tva_npr) { // If NPR, we add an entry for counterpartWe into tabother
  210. $tabother[$obj->rowid][$compta_counterpart_tva_npr] += $obj->total_tva;
  211. }
  212. $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
  213. $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
  214. $tabcompany[$obj->rowid] = array(
  215. 'id' => $obj->socid,
  216. 'name' => $obj->name,
  217. 'code_fournisseur' => $obj->code_fournisseur,
  218. 'code_compta_fournisseur' => $compta_soc
  219. );
  220. $i++;
  221. }
  222. } else {
  223. dol_print_error($db);
  224. }
  225. $errorforinvoice = array();
  226. // Loop in invoices to detect lines with not binding lines
  227. foreach ($tabfac as $key => $val) { // Loop on each invoice
  228. $sql = "SELECT COUNT(fd.rowid) as nb";
  229. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd";
  230. $sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
  231. $sql .= " AND fd.total_ttc <> 0 AND fk_facture_fourn = ".((int) $key);
  232. $resql = $db->query($sql);
  233. if ($resql) {
  234. $obj = $db->fetch_object($resql);
  235. if ($obj->nb > 0) {
  236. $errorforinvoice[$key] = 'somelinesarenotbound';
  237. }
  238. } else {
  239. dol_print_error($db);
  240. }
  241. }
  242. //var_dump($errorforinvoice);exit;
  243. // Bookkeeping Write
  244. if ($action == 'writebookkeeping') {
  245. $now = dol_now();
  246. $error = 0;
  247. $companystatic = new Societe($db);
  248. $invoicestatic = new FactureFournisseur($db);
  249. $accountingaccountsupplier = new AccountingAccount($db);
  250. $accountingaccountsupplier->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER, true);
  251. foreach ($tabfac as $key => $val) { // Loop on each invoice
  252. $errorforline = 0;
  253. $totalcredit = 0;
  254. $totaldebit = 0;
  255. $db->begin();
  256. $companystatic->id = $tabcompany[$key]['id'];
  257. $companystatic->name = $tabcompany[$key]['name'];
  258. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  259. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  260. $companystatic->fournisseur = 1;
  261. $invoicestatic->id = $key;
  262. $invoicestatic->ref = (string) $val["refsologest"];
  263. $invoicestatic->ref_supplier = $val["refsuppliersologest"];
  264. $invoicestatic->type = $val["type"];
  265. $invoicestatic->description = html_entity_decode(dol_trunc($val["description"], 32));
  266. $invoicestatic->close_code = $val["close_code"];
  267. $date = dol_print_date($val["date"], 'day');
  268. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  269. $replacedinvoice = 0;
  270. if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
  271. $replacedinvoice = 1;
  272. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  273. if ($alreadydispatched) {
  274. $replacedinvoice = 2;
  275. }
  276. }
  277. // If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
  278. if ($replacedinvoice == 1) {
  279. $db->rollback();
  280. continue;
  281. }
  282. // Error if some lines are not binded/ready to be journalized
  283. if ($errorforinvoice[$key] == 'somelinesarenotbound') {
  284. $error++;
  285. $errorforline++;
  286. setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
  287. }
  288. // Thirdparty
  289. if (!$errorforline) {
  290. foreach ($tabttc[$key] as $k => $mt) {
  291. $bookkeeping = new BookKeeping($db);
  292. $bookkeeping->doc_date = $val["date"];
  293. $bookkeeping->date_lim_reglement = $val["datereg"];
  294. $bookkeeping->doc_ref = $val["refsologest"];
  295. $bookkeeping->date_creation = $now;
  296. $bookkeeping->doc_type = 'supplier_invoice';
  297. $bookkeeping->fk_doc = $key;
  298. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  299. $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
  300. $bookkeeping->subledger_account = $tabcompany[$key]['code_compta_fournisseur'];
  301. $bookkeeping->subledger_label = $tabcompany[$key]['name'];
  302. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
  303. $bookkeeping->label_compte = $accountingaccountsupplier->label;
  304. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("SubledgerAccount");
  305. $bookkeeping->montant = $mt;
  306. $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
  307. $bookkeeping->debit = ($mt <= 0) ? -$mt : 0;
  308. $bookkeeping->credit = ($mt > 0) ? $mt : 0;
  309. $bookkeeping->code_journal = $journal;
  310. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  311. $bookkeeping->fk_user_author = $user->id;
  312. $bookkeeping->entity = $conf->entity;
  313. $totaldebit += $bookkeeping->debit;
  314. $totalcredit += $bookkeeping->credit;
  315. $result = $bookkeeping->create($user);
  316. if ($result < 0) {
  317. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  318. $error++;
  319. $errorforline++;
  320. $errorforinvoice[$key] = 'alreadyjournalized';
  321. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  322. } else {
  323. $error++;
  324. $errorforline++;
  325. $errorforinvoice[$key] = 'other';
  326. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  327. }
  328. } else {
  329. if (getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
  330. require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
  331. $lettering_static = new Lettering($db);
  332. $nb_lettering = $lettering_static->bookkeepingLettering(array($bookkeeping->id));
  333. if ($nb_lettering < 0) {
  334. $error++;
  335. $errorforline++;
  336. setEventMessages($lettering_static->error, $lettering_static->errors, 'errors');
  337. }
  338. }
  339. }
  340. }
  341. }
  342. // Product / Service
  343. if (!$errorforline) {
  344. foreach ($tabht[$key] as $k => $mt) {
  345. $resultfetch = $accountingaccount->fetch(null, $k, true); // TODO Use a cache
  346. $label_account = $accountingaccount->label;
  347. // get compte id and label
  348. if ($resultfetch > 0) {
  349. $bookkeeping = new BookKeeping($db);
  350. $bookkeeping->doc_date = $val["date"];
  351. $bookkeeping->date_lim_reglement = $val["datereg"];
  352. $bookkeeping->doc_ref = $val["refsologest"];
  353. $bookkeeping->date_creation = $now;
  354. $bookkeeping->doc_type = 'supplier_invoice';
  355. $bookkeeping->fk_doc = $key;
  356. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  357. $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
  358. if (!empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER_USE_AUXILIARY_ON_DEPOSIT)) {
  359. if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER_DEPOSIT')) {
  360. $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
  361. $bookkeeping->subledger_label = $tabcompany[$key]['name'];
  362. } else {
  363. $bookkeeping->subledger_account = '';
  364. $bookkeeping->subledger_label = '';
  365. }
  366. } else {
  367. $bookkeeping->subledger_account = '';
  368. $bookkeeping->subledger_label = '';
  369. }
  370. $bookkeeping->numero_compte = $k;
  371. $bookkeeping->label_compte = $label_account;
  372. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$label_account;
  373. $bookkeeping->montant = $mt;
  374. $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
  375. $bookkeeping->debit = ($mt > 0) ? $mt : 0;
  376. $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
  377. $bookkeeping->code_journal = $journal;
  378. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  379. $bookkeeping->fk_user_author = $user->id;
  380. $bookkeeping->entity = $conf->entity;
  381. $totaldebit += $bookkeeping->debit;
  382. $totalcredit += $bookkeeping->credit;
  383. $result = $bookkeeping->create($user);
  384. if ($result < 0) {
  385. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  386. $error++;
  387. $errorforline++;
  388. $errorforinvoice[$key] = 'alreadyjournalized';
  389. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  390. } else {
  391. $error++;
  392. $errorforline++;
  393. $errorforinvoice[$key] = 'other';
  394. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  395. }
  396. }
  397. }
  398. }
  399. }
  400. // VAT
  401. // var_dump($tabtva);
  402. if (!$errorforline) {
  403. $listoftax = array(0, 1, 2);
  404. foreach ($listoftax as $numtax) {
  405. $arrayofvat = $tabtva;
  406. if ($numtax == 1) {
  407. $arrayofvat = $tablocaltax1;
  408. }
  409. if ($numtax == 2) {
  410. $arrayofvat = $tablocaltax2;
  411. }
  412. foreach ($arrayofvat[$key] as $k => $mt) {
  413. if ($mt) {
  414. $accountingaccount->fetch(null, $k, true); // TODO Use a cache for label
  415. $label_account = $accountingaccount->label;
  416. $bookkeeping = new BookKeeping($db);
  417. $bookkeeping->doc_date = $val["date"];
  418. $bookkeeping->date_lim_reglement = $val["datereg"];
  419. $bookkeeping->doc_ref = $val["refsologest"];
  420. $bookkeeping->date_creation = $now;
  421. $bookkeeping->doc_type = 'supplier_invoice';
  422. $bookkeeping->fk_doc = $key;
  423. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  424. $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
  425. $bookkeeping->subledger_account = '';
  426. $bookkeeping->subledger_label = '';
  427. $bookkeeping->numero_compte = $k;
  428. $bookkeeping->label_compte = $label_account;
  429. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
  430. $bookkeeping->montant = $mt;
  431. $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
  432. $bookkeeping->debit = ($mt > 0) ? $mt : 0;
  433. $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
  434. $bookkeeping->code_journal = $journal;
  435. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  436. $bookkeeping->fk_user_author = $user->id;
  437. $bookkeeping->entity = $conf->entity;
  438. $totaldebit += $bookkeeping->debit;
  439. $totalcredit += $bookkeeping->credit;
  440. $result = $bookkeeping->create($user);
  441. if ($result < 0) {
  442. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  443. $error++;
  444. $errorforline++;
  445. $errorforinvoice[$key] = 'alreadyjournalized';
  446. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  447. } else {
  448. $error++;
  449. $errorforline++;
  450. $errorforinvoice[$key] = 'other';
  451. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  452. }
  453. }
  454. }
  455. }
  456. }
  457. }
  458. // Counterpart of VAT for VAT NPR
  459. // var_dump($tabother);
  460. if (!$errorforline && is_array($tabother[$key])) {
  461. foreach ($tabother[$key] as $k => $mt) {
  462. if ($mt) {
  463. $bookkeeping = new BookKeeping($db);
  464. $bookkeeping->doc_date = $val["date"];
  465. $bookkeeping->date_lim_reglement = $val["datereg"];
  466. $bookkeeping->doc_ref = $val["refsologest"];
  467. $bookkeeping->date_creation = $now;
  468. $bookkeeping->doc_type = 'supplier_invoice';
  469. $bookkeeping->fk_doc = $key;
  470. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  471. $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
  472. $bookkeeping->subledger_account = '';
  473. $bookkeeping->subledger_label = '';
  474. $bookkeeping->numero_compte = $k;
  475. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' NPR';
  476. $bookkeeping->montant = $mt;
  477. $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
  478. $bookkeeping->debit = ($mt > 0) ? $mt : 0;
  479. $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
  480. $bookkeeping->code_journal = $journal;
  481. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  482. $bookkeeping->fk_user_author = $user->id;
  483. $bookkeeping->entity = $conf->entity;
  484. $totaldebit += $bookkeeping->debit;
  485. $totalcredit += $bookkeeping->credit;
  486. $result = $bookkeeping->create($user);
  487. if ($result < 0) {
  488. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  489. $error++;
  490. $errorforline++;
  491. $errorforinvoice[$key] = 'alreadyjournalized';
  492. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  493. } else {
  494. $error++;
  495. $errorforline++;
  496. $errorforinvoice[$key] = 'other';
  497. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  498. }
  499. }
  500. }
  501. }
  502. }
  503. // Protection against a bug on lines before
  504. if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
  505. $error++;
  506. $errorforline++;
  507. $errorforinvoice[$key] = 'amountsnotbalanced';
  508. setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
  509. }
  510. if (!$errorforline) {
  511. $db->commit();
  512. } else {
  513. $db->rollback();
  514. if ($error >= 10) {
  515. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
  516. break; // Break in the foreach
  517. }
  518. }
  519. }
  520. $tabpay = $tabfac;
  521. if (empty($error) && count($tabpay) > 0) {
  522. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  523. } elseif (count($tabpay) == $error) {
  524. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  525. } else {
  526. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  527. }
  528. $action = '';
  529. // Must reload data, so we make a redirect
  530. if (count($tabpay) != $error) {
  531. $param = 'id_journal='.$id_journal;
  532. $param .= '&date_startday='.$date_startday;
  533. $param .= '&date_startmonth='.$date_startmonth;
  534. $param .= '&date_startyear='.$date_startyear;
  535. $param .= '&date_endday='.$date_endday;
  536. $param .= '&date_endmonth='.$date_endmonth;
  537. $param .= '&date_endyear='.$date_endyear;
  538. $param .= '&in_bookkeeping='.$in_bookkeeping;
  539. header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
  540. exit;
  541. }
  542. }
  543. /*
  544. * View
  545. */
  546. $form = new Form($db);
  547. // Export
  548. if ($action == 'exportcsv') { // ISO and not UTF8 !
  549. $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
  550. $filename = 'journal';
  551. $type_export = 'journal';
  552. include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
  553. $companystatic = new Fournisseur($db);
  554. $invoicestatic = new FactureFournisseur($db);
  555. foreach ($tabfac as $key => $val) {
  556. $companystatic->id = $tabcompany[$key]['id'];
  557. $companystatic->name = $tabcompany[$key]['name'];
  558. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  559. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  560. $companystatic->fournisseur = 1;
  561. $invoicestatic->id = $key;
  562. $invoicestatic->ref = $val["refsologest"];
  563. $invoicestatic->ref_supplier = $val["refsuppliersologest"];
  564. $invoicestatic->type = $val["type"];
  565. $invoicestatic->description = dol_trunc(html_entity_decode($val["description"]), 32);
  566. $invoicestatic->close_code = $val["close_code"];
  567. $date = dol_print_date($val["date"], 'day');
  568. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  569. $replacedinvoice = 0;
  570. if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
  571. $replacedinvoice = 1;
  572. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  573. if ($alreadydispatched) {
  574. $replacedinvoice = 2;
  575. }
  576. }
  577. // If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
  578. if ($replacedinvoice == 1) {
  579. continue;
  580. }
  581. // Third party
  582. foreach ($tabttc[$key] as $k => $mt) {
  583. //if ($mt) {
  584. print '"'.$key.'"'.$sep;
  585. print '"'.$date.'"'.$sep;
  586. print '"'.$val["refsologest"].'"'.$sep;
  587. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  588. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  589. print '"'.length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER).'"'.$sep;
  590. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  591. print '"'.$langs->trans("Thirdparty").'"'.$sep;
  592. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("Thirdparty").'"'.$sep;
  593. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  594. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  595. print '"'.$journal.'"';
  596. print "\n";
  597. //}
  598. }
  599. // Product / Service
  600. foreach ($tabht[$key] as $k => $mt) {
  601. $accountingaccount = new AccountingAccount($db);
  602. $accountingaccount->fetch(null, $k, true);
  603. //if ($mt) {
  604. print '"'.$key.'"'.$sep;
  605. print '"'.$date.'"'.$sep;
  606. print '"'.$val["refsologest"].'"'.$sep;
  607. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  608. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  609. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  610. print '""'.$sep;
  611. print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
  612. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep;
  613. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  614. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  615. print '"'.$journal.'"';
  616. print "\n";
  617. //}
  618. }
  619. // VAT
  620. $listoftax = array(0, 1, 2);
  621. foreach ($listoftax as $numtax) {
  622. $arrayofvat = $tabtva;
  623. if ($numtax == 1) {
  624. $arrayofvat = $tablocaltax1;
  625. }
  626. if ($numtax == 2) {
  627. $arrayofvat = $tablocaltax2;
  628. }
  629. foreach ($arrayofvat[$key] as $k => $mt) {
  630. if ($mt) {
  631. print '"'.$key.'"'.$sep;
  632. print '"'.$date.'"'.$sep;
  633. print '"'.$val["refsologest"].'"'.$sep;
  634. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  635. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  636. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  637. print '""'.$sep;
  638. print '"'.$langs->trans("VAT").' - '.join(', ', $def_tva[$key][$k]).' %"'.$sep;
  639. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep;
  640. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  641. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  642. print '"'.$journal.'"';
  643. print "\n";
  644. }
  645. }
  646. // VAT counterpart for NPR
  647. if (is_array($tabother[$key])) {
  648. foreach ($tabother[$key] as $k => $mt) {
  649. if ($mt) {
  650. print '"'.$key.'"'.$sep;
  651. print '"'.$date.'"'.$sep;
  652. print '"'.$val["refsologest"].'"'.$sep;
  653. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  654. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  655. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  656. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  657. print '"'.$langs->trans("Thirdparty").'"'.$sep;
  658. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").' NPR"'.$sep;
  659. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  660. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  661. print '"'.$journal.'"';
  662. print "\n";
  663. }
  664. }
  665. }
  666. }
  667. }
  668. }
  669. if (empty($action) || $action == 'view') {
  670. $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
  671. llxHeader('', dol_string_nohtmltag($title));
  672. $nom = $title;
  673. $nomlink = '';
  674. $periodlink = '';
  675. $exportlink = '';
  676. $builddate = dol_now();
  677. $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  678. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  679. $description .= $langs->trans("DepositsAreNotIncluded");
  680. } else {
  681. $description .= $langs->trans("DepositsAreIncluded");
  682. }
  683. $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  684. $period = $form->selectDate($date_start ? $date_start : -1, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end ? $date_end : -1, 'date_end', 0, 0, 0, '', 1, 0);
  685. $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  686. $varlink = 'id_journal='.$id_journal;
  687. journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  688. // Button to write into Ledger
  689. if (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
  690. print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  691. $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
  692. $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
  693. print $desc;
  694. print '</div>';
  695. }
  696. print '<div class="tabsAction tabsActionNoBottom centerimp">';
  697. if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') {
  698. print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
  699. }
  700. if (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
  701. print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
  702. } else {
  703. if ($in_bookkeeping == 'notyet') {
  704. print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
  705. } else {
  706. print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
  707. }
  708. }
  709. print '</div>';
  710. // TODO Avoid using js. We can use a direct link with $param
  711. print '
  712. <script type="text/javascript">
  713. function launch_export() {
  714. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  715. $("div.fiche form input[type=\"submit\"]").click();
  716. $("div.fiche form input[name=\"action\"]").val("");
  717. }
  718. function writebookkeeping() {
  719. console.log("click on writebookkeeping");
  720. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  721. $("div.fiche form input[type=\"submit\"]").click();
  722. $("div.fiche form input[name=\"action\"]").val("");
  723. }
  724. </script>';
  725. /*
  726. * Show result array
  727. */
  728. print '<br>';
  729. print '<div class="div-table-responsive">';
  730. print "<table class=\"noborder\" width=\"100%\">";
  731. print "<tr class=\"liste_titre\">";
  732. print "<td>".$langs->trans("Date")."</td>";
  733. print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
  734. print "<td>".$langs->trans("AccountAccounting")."</td>";
  735. print "<td>".$langs->trans("SubledgerAccount")."</td>";
  736. print "<td>".$langs->trans("LabelOperation")."</td>";
  737. print '<td class="center">'.$langs->trans("AccountingDebit")."</td>";
  738. print '<td class="center">'.$langs->trans("AccountingCredit")."</td>";
  739. print "</tr>\n";
  740. $i = 0;
  741. $invoicestatic = new FactureFournisseur($db);
  742. $companystatic = new Fournisseur($db);
  743. foreach ($tabfac as $key => $val) {
  744. $companystatic->id = $tabcompany[$key]['id'];
  745. $companystatic->name = $tabcompany[$key]['name'];
  746. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  747. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  748. $companystatic->fournisseur = 1;
  749. $invoicestatic->id = $key;
  750. $invoicestatic->ref = $val["refsologest"];
  751. $invoicestatic->ref_supplier = $val["refsuppliersologest"];
  752. $invoicestatic->type = $val["type"];
  753. $invoicestatic->description = dol_trunc(html_entity_decode($val["description"]), 32);
  754. $invoicestatic->close_code = $val["close_code"];
  755. $date = dol_print_date($val["date"], 'day');
  756. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  757. $replacedinvoice = 0;
  758. if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
  759. $replacedinvoice = 1;
  760. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  761. if ($alreadydispatched) {
  762. $replacedinvoice = 2;
  763. }
  764. }
  765. // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
  766. if ($replacedinvoice == 1) {
  767. print '<tr class="oddeven">';
  768. print "<!-- Replaced invoice -->";
  769. print "<td>".$date."</td>";
  770. print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
  771. // Account
  772. print "<td>";
  773. print $langs->trans("Replaced");
  774. print '</td>';
  775. // Subledger account
  776. print "<td>";
  777. print '</td>';
  778. print "<td>";
  779. print "</td>";
  780. print '<td class="right"></td>';
  781. print '<td class="right"></td>';
  782. print "</tr>";
  783. $i++;
  784. continue;
  785. }
  786. if ($errorforinvoice[$key] == 'somelinesarenotbound') {
  787. print '<tr class="oddeven">';
  788. print "<!-- Some lines are not bound -->";
  789. print "<td>".$date."</td>";
  790. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  791. // Account
  792. print "<td>";
  793. print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
  794. print '</td>';
  795. // Subledger account
  796. print "<td>";
  797. print '</td>';
  798. print "<td>";
  799. print "</td>";
  800. print '<td class="right"></td>';
  801. print '<td class="right"></td>';
  802. print "</tr>";
  803. $i++;
  804. }
  805. // Third party
  806. foreach ($tabttc[$key] as $k => $mt) {
  807. print '<tr class="oddeven">';
  808. print "<!-- Thirdparty -->";
  809. print "<td>".$date."</td>";
  810. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  811. // Account
  812. print "<td>";
  813. $accountoshow = length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER);
  814. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  815. print '<span class="error">'.$langs->trans("MainAccountForSuppliersNotDefined").'</span>';
  816. } else {
  817. print $accountoshow;
  818. }
  819. print '</td>';
  820. // Subledger account
  821. print "<td>";
  822. $accountoshow = length_accounta($k);
  823. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  824. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  825. } else {
  826. print $accountoshow;
  827. }
  828. print '</td>';
  829. print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("SubledgerAccount")."</td>";
  830. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  831. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  832. print "</tr>";
  833. $i++;
  834. }
  835. // Product / Service
  836. foreach ($tabht[$key] as $k => $mt) {
  837. $accountingaccount = new AccountingAccount($db);
  838. $accountingaccount->fetch(null, $k, true);
  839. print '<tr class="oddeven">';
  840. print "<!-- Product -->";
  841. print "<td>".$date."</td>";
  842. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  843. // Account
  844. print "<td>";
  845. $accountoshow = length_accountg($k);
  846. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  847. print '<span class="error">'.$langs->trans("ProductAccountNotDefined").'</span>';
  848. } else {
  849. print $accountoshow;
  850. }
  851. print "</td>";
  852. // Subledger account
  853. print "<td>";
  854. if (!empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER_USE_AUXILIARY_ON_DEPOSIT)) {
  855. if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER_DEPOSIT')) {
  856. print length_accounta($tabcompany[$key]['code_compta']);
  857. }
  858. } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
  859. print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
  860. }
  861. print '</td>';
  862. $companystatic->id = $tabcompany[$key]['id'];
  863. $companystatic->name = $tabcompany[$key]['name'];
  864. print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$accountingaccount->label."</td>";
  865. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  866. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  867. print "</tr>";
  868. $i++;
  869. }
  870. // VAT
  871. $listoftax = array(0, 1, 2);
  872. foreach ($listoftax as $numtax) {
  873. $arrayofvat = $tabtva;
  874. if ($numtax == 1) {
  875. $arrayofvat = $tablocaltax1;
  876. }
  877. if ($numtax == 2) {
  878. $arrayofvat = $tablocaltax2;
  879. }
  880. foreach ($arrayofvat[$key] as $k => $mt) {
  881. if ($mt) {
  882. print '<tr class="oddeven">';
  883. print "<!-- VAT -->";
  884. print "<td>".$date."</td>";
  885. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  886. // Account
  887. print "<td>";
  888. $accountoshow = length_accountg($k);
  889. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  890. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Purchase").')</span>';
  891. } else {
  892. print $accountoshow;
  893. }
  894. print "</td>";
  895. // Subledger account
  896. print "<td>";
  897. print '</td>';
  898. print "<td>";
  899. print $companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
  900. print "</td>";
  901. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  902. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  903. print "</tr>";
  904. $i++;
  905. }
  906. }
  907. }
  908. // VAT counterpart for NPR
  909. if (is_array($tabother[$key])) {
  910. foreach ($tabother[$key] as $k => $mt) {
  911. if ($mt) {
  912. print '<tr class="oddeven">';
  913. print '<!-- VAT counterpart NPR -->';
  914. print "<td>".$date."</td>";
  915. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  916. // Account
  917. print '<td>';
  918. $accountoshow = length_accountg($k);
  919. if ($accountoshow == '' || $accountoshow == 'NotDefined') {
  920. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("NPR counterpart").'). Set ACCOUNTING_COUNTERPART_VAT_NPR to the subvention account</span>';
  921. } else {
  922. print $accountoshow;
  923. }
  924. print '</td>';
  925. // Subledger account
  926. print "<td>";
  927. print '</td>';
  928. print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT")." NPR (counterpart)</td>";
  929. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  930. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  931. print "</tr>";
  932. $i++;
  933. }
  934. }
  935. }
  936. }
  937. if (!$i) {
  938. print '<tr class="oddeven"><td colspan="7"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
  939. }
  940. print "</table>";
  941. print '</div>';
  942. // End of page
  943. llxFooter();
  944. }
  945. $db->close();