sellsjournal.php 43 KB

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