sellsjournal.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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-2023 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 (!$user->hasRight('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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
  133. $sql .= " AND f.datef >= '".$db->idate(getDolGlobalString('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 = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER', 'NotDefined');
  161. $cpttva = getDolGlobalString('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 = getDolGlobalString('ACCOUNTING_PRODUCT_SOLD_ACCOUNT', 'NotDefined');
  171. } else {
  172. $compta_prod = getDolGlobalString('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 (getDolGlobalString('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, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), true);
  279. $accountingaccountcustomerwarranty = new AccountingAccount($db);
  280. $accountingaccountcustomerwarranty->fetch(null, getDolGlobalString('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 = getDolGlobalString('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 = getDolGlobalString('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. }
  405. }
  406. }
  407. }
  408. // Product / Service
  409. if (!$errorforline) {
  410. foreach ($tabht[$key] as $k => $mt) {
  411. $resultfetch = $accountingaccount->fetch(null, $k, true); // TODO Use a cache
  412. $label_account = $accountingaccount->label;
  413. // get compte id and label
  414. if ($resultfetch > 0) {
  415. $bookkeeping = new BookKeeping($db);
  416. $bookkeeping->doc_date = $val["date"];
  417. $bookkeeping->date_lim_reglement = $val["datereg"];
  418. $bookkeeping->doc_ref = $val["ref"];
  419. $bookkeeping->date_creation = $now;
  420. $bookkeeping->doc_type = 'customer_invoice';
  421. $bookkeeping->fk_doc = $key;
  422. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  423. $bookkeeping->thirdparty_code = $companystatic->code_client;
  424. if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
  425. if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
  426. $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
  427. $bookkeeping->subledger_label = $tabcompany[$key]['name'];
  428. } else {
  429. $bookkeeping->subledger_account = '';
  430. $bookkeeping->subledger_label = '';
  431. }
  432. } else {
  433. $bookkeeping->subledger_account = '';
  434. $bookkeeping->subledger_label = '';
  435. }
  436. $bookkeeping->numero_compte = $k;
  437. $bookkeeping->label_compte = $label_account;
  438. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$label_account;
  439. $bookkeeping->montant = $mt;
  440. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  441. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  442. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  443. $bookkeeping->code_journal = $journal;
  444. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  445. $bookkeeping->fk_user_author = $user->id;
  446. $bookkeeping->entity = $conf->entity;
  447. $totaldebit += $bookkeeping->debit;
  448. $totalcredit += $bookkeeping->credit;
  449. $result = $bookkeeping->create($user);
  450. if ($result < 0) {
  451. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  452. $error++;
  453. $errorforline++;
  454. $errorforinvoice[$key] = 'alreadyjournalized';
  455. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  456. } else {
  457. $error++;
  458. $errorforline++;
  459. $errorforinvoice[$key] = 'other';
  460. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  461. }
  462. }
  463. }
  464. }
  465. }
  466. // VAT
  467. if (!$errorforline) {
  468. $listoftax = array(0, 1, 2);
  469. foreach ($listoftax as $numtax) {
  470. $arrayofvat = $tabtva;
  471. if ($numtax == 1) {
  472. $arrayofvat = $tablocaltax1;
  473. }
  474. if ($numtax == 2) {
  475. $arrayofvat = $tablocaltax2;
  476. }
  477. foreach ($arrayofvat[$key] as $k => $mt) {
  478. if ($mt) {
  479. $accountingaccount->fetch(null, $k, true); // TODO Use a cache for label
  480. $label_account = $accountingaccount->label;
  481. $bookkeeping = new BookKeeping($db);
  482. $bookkeeping->doc_date = $val["date"];
  483. $bookkeeping->date_lim_reglement = $val["datereg"];
  484. $bookkeeping->doc_ref = $val["ref"];
  485. $bookkeeping->date_creation = $now;
  486. $bookkeeping->doc_type = 'customer_invoice';
  487. $bookkeeping->fk_doc = $key;
  488. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  489. $bookkeeping->thirdparty_code = $companystatic->code_client;
  490. $bookkeeping->subledger_account = '';
  491. $bookkeeping->subledger_label = '';
  492. $bookkeeping->numero_compte = $k;
  493. $bookkeeping->label_compte = $label_account;
  494. $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
  495. $bookkeeping->montant = $mt;
  496. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  497. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  498. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  499. $bookkeeping->code_journal = $journal;
  500. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  501. $bookkeeping->fk_user_author = $user->id;
  502. $bookkeeping->entity = $conf->entity;
  503. $totaldebit += $bookkeeping->debit;
  504. $totalcredit += $bookkeeping->credit;
  505. $result = $bookkeeping->create($user);
  506. if ($result < 0) {
  507. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  508. $error++;
  509. $errorforline++;
  510. $errorforinvoice[$key] = 'alreadyjournalized';
  511. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  512. } else {
  513. $error++;
  514. $errorforline++;
  515. $errorforinvoice[$key] = 'other';
  516. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  517. }
  518. }
  519. }
  520. }
  521. }
  522. }
  523. // Protection against a bug on lines before
  524. if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
  525. $error++;
  526. $errorforline++;
  527. $errorforinvoice[$key] = 'amountsnotbalanced';
  528. setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
  529. }
  530. if (!$errorforline) {
  531. $db->commit();
  532. } else {
  533. $db->rollback();
  534. if ($error >= 10) {
  535. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
  536. break; // Break in the foreach
  537. }
  538. }
  539. }
  540. $tabpay = $tabfac;
  541. if (empty($error) && count($tabpay) > 0) {
  542. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  543. } elseif (count($tabpay) == $error) {
  544. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  545. } else {
  546. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  547. }
  548. $action = '';
  549. // Must reload data, so we make a redirect
  550. if (count($tabpay) != $error) {
  551. $param = 'id_journal='.$id_journal;
  552. $param .= '&date_startday='.$date_startday;
  553. $param .= '&date_startmonth='.$date_startmonth;
  554. $param .= '&date_startyear='.$date_startyear;
  555. $param .= '&date_endday='.$date_endday;
  556. $param .= '&date_endmonth='.$date_endmonth;
  557. $param .= '&date_endyear='.$date_endyear;
  558. $param .= '&in_bookkeeping='.$in_bookkeeping;
  559. header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
  560. exit;
  561. }
  562. }
  563. /*
  564. * View
  565. */
  566. $form = new Form($db);
  567. // Export
  568. if ($action == 'exportcsv') { // ISO and not UTF8 !
  569. $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
  570. $filename = 'journal';
  571. $type_export = 'journal';
  572. include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
  573. $companystatic = new Client($db);
  574. $invoicestatic = new Facture($db);
  575. foreach ($tabfac as $key => $val) {
  576. $companystatic->id = $tabcompany[$key]['id'];
  577. $companystatic->name = $tabcompany[$key]['name'];
  578. $companystatic->code_compta = $tabcompany[$key]['code_compta']; // deprecated
  579. $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
  580. $companystatic->code_client = $tabcompany[$key]['code_client'];
  581. $companystatic->client = 3;
  582. $invoicestatic->id = $key;
  583. $invoicestatic->ref = (string) $val["ref"];
  584. $invoicestatic->type = $val["type"];
  585. $invoicestatic->close_code = $val["close_code"];
  586. $date = dol_print_date($val["date"], 'day');
  587. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  588. $replacedinvoice = 0;
  589. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
  590. $replacedinvoice = 1;
  591. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  592. if ($alreadydispatched) {
  593. $replacedinvoice = 2;
  594. }
  595. }
  596. // 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)
  597. if ($replacedinvoice == 1) {
  598. continue;
  599. }
  600. // Warranty
  601. foreach ($tabwarranty[$key] as $k => $mt) {
  602. //if ($mt) {
  603. print '"'.$key.'"'.$sep;
  604. print '"'.$date.'"'.$sep;
  605. print '"'.$val["ref"].'"'.$sep;
  606. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  607. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  608. print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY')).'"'.$sep;
  609. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  610. print '"'.$langs->trans("Thirdparty").'"'.$sep;
  611. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty").'"'.$sep;
  612. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  613. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  614. print '"'.$journal.'"';
  615. print "\n";
  616. //}
  617. }
  618. // Third party
  619. foreach ($tabttc[$key] as $k => $mt) {
  620. //if ($mt) {
  621. print '"'.$key.'"'.$sep;
  622. print '"'.$date.'"'.$sep;
  623. print '"'.$val["ref"].'"'.$sep;
  624. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  625. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  626. print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER')).'"'.$sep;
  627. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  628. print '"'.$langs->trans("Thirdparty").'"'.$sep;
  629. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Thirdparty").'"'.$sep;
  630. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  631. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  632. print '"'.$journal.'"';
  633. print "\n";
  634. //}
  635. }
  636. // Product / Service
  637. foreach ($tabht[$key] as $k => $mt) {
  638. $accountingaccount = new AccountingAccount($db);
  639. $accountingaccount->fetch(null, $k, true);
  640. //if ($mt) {
  641. print '"'.$key.'"'.$sep;
  642. print '"'.$date.'"'.$sep;
  643. print '"'.$val["ref"].'"'.$sep;
  644. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  645. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  646. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  647. print '""'.$sep;
  648. print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
  649. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep;
  650. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  651. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  652. print '"'.$journal.'"';
  653. print "\n";
  654. //}
  655. }
  656. // VAT
  657. $listoftax = array(0, 1, 2);
  658. foreach ($listoftax as $numtax) {
  659. $arrayofvat = $tabtva;
  660. if ($numtax == 1) {
  661. $arrayofvat = $tablocaltax1;
  662. }
  663. if ($numtax == 2) {
  664. $arrayofvat = $tablocaltax2;
  665. }
  666. foreach ($arrayofvat[$key] as $k => $mt) {
  667. if ($mt) {
  668. print '"'.$key.'"'.$sep;
  669. print '"'.$date.'"'.$sep;
  670. print '"'.$val["ref"].'"'.$sep;
  671. print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
  672. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  673. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  674. print '""'.$sep;
  675. print '"'.$langs->trans("VAT").' - '.join(', ', $def_tva[$key][$k]).' %"'.$sep;
  676. print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep;
  677. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  678. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  679. print '"'.$journal.'"';
  680. print "\n";
  681. }
  682. }
  683. }
  684. }
  685. }
  686. if (empty($action) || $action == 'view') {
  687. $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
  688. llxHeader('', dol_string_nohtmltag($title));
  689. $nom = $title;
  690. $nomlink = '';
  691. $periodlink = '';
  692. $exportlink = '';
  693. $builddate = dol_now();
  694. $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  695. if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
  696. $description .= $langs->trans("DepositsAreNotIncluded");
  697. } else {
  698. $description .= $langs->trans("DepositsAreIncluded");
  699. }
  700. $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  701. $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);
  702. $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  703. $varlink = 'id_journal='.$id_journal;
  704. journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  705. // Button to write into Ledger
  706. $acctCustomerNotConfigured = in_array(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), ['','-1']);
  707. if ($acctCustomerNotConfigured) {
  708. print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  709. $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
  710. $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
  711. print $desc;
  712. print '</div>';
  713. }
  714. print '<div class="tabsAction tabsActionNoBottom centerimp">';
  715. if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL') && $in_bookkeeping == 'notyet') {
  716. print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
  717. }
  718. if ($acctCustomerNotConfigured) {
  719. print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
  720. } else {
  721. if ($in_bookkeeping == 'notyet') {
  722. print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
  723. } else {
  724. print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
  725. }
  726. }
  727. print '</div>';
  728. // TODO Avoid using js. We can use a direct link with $param
  729. print '
  730. <script type="text/javascript">
  731. function launch_export() {
  732. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  733. $("div.fiche form input[type=\"submit\"]").click();
  734. $("div.fiche form input[name=\"action\"]").val("");
  735. }
  736. function writebookkeeping() {
  737. console.log("click on writebookkeeping");
  738. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  739. $("div.fiche form input[type=\"submit\"]").click();
  740. $("div.fiche form input[name=\"action\"]").val("");
  741. }
  742. </script>';
  743. /*
  744. * Show result array
  745. */
  746. print '<br>';
  747. print '<div class="div-table-responsive">';
  748. print "<table class=\"noborder\" width=\"100%\">";
  749. print "<tr class=\"liste_titre\">";
  750. print "<td>".$langs->trans("Date")."</td>";
  751. print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
  752. print "<td>".$langs->trans("AccountAccounting")."</td>";
  753. print "<td>".$langs->trans("SubledgerAccount")."</td>";
  754. print "<td>".$langs->trans("LabelOperation")."</td>";
  755. print '<td class="center">'.$langs->trans("AccountingDebit")."</td>";
  756. print '<td class="center">'.$langs->trans("AccountingCredit")."</td>";
  757. print "</tr>\n";
  758. $i = 0;
  759. $companystatic = new Client($db);
  760. $invoicestatic = new Facture($db);
  761. foreach ($tabfac as $key => $val) {
  762. $companystatic->id = $tabcompany[$key]['id'];
  763. $companystatic->name = $tabcompany[$key]['name'];
  764. $companystatic->code_compta = $tabcompany[$key]['code_compta'];
  765. $companystatic->code_client = $tabcompany[$key]['code_client'];
  766. $companystatic->client = 3;
  767. $invoicestatic->id = $key;
  768. $invoicestatic->ref = (string) $val["ref"];
  769. $invoicestatic->type = $val["type"];
  770. $invoicestatic->close_code = $val["close_code"];
  771. $date = dol_print_date($val["date"], 'day');
  772. // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
  773. $replacedinvoice = 0;
  774. if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
  775. $replacedinvoice = 1;
  776. $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
  777. if ($alreadydispatched) {
  778. $replacedinvoice = 2;
  779. }
  780. }
  781. // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
  782. if ($replacedinvoice == 1) {
  783. print '<tr class="oddeven">';
  784. print "<!-- Replaced invoice -->";
  785. print "<td>".$date."</td>";
  786. print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
  787. // Account
  788. print "<td>";
  789. print $langs->trans("Replaced");
  790. print '</td>';
  791. // Subledger account
  792. print "<td>";
  793. print '</td>';
  794. print "<td>";
  795. print "</td>";
  796. print '<td class="right"></td>';
  797. print '<td class="right"></td>';
  798. print "</tr>";
  799. $i++;
  800. continue;
  801. }
  802. if ($errorforinvoice[$key] == 'somelinesarenotbound') {
  803. print '<tr class="oddeven">';
  804. print "<!-- Some lines are not bound -->";
  805. print "<td>".$date."</td>";
  806. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  807. // Account
  808. print "<td>";
  809. print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
  810. print '</td>';
  811. // Subledger account
  812. print "<td>";
  813. print '</td>';
  814. print "<td>";
  815. print "</td>";
  816. print '<td class="right"></td>';
  817. print '<td class="right"></td>';
  818. print "</tr>";
  819. $i++;
  820. }
  821. // Warranty
  822. foreach ($tabwarranty[$key] as $k => $mt) {
  823. print '<tr class="oddeven">';
  824. print "<!-- Thirdparty warranty -->";
  825. print "<td>".$date."</td>";
  826. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  827. // Account
  828. print "<td>";
  829. $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'));
  830. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  831. print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
  832. } else {
  833. print $accountoshow;
  834. }
  835. print '</td>';
  836. // Subledger account
  837. print "<td>";
  838. $accountoshow = length_accounta($k);
  839. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  840. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  841. } else {
  842. print $accountoshow;
  843. }
  844. print '</td>';
  845. print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty")."</td>";
  846. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  847. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  848. print "</tr>";
  849. }
  850. // Third party
  851. foreach ($tabttc[$key] as $k => $mt) {
  852. print '<tr class="oddeven">';
  853. print "<!-- Thirdparty -->";
  854. print "<td>".$date."</td>";
  855. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  856. // Account
  857. print "<td>";
  858. $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'));
  859. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  860. print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
  861. } else {
  862. print $accountoshow;
  863. }
  864. print '</td>';
  865. // Subledger account
  866. print "<td>";
  867. $accountoshow = length_accounta($k);
  868. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  869. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  870. } else {
  871. print $accountoshow;
  872. }
  873. print '</td>';
  874. print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("SubledgerAccount")."</td>";
  875. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  876. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  877. print "</tr>";
  878. $i++;
  879. }
  880. // Product / Service
  881. foreach ($tabht[$key] as $k => $mt) {
  882. $accountingaccount = new AccountingAccount($db);
  883. $accountingaccount->fetch(null, $k, true);
  884. print '<tr class="oddeven">';
  885. print "<!-- Product -->";
  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("ProductNotDefined").'</span>';
  893. } else {
  894. print $accountoshow;
  895. }
  896. print "</td>";
  897. // Subledger account
  898. print "<td>";
  899. if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
  900. if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
  901. print length_accounta($tabcompany[$key]['code_compta']);
  902. }
  903. } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
  904. print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
  905. }
  906. print '</td>';
  907. $companystatic->id = $tabcompany[$key]['id'];
  908. $companystatic->name = $tabcompany[$key]['name'];
  909. print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$accountingaccount->label."</td>";
  910. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  911. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  912. print "</tr>";
  913. $i++;
  914. }
  915. // VAT
  916. $listoftax = array(0, 1, 2);
  917. foreach ($listoftax as $numtax) {
  918. $arrayofvat = $tabtva;
  919. if ($numtax == 1) {
  920. $arrayofvat = $tablocaltax1;
  921. }
  922. if ($numtax == 2) {
  923. $arrayofvat = $tablocaltax2;
  924. }
  925. foreach ($arrayofvat[$key] as $k => $mt) {
  926. if ($mt) {
  927. print '<tr class="oddeven">';
  928. print "<!-- VAT -->";
  929. print "<td>".$date."</td>";
  930. print "<td>".$invoicestatic->getNomUrl(1)."</td>";
  931. // Account
  932. print "<td>";
  933. $accountoshow = length_accountg($k);
  934. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  935. print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')</span>';
  936. } else {
  937. print $accountoshow;
  938. }
  939. print "</td>";
  940. // Subledger account
  941. print "<td>";
  942. print '</td>';
  943. print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
  944. print "</td>";
  945. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  946. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  947. print "</tr>";
  948. $i++;
  949. }
  950. }
  951. }
  952. }
  953. if (!$i) {
  954. print '<tr class="oddeven"><td colspan="6"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
  955. }
  956. print "</table>";
  957. print '</div>';
  958. // End of page
  959. llxFooter();
  960. }
  961. $db->close();