purchasesjournal.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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 (empty($conf->accounting->enabled)) {
  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,";
  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_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. if (!empty($line->tva_npr)) { // Add an entry for counterpart
  209. $tabother[$obj->rowid][$compta_counterpart_tva_npr] += $obj->total_tva;
  210. }
  211. $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
  212. $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
  213. $tabcompany[$obj->rowid] = array(
  214. 'id' => $obj->socid,
  215. 'name' => $obj->name,
  216. 'code_fournisseur' => $obj->code_fournisseur,
  217. 'code_compta_fournisseur' => $compta_soc
  218. );
  219. $i++;
  220. }
  221. } else {
  222. dol_print_error($db);
  223. }
  224. $errorforinvoice = array();
  225. // Loop in invoices to detect lines with not binding lines
  226. foreach ($tabfac as $key => $val) { // Loop on each invoice
  227. $sql = "SELECT COUNT(fd.rowid) as nb";
  228. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd";
  229. $sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
  230. $sql .= " AND fd.total_ttc <> 0 AND fk_facture_fourn = ".((int) $key);
  231. $resql = $db->query($sql);
  232. if ($resql) {
  233. $obj = $db->fetch_object($resql);
  234. if ($obj->nb > 0) {
  235. $errorforinvoice[$key] = 'somelinesarenotbound';
  236. }
  237. } else {
  238. dol_print_error($db);
  239. }
  240. }
  241. //var_dump($errorforinvoice);exit;
  242. // Bookkeeping Write
  243. if ($action == 'writebookkeeping') {
  244. $now = dol_now();
  245. $error = 0;
  246. $companystatic = new Societe($db);
  247. $invoicestatic = new FactureFournisseur($db);
  248. $accountingaccountsupplier = new AccountingAccount($db);
  249. $accountingaccountsupplier->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER, true);
  250. foreach ($tabfac as $key => $val) { // Loop on each invoice
  251. $errorforline = 0;
  252. $totalcredit = 0;
  253. $totaldebit = 0;
  254. $db->begin();
  255. $companystatic->id = $tabcompany[$key]['id'];
  256. $companystatic->name = $tabcompany[$key]['name'];
  257. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  258. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  259. $companystatic->code_client = $tabcompany[$key]['code_client'];
  260. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  261. $companystatic->fournisseur = 1;
  262. $invoicestatic->id = $key;
  263. $invoicestatic->ref = (string) $val["refsologest"];
  264. $invoicestatic->ref_supplier = $val["refsuppliersologest"];
  265. $invoicestatic->type = $val["type"];
  266. $invoicestatic->description = html_entity_decode(dol_trunc($val["description"], 32));
  267. $invoicestatic->close_code = $val["close_code"];
  268. $date = dol_print_date($val["date"], 'day');
  269. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  270. $replacedinvoice = 0;
  271. if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
  272. $replacedinvoice = 1;
  273. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  274. if ($alreadydispatched) {
  275. $replacedinvoice = 2;
  276. }
  277. }
  278. // 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)
  279. if ($replacedinvoice == 1) {
  280. $db->rollback();
  281. continue;
  282. }
  283. // Error if some lines are not binded/ready to be journalized
  284. if ($errorforinvoice[$key] == 'somelinesarenotbound') {
  285. $error++;
  286. $errorforline++;
  287. setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
  288. }
  289. // Thirdparty
  290. if (!$errorforline) {
  291. foreach ($tabttc[$key] as $k => $mt) {
  292. $bookkeeping = new BookKeeping($db);
  293. $bookkeeping->doc_date = $val["date"];
  294. $bookkeeping->date_lim_reglement = $val["datereg"];
  295. $bookkeeping->doc_ref = $val["refsologest"];
  296. $bookkeeping->date_creation = $now;
  297. $bookkeeping->doc_type = 'supplier_invoice';
  298. $bookkeeping->fk_doc = $key;
  299. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  300. $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
  301. $bookkeeping->subledger_account = $tabcompany[$key]['code_compta_fournisseur'];
  302. $bookkeeping->subledger_label = $tabcompany[$key]['name'];
  303. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
  304. $bookkeeping->label_compte = $accountingaccountsupplier->label;
  305. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("SubledgerAccount");
  306. $bookkeeping->montant = $mt;
  307. $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
  308. $bookkeeping->debit = ($mt <= 0) ? -$mt : 0;
  309. $bookkeeping->credit = ($mt > 0) ? $mt : 0;
  310. $bookkeeping->code_journal = $journal;
  311. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  312. $bookkeeping->fk_user_author = $user->id;
  313. $bookkeeping->entity = $conf->entity;
  314. $totaldebit += $bookkeeping->debit;
  315. $totalcredit += $bookkeeping->credit;
  316. $result = $bookkeeping->create($user);
  317. if ($result < 0) {
  318. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  319. $error++;
  320. $errorforline++;
  321. $errorforinvoice[$key] = 'alreadyjournalized';
  322. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  323. } else {
  324. $error++;
  325. $errorforline++;
  326. $errorforinvoice[$key] = 'other';
  327. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  328. }
  329. }
  330. }
  331. }
  332. // Product / Service
  333. if (!$errorforline) {
  334. foreach ($tabht[$key] as $k => $mt) {
  335. $resultfetch = $accountingaccount->fetch(null, $k, true); // TODO Use a cache
  336. $label_account = $accountingaccount->label;
  337. // get compte id and label
  338. if ($resultfetch > 0) {
  339. $bookkeeping = new BookKeeping($db);
  340. $bookkeeping->doc_date = $val["date"];
  341. $bookkeeping->date_lim_reglement = $val["datereg"];
  342. $bookkeeping->doc_ref = $val["refsologest"];
  343. $bookkeeping->date_creation = $now;
  344. $bookkeeping->doc_type = 'supplier_invoice';
  345. $bookkeeping->fk_doc = $key;
  346. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  347. $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
  348. $bookkeeping->subledger_account = '';
  349. $bookkeeping->subledger_label = '';
  350. $bookkeeping->numero_compte = $k;
  351. $bookkeeping->label_compte = $label_account;
  352. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$label_account;
  353. $bookkeeping->montant = $mt;
  354. $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
  355. $bookkeeping->debit = ($mt > 0) ? $mt : 0;
  356. $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
  357. $bookkeeping->code_journal = $journal;
  358. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  359. $bookkeeping->fk_user_author = $user->id;
  360. $bookkeeping->entity = $conf->entity;
  361. $totaldebit += $bookkeeping->debit;
  362. $totalcredit += $bookkeeping->credit;
  363. $result = $bookkeeping->create($user);
  364. if ($result < 0) {
  365. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  366. $error++;
  367. $errorforline++;
  368. $errorforinvoice[$key] = 'alreadyjournalized';
  369. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  370. } else {
  371. $error++;
  372. $errorforline++;
  373. $errorforinvoice[$key] = 'other';
  374. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  375. }
  376. }
  377. }
  378. }
  379. }
  380. // VAT
  381. // var_dump($tabtva);
  382. if (!$errorforline) {
  383. $listoftax = array(0, 1, 2);
  384. foreach ($listoftax as $numtax) {
  385. $arrayofvat = $tabtva;
  386. if ($numtax == 1) {
  387. $arrayofvat = $tablocaltax1;
  388. }
  389. if ($numtax == 2) {
  390. $arrayofvat = $tablocaltax2;
  391. }
  392. foreach ($arrayofvat[$key] as $k => $mt) {
  393. if ($mt) {
  394. $accountingaccount->fetch($k, null, true); // TODO Use a cache for label
  395. $label_account = $accountingaccount->label;
  396. $bookkeeping = new BookKeeping($db);
  397. $bookkeeping->doc_date = $val["date"];
  398. $bookkeeping->date_lim_reglement = $val["datereg"];
  399. $bookkeeping->doc_ref = $val["refsologest"];
  400. $bookkeeping->date_creation = $now;
  401. $bookkeeping->doc_type = 'supplier_invoice';
  402. $bookkeeping->fk_doc = $key;
  403. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  404. $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
  405. $bookkeeping->subledger_account = '';
  406. $bookkeeping->subledger_label = '';
  407. $bookkeeping->numero_compte = $k;
  408. $bookkeeping->label_compte = $label_account;
  409. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
  410. $bookkeeping->montant = $mt;
  411. $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
  412. $bookkeeping->debit = ($mt > 0) ? $mt : 0;
  413. $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
  414. $bookkeeping->code_journal = $journal;
  415. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  416. $bookkeeping->fk_user_author = $user->id;
  417. $bookkeeping->entity = $conf->entity;
  418. $totaldebit += $bookkeeping->debit;
  419. $totalcredit += $bookkeeping->credit;
  420. $result = $bookkeeping->create($user);
  421. if ($result < 0) {
  422. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  423. $error++;
  424. $errorforline++;
  425. $errorforinvoice[$key] = 'alreadyjournalized';
  426. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  427. } else {
  428. $error++;
  429. $errorforline++;
  430. $errorforinvoice[$key] = 'other';
  431. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  432. }
  433. }
  434. }
  435. }
  436. }
  437. }
  438. // Counterpart of VAT for VAT NPR
  439. // var_dump($tabother);
  440. if (!$errorforline && is_array($tabother[$key])) {
  441. foreach ($tabother[$key] as $k => $mt) {
  442. if ($mt) {
  443. $bookkeeping = new BookKeeping($db);
  444. $bookkeeping->doc_date = $val["date"];
  445. $bookkeeping->date_lim_reglement = $val["datereg"];
  446. $bookkeeping->doc_ref = $val["refsologest"];
  447. $bookkeeping->date_creation = $now;
  448. $bookkeeping->doc_type = 'supplier_invoice';
  449. $bookkeeping->fk_doc = $key;
  450. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  451. $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
  452. $bookkeeping->subledger_account = '';
  453. $bookkeeping->subledger_label = '';
  454. $bookkeeping->numero_compte = $k;
  455. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' NPR';
  456. $bookkeeping->montant = $mt;
  457. $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
  458. $bookkeeping->debit = ($mt > 0) ? $mt : 0;
  459. $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
  460. $bookkeeping->code_journal = $journal;
  461. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  462. $bookkeeping->fk_user_author = $user->id;
  463. $bookkeeping->entity = $conf->entity;
  464. $totaldebit += $bookkeeping->debit;
  465. $totalcredit += $bookkeeping->credit;
  466. $result = $bookkeeping->create($user);
  467. if ($result < 0) {
  468. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  469. $error++;
  470. $errorforline++;
  471. $errorforinvoice[$key] = 'alreadyjournalized';
  472. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  473. } else {
  474. $error++;
  475. $errorforline++;
  476. $errorforinvoice[$key] = 'other';
  477. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  478. }
  479. }
  480. }
  481. }
  482. }
  483. // Protection against a bug on lines before
  484. if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
  485. $error++;
  486. $errorforline++;
  487. $errorforinvoice[$key] = 'amountsnotbalanced';
  488. setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
  489. }
  490. if (!$errorforline) {
  491. $db->commit();
  492. } else {
  493. $db->rollback();
  494. if ($error >= 10) {
  495. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
  496. break; // Break in the foreach
  497. }
  498. }
  499. }
  500. $tabpay = $tabfac;
  501. if (empty($error) && count($tabpay) > 0) {
  502. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  503. } elseif (count($tabpay) == $error) {
  504. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  505. } else {
  506. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  507. }
  508. $action = '';
  509. // Must reload data, so we make a redirect
  510. if (count($tabpay) != $error) {
  511. $param = 'id_journal='.$id_journal;
  512. $param .= '&date_startday='.$date_startday;
  513. $param .= '&date_startmonth='.$date_startmonth;
  514. $param .= '&date_startyear='.$date_startyear;
  515. $param .= '&date_endday='.$date_endday;
  516. $param .= '&date_endmonth='.$date_endmonth;
  517. $param .= '&date_endyear='.$date_endyear;
  518. $param .= '&in_bookkeeping='.$in_bookkeeping;
  519. header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
  520. exit;
  521. }
  522. }
  523. /*
  524. * View
  525. */
  526. $form = new Form($db);
  527. // Export
  528. if ($action == 'exportcsv') { // ISO and not UTF8 !
  529. $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
  530. $filename = 'journal';
  531. $type_export = 'journal';
  532. include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
  533. $companystatic = new Fournisseur($db);
  534. $invoicestatic = new FactureFournisseur($db);
  535. foreach ($tabfac as $key => $val) {
  536. $companystatic->id = $tabcompany[$key]['id'];
  537. $companystatic->name = $tabcompany[$key]['name'];
  538. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  539. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  540. $companystatic->code_client = $tabcompany[$key]['code_client'];
  541. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  542. $companystatic->fournisseur = 1;
  543. $invoicestatic->id = $key;
  544. $invoicestatic->ref = $val["refsologest"];
  545. $invoicestatic->ref_supplier = $val["refsuppliersologest"];
  546. $invoicestatic->type = $val["type"];
  547. $invoicestatic->description = dol_trunc(html_entity_decode($val["description"]), 32);
  548. $invoicestatic->close_code = $val["close_code"];
  549. $date = dol_print_date($val["date"], 'day');
  550. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  551. $replacedinvoice = 0;
  552. if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
  553. $replacedinvoice = 1;
  554. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  555. if ($alreadydispatched) {
  556. $replacedinvoice = 2;
  557. }
  558. }
  559. // 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)
  560. if ($replacedinvoice == 1) {
  561. continue;
  562. }
  563. // Third party
  564. foreach ($tabttc[$key] as $k => $mt) {
  565. //if ($mt) {
  566. print '"'.$key.'"'.$sep;
  567. print '"'.$date.'"'.$sep;
  568. print '"'.$val["refsologest"].'"'.$sep;
  569. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  570. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  571. print '"'.length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER).'"'.$sep;
  572. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  573. print '"'.$langs->trans("Thirdparty").'"'.$sep;
  574. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("Thirdparty").'"'.$sep;
  575. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  576. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  577. print '"'.$journal.'"';
  578. print "\n";
  579. //}
  580. }
  581. // Product / Service
  582. foreach ($tabht[$key] as $k => $mt) {
  583. $accountingaccount = new AccountingAccount($db);
  584. $accountingaccount->fetch(null, $k, true);
  585. //if ($mt) {
  586. print '"'.$key.'"'.$sep;
  587. print '"'.$date.'"'.$sep;
  588. print '"'.$val["refsologest"].'"'.$sep;
  589. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  590. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  591. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  592. print '""'.$sep;
  593. print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
  594. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep;
  595. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  596. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  597. print '"'.$journal.'"';
  598. print "\n";
  599. //}
  600. }
  601. // VAT
  602. $listoftax = array(0, 1, 2);
  603. foreach ($listoftax as $numtax) {
  604. $arrayofvat = $tabtva;
  605. if ($numtax == 1) {
  606. $arrayofvat = $tablocaltax1;
  607. }
  608. if ($numtax == 2) {
  609. $arrayofvat = $tablocaltax2;
  610. }
  611. foreach ($arrayofvat[$key] as $k => $mt) {
  612. if ($mt) {
  613. print '"'.$key.'"'.$sep;
  614. print '"'.$date.'"'.$sep;
  615. print '"'.$val["refsologest"].'"'.$sep;
  616. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  617. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  618. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  619. print '""'.$sep;
  620. print '"'.$langs->trans("VAT").' - '.join(', ', $def_tva[$key][$k]).' %"'.$sep;
  621. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep;
  622. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  623. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  624. print '"'.$journal.'"';
  625. print "\n";
  626. }
  627. }
  628. // VAT counterpart for NPR
  629. if (is_array($tabother[$key])) {
  630. foreach ($tabother[$key] as $k => $mt) {
  631. if ($mt) {
  632. print '"'.$key.'"'.$sep;
  633. print '"'.$date.'"'.$sep;
  634. print '"'.$val["refsologest"].'"'.$sep;
  635. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  636. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  637. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  638. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  639. print '"'.$langs->trans("Thirdparty").'"'.$sep;
  640. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").' NPR"'.$sep;
  641. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  642. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  643. print '"'.$journal.'"';
  644. print "\n";
  645. }
  646. }
  647. }
  648. }
  649. }
  650. }
  651. if (empty($action) || $action == 'view') {
  652. llxHeader('', $langs->trans("PurchasesJournal"));
  653. $nom = $langs->trans("PurchasesJournal").' | '.$accountingjournalstatic->getNomUrl(0, 1, 1, '', 1);
  654. $nomlink = '';
  655. $periodlink = '';
  656. $exportlink = '';
  657. $builddate = dol_now();
  658. $description .= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  659. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  660. $description .= $langs->trans("DepositsAreNotIncluded");
  661. } else {
  662. $description .= $langs->trans("DepositsAreIncluded");
  663. }
  664. $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  665. $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);
  666. $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  667. $varlink = 'id_journal='.$id_journal;
  668. journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  669. // Button to write into Ledger
  670. if (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
  671. print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  672. $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
  673. $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
  674. print $desc;
  675. print '</div>';
  676. }
  677. print '<div class="tabsAction tabsActionNoBottom">';
  678. if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') {
  679. print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
  680. }
  681. if (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
  682. print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
  683. } else {
  684. if ($in_bookkeeping == 'notyet') {
  685. print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
  686. } else {
  687. print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
  688. }
  689. }
  690. print '</div>';
  691. // TODO Avoid using js. We can use a direct link with $param
  692. print '
  693. <script type="text/javascript">
  694. function launch_export() {
  695. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  696. $("div.fiche form input[type=\"submit\"]").click();
  697. $("div.fiche form input[name=\"action\"]").val("");
  698. }
  699. function writebookkeeping() {
  700. console.log("click on writebookkeeping");
  701. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  702. $("div.fiche form input[type=\"submit\"]").click();
  703. $("div.fiche form input[name=\"action\"]").val("");
  704. }
  705. </script>';
  706. /*
  707. * Show result array
  708. */
  709. print '<br>';
  710. $i = 0;
  711. print '<div class="div-table-responsive">';
  712. print "<table class=\"noborder\" width=\"100%\">";
  713. print "<tr class=\"liste_titre\">";
  714. print "<td>".$langs->trans("Date")."</td>";
  715. print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
  716. print "<td>".$langs->trans("AccountAccounting")."</td>";
  717. print "<td>".$langs->trans("SubledgerAccount")."</td>";
  718. print "<td>".$langs->trans("LabelOperation")."</td>";
  719. print '<td class="center">'.$langs->trans("Debit")."</td>";
  720. print '<td class="center">'.$langs->trans("Credit")."</td>";
  721. print "</tr>\n";
  722. $r = '';
  723. $invoicestatic = new FactureFournisseur($db);
  724. $companystatic = new Fournisseur($db);
  725. foreach ($tabfac as $key => $val) {
  726. $companystatic->id = $tabcompany[$key]['id'];
  727. $companystatic->name = $tabcompany[$key]['name'];
  728. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  729. $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
  730. $companystatic->code_client = $tabcompany[$key]['code_client'];
  731. $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
  732. $companystatic->fournisseur = 1;
  733. $invoicestatic->id = $key;
  734. $invoicestatic->ref = $val["refsologest"];
  735. $invoicestatic->ref_supplier = $val["refsuppliersologest"];
  736. $invoicestatic->type = $val["type"];
  737. $invoicestatic->description = dol_trunc(html_entity_decode($val["description"]), 32);
  738. $invoicestatic->close_code = $val["close_code"];
  739. $date = dol_print_date($val["date"], 'day');
  740. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  741. $replacedinvoice = 0;
  742. if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
  743. $replacedinvoice = 1;
  744. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  745. if ($alreadydispatched) {
  746. $replacedinvoice = 2;
  747. }
  748. }
  749. // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
  750. if ($replacedinvoice == 1) {
  751. print '<tr class="oddeven">';
  752. print "<!-- Replaced invoice -->";
  753. print "<td>".$date."</td>";
  754. print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
  755. // Account
  756. print "<td>";
  757. print $langs->trans("Replaced");
  758. print '</td>';
  759. // Subledger account
  760. print "<td>";
  761. print '</td>';
  762. print "<td>";
  763. print "</td>";
  764. print '<td class="right"></td>';
  765. print '<td class="right"></td>';
  766. print "</tr>";
  767. continue;
  768. }
  769. if ($errorforinvoice[$key] == 'somelinesarenotbound') {
  770. print '<tr class="oddeven">';
  771. print "<!-- Some lines are not bound -->";
  772. print "<td>".$date."</td>";
  773. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  774. // Account
  775. print "<td>";
  776. print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
  777. print '</td>';
  778. // Subledger account
  779. print "<td>";
  780. print '</td>';
  781. print "<td>";
  782. print "</td>";
  783. print '<td class="right"></td>';
  784. print '<td class="right"></td>';
  785. print "</tr>";
  786. }
  787. // Third party
  788. foreach ($tabttc[$key] as $k => $mt) {
  789. print '<tr class="oddeven">';
  790. print "<!-- Thirdparty -->";
  791. print "<td>".$date."</td>";
  792. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  793. // Account
  794. print "<td>";
  795. $accountoshow = length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER);
  796. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  797. print '<span class="error">'.$langs->trans("MainAccountForSuppliersNotDefined").'</span>';
  798. } else {
  799. print $accountoshow;
  800. }
  801. print '</td>';
  802. // Subledger account
  803. print "<td>";
  804. $accountoshow = length_accounta($k);
  805. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  806. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  807. } else {
  808. print $accountoshow;
  809. }
  810. print '</td>';
  811. print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("SubledgerAccount")."</td>";
  812. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  813. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  814. print "</tr>";
  815. }
  816. // Product / Service
  817. foreach ($tabht[$key] as $k => $mt) {
  818. $accountingaccount = new AccountingAccount($db);
  819. $accountingaccount->fetch(null, $k, true);
  820. print '<tr class="oddeven">';
  821. print "<!-- Product -->";
  822. print "<td>".$date."</td>";
  823. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  824. // Account
  825. print "<td>";
  826. $accountoshow = length_accountg($k);
  827. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  828. print '<span class="error">'.$langs->trans("ProductAccountNotDefined").'</span>';
  829. } else {
  830. print $accountoshow;
  831. }
  832. print "</td>";
  833. // Subledger account
  834. print "<td>";
  835. print '</td>';
  836. $companystatic->id = $tabcompany[$key]['id'];
  837. $companystatic->name = $tabcompany[$key]['name'];
  838. print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$accountingaccount->label."</td>";
  839. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  840. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  841. print "</tr>";
  842. }
  843. // VAT
  844. $listoftax = array(0, 1, 2);
  845. foreach ($listoftax as $numtax) {
  846. $arrayofvat = $tabtva;
  847. if ($numtax == 1) {
  848. $arrayofvat = $tablocaltax1;
  849. }
  850. if ($numtax == 2) {
  851. $arrayofvat = $tablocaltax2;
  852. }
  853. foreach ($arrayofvat[$key] as $k => $mt) {
  854. if ($mt) {
  855. print '<tr class="oddeven">';
  856. print "<!-- VAT -->";
  857. print "<td>".$date."</td>";
  858. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  859. // Account
  860. print "<td>";
  861. $accountoshow = length_accountg($k);
  862. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  863. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Purchase").')</span>';
  864. } else {
  865. print $accountoshow;
  866. }
  867. print "</td>";
  868. // Subledger account
  869. print "<td>";
  870. print '</td>';
  871. print "<td>";
  872. print $companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
  873. print "</td>";
  874. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  875. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  876. print "</tr>";
  877. }
  878. }
  879. }
  880. // VAT counterpart for NPR
  881. if (is_array($tabother[$key])) {
  882. foreach ($tabother[$key] as $k => $mt) {
  883. if ($mt) {
  884. print '<tr class="oddeven">';
  885. print '<!-- VAT counterpart NPR -->';
  886. print "<td>".$date."</td>";
  887. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  888. // Account
  889. print '<td>';
  890. $accountoshow = length_accountg($k);
  891. if ($accountoshow == '' || $accountoshow == 'NotDefined') {
  892. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("NPR counterpart").'). Set ACCOUNTING_COUNTERPART_VAT_NPR to the subvention account</span>';
  893. } else {
  894. print $accountoshow;
  895. }
  896. print '</td>';
  897. // Subledger account
  898. print "<td>";
  899. print '</td>';
  900. print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT")." NPR (counterpart)</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. }
  905. }
  906. }
  907. }
  908. print "</table>";
  909. print '</div>';
  910. // End of page
  911. llxFooter();
  912. }
  913. $db->close();